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 21:21:19 UTC
[01/50] [abbrv] git commit: Fixes information in pom.xml
Updated Branches:
refs/heads/optimistic-tx-semantics c04f49d9b -> 1d06007c3
refs/heads/two-dot-o 528afe5ad -> 2f786ebac
Fixes information in pom.xml
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/ad8d78f0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/ad8d78f0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/ad8d78f0
Branch: refs/heads/optimistic-tx-semantics
Commit: ad8d78f089cfcc31f576c14d6b7745cde28833b9
Parents: c18448c
Author: Sungju Jin <su...@softwaregeeks.org>
Authored: Sun Feb 9 13:45:22 2014 +0900
Committer: Sungju Jin <su...@softwaregeeks.org>
Committed: Sun Feb 9 13:45:22 2014 +0900
----------------------------------------------------------------------
stack/pom.xml | 16 +++++++++++++---
1 file changed, 13 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/ad8d78f0/stack/pom.xml
----------------------------------------------------------------------
diff --git a/stack/pom.xml b/stack/pom.xml
index 8bc7fdc..52dbaa8 100644
--- a/stack/pom.xml
+++ b/stack/pom.xml
@@ -108,6 +108,16 @@
</license>
</licenses>
+ <organization>
+ <name>The Apache Software Foundation</name>
+ <url>http://www.apache.org/</url>
+ </organization>
+
+ <issueManagement>
+ <system>Jira</system>
+ <url>https://issues.apache.org/jira/browse/USERGRID</url>
+ </issueManagement>
+
<developers>
<developer>
<id>eanuff</id>
@@ -136,9 +146,9 @@
</developers>
<scm>
- <connection>scm:git:git@github.com:apigee/usergrid-stack-internal.git</connection>
- <developerConnection>scm:git:git@github.com:apigee/usergrid-stack-internal.git</developerConnection>
- <url>git@github.com:apigee/usergrid-stack-internal.git</url>
+ <connection>scm:git:git@github.com:usergrid/usergrid.git</connection>
+ <developerConnection>scm:git:git@github.com:usergrid/usergrid.git</developerConnection>
+ <url>https://github.com/usergrid/usergrid</url>
</scm>
<distributionManagement>
[49/50] [abbrv] Merge branch 'two-dot-o' into optimistic-tx-semantics
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/1d06007c/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
----------------------------------------------------------------------
diff --cc stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
index aed8d22,e0744c3..2837255
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
@@@ -26,11 -27,8 +26,10 @@@ import org.apache.usergrid.persistence.
import org.apache.usergrid.persistence.collection.impl.EntityCollectionManagerImpl;
import org.apache.usergrid.persistence.collection.impl.EntityCollectionManagerSyncImpl;
import org.apache.usergrid.persistence.collection.migration.MigrationManagerFig;
+import org.apache.usergrid.persistence.collection.mvcc.MvccEntitySerializationStrategy;
+import org.apache.usergrid.persistence.collection.mvcc.MvccLogEntrySerializationStrategy;
import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategy;
import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategyImpl;
- import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteFig;
import org.apache.usergrid.persistence.collection.rx.CassandraThreadScheduler;
import org.apache.usergrid.persistence.collection.rx.RxFig;
import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
@@@ -56,14 -56,9 +55,13 @@@ public class CollectionModule extends A
RxFig.class,
MigrationManagerFig.class,
CassandraFig.class,
- SerializationFig.class,
- WriteFig.class ) );
+ SerializationFig.class ) );
install( new SerializationModule() );
+ bind( MvccEntitySerializationStrategy.class ).to( MvccEntitySerializationStrategyImpl.class );
+ bind( MvccLogEntrySerializationStrategy.class ).to( MvccLogEntrySerializationStrategyImpl.class );
+ bind( UniqueValueSerializationStrategy.class ).to( UniqueValueSerializationStrategyImpl.class );
+
install( new ServiceModule() );
// create a guice factor for getting our collection manager
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/1d06007c/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
----------------------------------------------------------------------
diff --cc stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
index f8c77f0,2586285..7895552
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
@@@ -39,10 -40,15 +38,12 @@@ import org.apache.usergrid.persistence.
import org.apache.usergrid.persistence.collection.util.EntityUtils;
import org.apache.usergrid.persistence.model.entity.Entity;
import org.apache.usergrid.persistence.model.entity.Id;
-
-import com.google.common.base.Preconditions;
-import com.google.inject.Inject;
-import com.google.inject.assistedinject.Assisted;
-
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Scheduler;
+ import rx.util.functions.Func1;
+ import rx.util.functions.Func2;
import rx.util.functions.FuncN;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/1d06007c/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
----------------------------------------------------------------------
diff --cc stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
index 9f741dc,20dfa91..a5d360a
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
@@@ -62,18 -103,19 +103,19 @@@ public class WriteUniqueVerifyTest
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( null, uniqueValueSerializiationStrategy );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uvstrat, scheduler, fig );
- CollectionIoEvent<MvccEntity>
- result = newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) );
+ CollectionIoEvent<MvccEntity> result = newStage.call(
+ new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) )
+ .toBlockingObservable().last();
- assertSame("Context was correct", collectionScope, result.getEntityCollection()) ;
+ assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
- // verify the log entry is correct
+ // verify the entity is correct
MvccEntity entry = result.getEvent();
- // verify uuid and version in both the MvccEntity and the entity itself
- // assertSame is used on purpose. We want to make sure the same instance is used, not a copy.
+ // verify uuid and version in both the MvccEntity and the entity itself. assertSame is
+ // used on purpose. We want to make sure the same instance is used, not a copy.
// this way the caller's runtime type is retained.
assertSame( "id correct", entity.getId(), entry.getId() );
assertSame( "version did not not match entityId", entity.getVersion(), entry.getVersion() );
[04/50] [abbrv] fixing issues in test cases
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index 8b2774b..f5e01f2 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
-/*! usergrid@0.0.0 2014-02-06 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;if(isFunction(callback)){params||(params=[]),context||(context=this),params.push(context);try{returnValue=callback.apply(context,params)}catch(ex){console&&console.error&&console.error("Callback error:",ex)}}return returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventabl
e.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.ini
t(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&c
onsole[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new
Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)})
,p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){var exports,name="Ajax",global=this,overwrittenName=global[name];return Function.prototype.partial=function(){var fn=this,b=[].slice.call(arguments);return fn.bind(void 0,b)},exports=function(){function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}this.logger=new global.Logger(name);var self=this,request=function(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),self.logger.timeEnd(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.info("%s
request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&(xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),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}(),global[name]=exports,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is no
t a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return
this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];ret
urn Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint),api_uri,orgName,appName),new UsergridError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Request.prototype.validate=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.prepare=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.fire=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(th
is.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.Client=function(options){this.logger=new global.Logger("Usergrid.Client");this.getStorage(),this.set("api_uri",options.URI||"https://api.usergrid.com"),this.set("orgName",options.orgName),this.set("appName",options.appName),this.set("buildCurl",options.buildCurl||!1),this.set("logging",options.logging||!1)},UsergridStorable.mixin(Usergrid.Client),UsergridEventable.mixin(Usergrid.Client),Usergrid.Client.prototype.buildAssetURL=function(uuid){var qs={},uri_elements=this.get("api_uri","orgName","appName");uri_elements=uri_elements.concat(["assets",uuid,"data"]);var assetURL=uri_elements.join("/"),token=this.getToken();token&&(qs.access_token=token);var encoded_params=encodeParams(qs);return encoded_params&&(assetUR
L+="?"+encoded_params),assetURL},Usergrid.Client.prototype.buildEndpointURL=function(endpoint,qs){qs=qs||{};var endSlashes=/(^\/|\/$)/g,assetURL=[endpoint.replace(endSlashes,"")].concat(this.get("api_uri","orgName","appName")),token=this.getToken();token&&(qs.access_token=token);var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.request=function(options,callback){var p=new Promise;this.logger=new Logger("Request");var method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},api_uri=(options.mQuery||!1,this.get("api_uri")),orgName=this.get("orgName"),appName=this.get("appName");this.getToken()&&(qs.access_token=this.getToken()),endpoint=api_uri&&orgName&&appName?[api_uri,orgName,appName,endpoint].join("/"):[api_uri,endpoint].join("/");new Usergrid.Request(method,endpoint,qs,body,function(err,response){-1!==["auth_expired_session_token","auth_missing_credentials","auth_unve
rified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error),doCallback(callback,[err,response]),p.done(err,response)});return p},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){console.log(err,data);var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=err.name&&-1!==common_errors.indexOf(err.name)||!err&&getOnExist;okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=funct
ion(serializedObject){return new Usergrid.Entity({client:this,data:JSON.parse(serializedObject)})},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){"function"==typeof callback&&callback(err,collection,data)})},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return
c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var se
lf=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"],options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("A
FTER FETCH",self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/
"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data.entities.length,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:s
elf[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].create
dDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err
,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client
.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&
console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);
this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callba
ck(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.ty
pe=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{t
ype:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&th
is._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._dat
a=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOption
s);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){
err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)
-})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype
=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,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,da
ta){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("
self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new Usergrid.Error(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new Usergrid.Error(data)],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},
Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new Usergrid.Error("folder not specified")],self)},Usergrid.As
set.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new Usergrid.Error("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new Usergrid.Error("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new Usergrid.Error(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client
.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new Usergrid.Error(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message
,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},
UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+/*! usergrid@0.0.0 2014-02-10 */
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){console.info("CALLED FROM",this.name||context?context.name:"UNKNOWN");var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prot
otype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name
,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console
[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promi
se},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},gl
obal[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(fn){var args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(this,args.concat(Array.prototype.slice(arguments,0)))}}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),self.logger.timeEnd(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&(xhr.setRequestHeader("Conten
t-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setSt
orage' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(to
ken){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","
DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeE
nd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Request.prototype.validate=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.prepare=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.fire=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),thi
s),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"
GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName");if(!mQuery&&!orgName&&!appName&&"function"==typeof this.logoutCallback)return this.logoutCallback(!0,"no_org_or_app_name_specified");uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error),doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.proto
type.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data]
)})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,funct
ion(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",tok
en)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Clie
nt.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),Usergrid.Entity=function(options){options&&(this._data=opt
ions.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),namePropertie
s=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"],options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA
#2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);i
f(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callb
ack){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._c
lient.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].c
reatedDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback)
{var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="n
o";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log(
"entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return d
ata=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;
+var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._typ
e;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),this.removeEntity(entity)},Usergrid.Collection.prototype.removeEntity=function(en
tity){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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._li
st.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collectio
n.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(er
r&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/us
ers/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callb
ack(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, de
crement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callb
ack,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new Usergrid.Error(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"str
ing":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new Usergrid.Error(data)],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(
callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergri
d.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new Usergrid.Error("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new Usergrid.Error("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new Usergrid.Error("The
File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new Usergrid.Error(JSON.parse(xhr.responseText))],self):doCallback(callback,[null,self],self)};var fr=new FileReader;
<TRUNCATED>
[47/50] [abbrv] git commit: Break WriteUniqueVerify tests into two
classes, one that uses Theories and one that uses Jukito.
Posted by sn...@apache.org.
Break WriteUniqueVerify tests into two classes, one that uses Theories and one that uses Jukito.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/2f786eba
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/2f786eba
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/2f786eba
Branch: refs/heads/optimistic-tx-semantics
Commit: 2f786ebac2f9743bb3fe8fecd4df24fc7a3793be
Parents: 528afe5
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 14:51:09 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 14:51:09 2014 -0500
----------------------------------------------------------------------
.../mvcc/stage/write/WriteUniqueVerify.java | 54 +++++++++-----------
.../changelog/ChangeLogGeneratorImplTest.java | 4 +-
.../stage/write/WriteUniqueVerifyStageTest.java | 49 ++++++++++++++++++
.../mvcc/stage/write/WriteUniqueVerifyTest.java | 46 ++++++++++-------
.../util/InvalidValueGeneratorTest.java | 48 +++++++++++++++++
5 files changed, 152 insertions(+), 49 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
index 370fd0a..32dc577 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
@@ -48,7 +48,8 @@ import rx.util.functions.FuncN;
* This phase execute all unique value verification on the MvccEntity.
*/
@Singleton
-public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, Observable<? extends CollectionIoEvent<MvccEntity>>> {
+public class WriteUniqueVerify implements
+ Func1<CollectionIoEvent<MvccEntity>, Observable<? extends CollectionIoEvent<MvccEntity>>> {
private static final Logger LOG = LoggerFactory.getLogger( WriteUniqueVerify.class );
@@ -61,64 +62,58 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
@Inject
- public WriteUniqueVerify( final UniqueValueSerializationStrategy uniqueValueSerializiationStrategy,
+ public WriteUniqueVerify( final UniqueValueSerializationStrategy uvstrat,
final Scheduler scheduler, final SerializationFig serializationFig ) {
- Preconditions.checkNotNull( uniqueValueSerializiationStrategy, "uniqueValueSerializationStrategy is required" );
+ Preconditions.checkNotNull( uvstrat, "uniqueValueSerializationStrategy is required" );
Preconditions.checkNotNull( scheduler, "scheduler is required" );
Preconditions.checkNotNull( serializationFig, "serializationFig is required" );
- this.uniqueValueStrat = uniqueValueSerializiationStrategy;
+ this.uniqueValueStrat = uvstrat;
this.scheduler = scheduler;
this.serializationFig = serializationFig;
}
@Override
- public Observable<? extends CollectionIoEvent<MvccEntity>> call(final CollectionIoEvent<MvccEntity> ioevent ) {
+ public Observable<? extends CollectionIoEvent<MvccEntity>> call(
+ final CollectionIoEvent<MvccEntity> ioevent ) {
ValidationUtils.verifyMvccEntityWithEntity( ioevent.getEvent() );
final Entity entity = ioevent.getEvent().getEntity().get();
- // use simple thread pool to verify fields in parallel
-
- //TODO Dave: We don't want to use custom thread pools and futures here.
- // We want to use concurrent to fork all validations this way they're wrapped by timeouts and
- // Hystrix thread pools for JMX operations. See the WriteCommand in the EntityCollectionManagerImpl
- // I think it still needs added to the Concurrent utility class
-
-
final List<Observable<FieldUniquenessResult>> fields =
new ArrayList<Observable<FieldUniquenessResult>>();
-
-
- /**
- * Construct all the functions for verifying we're unique
- */
+ // Construct all the functions for verifying we're unique
for ( final Field field : entity.getFields() ) {
- //if it's unique, create a function to validate it and add it to the list of concurrent validations
- if ( !field.isUnique() ) {
+ // if it's unique, add a function to validate it
+ if ( field.isUnique() ) {
+
+ Observable<FieldUniquenessResult> result =
+ Observable.from( field ).subscribeOn( scheduler )
+ .map(new Func1<Field, FieldUniquenessResult>() {
- Observable<FieldUniquenessResult> result = Observable.from( field ).subscribeOn( scheduler ).map(new Func1<Field, FieldUniquenessResult>() {
@Override
public FieldUniquenessResult call(Field field ) {
// use write-first then read strategy
- UniqueValue written = new UniqueValueImpl( ioevent.getEntityCollection(), field, entity.getId(),
+ UniqueValue written = new UniqueValueImpl(
+ ioevent.getEntityCollection(), field, entity.getId(),
entity.getVersion() );
// use TTL in case something goes wrong before entity is finally committed
- MutationBatch mb = uniqueValueStrat.write( written, serializationFig.getTimeout() );
+ MutationBatch mb = uniqueValueStrat.write(
+ written, serializationFig.getTimeout() );
try {
mb.execute();
}
catch ( ConnectionException ex ) {
- throw new CollectionRuntimeException( "Error writing unique value " + field.toString(),
- ex );
+ throw new CollectionRuntimeException(
+ "Error writing unique value " + field.toString(), ex );
}
// does the database value match what we wrote?
@@ -146,12 +141,12 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
/**
* Zip the results up
*/
- final FuncN<CollectionIoEvent<MvccEntity>> zipFunction = new FuncN<CollectionIoEvent<MvccEntity>>() {
+ final FuncN<CollectionIoEvent<MvccEntity>> zipFunction =
+ new FuncN<CollectionIoEvent<MvccEntity>>() {
+
@Override
public CollectionIoEvent<MvccEntity> call( final Object... args ) {
-
-
for ( Object resultObj : args ) {
FieldUniquenessResult result = ( FieldUniquenessResult ) resultObj;
@@ -159,7 +154,8 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
if ( !result.isUnique() ) {
Field field = result.getField();
throw new CollectionRuntimeException(
- "Duplicate field value " + field.getName() + " = " + field.getValue().toString() );
+ "Duplicate field value " + field.getName()
+ + " = " + field.getValue().toString() );
}
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
index d64cc44..db79739 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
@@ -78,8 +78,8 @@ public class ChangeLogGeneratorImplTest {
/**
* Test that change log creation follows Todd's example.
- * TODO, can we do this without doing serialization I/O on the entities? This seems out of the scope of the changelog
- * itself
+ * TODO, can we do this without doing serialization I/O on the entities?
+ * This seems out of the scope of the changelog itself
*/
@Test
public void testBasicOperation() throws ConnectionException {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
new file mode 100644
index 0000000..78b7d13
--- /dev/null
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.usergrid.persistence.collection.mvcc.stage.write;
+
+
+import org.jukito.UseModules;
+
+import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
+import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
+import org.apache.usergrid.persistence.collection.mvcc.stage.AbstractMvccEntityStageTest;
+import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
+import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
+import static org.mockito.Mockito.mock;
+import rx.Scheduler;
+
+
+/**
+ * TODO: Update the test to correctly test for detecting more than 1 duplicate and exception handling correctly
+ *
+ * @author tnine
+ */
+@UseModules( TestCollectionModule.class )
+public class WriteUniqueVerifyStageTest extends AbstractMvccEntityStageTest {
+
+ @Override
+ protected void validateStage( final CollectionIoEvent<MvccEntity> event ) {
+ UniqueValueSerializationStrategy uvstrat = mock( UniqueValueSerializationStrategy.class );
+ Scheduler scheduler = mock( Scheduler.class );
+ SerializationFig fig = mock( SerializationFig.class );
+ new WriteUniqueVerify( uvstrat, scheduler, fig ).call( event );
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
index da16a21..20dfa91 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
@@ -14,6 +14,22 @@
* limitations under the License. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
+ *//*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
*/
package org.apache.usergrid.persistence.collection.mvcc.stage.write;
@@ -30,7 +46,6 @@ import org.apache.usergrid.persistence.collection.cassandra.CassandraRule;
import org.apache.usergrid.persistence.collection.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
-import org.apache.usergrid.persistence.collection.mvcc.stage.AbstractMvccEntityStageTest;
import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
import org.apache.usergrid.persistence.model.entity.Entity;
@@ -52,13 +67,13 @@ import static org.mockito.Mockito.mock;
*/
@RunWith( JukitoRunner.class )
@UseModules( TestCollectionModule.class )
-public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
+public class WriteUniqueVerifyTest {
@ClassRule
public static CassandraRule rule = new CassandraRule();
@Inject
- private UniqueValueSerializationStrategy uniqueValueSerializiationStrategy;
+ private UniqueValueSerializationStrategy uvstrat;
@Inject
@@ -88,19 +103,19 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uvstrat, scheduler, fig );
- CollectionIoEvent<MvccEntity> result =
- newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
- .last();
+ CollectionIoEvent<MvccEntity> result = newStage.call(
+ new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) )
+ .toBlockingObservable().last();
assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
// verify the log entry is correct
MvccEntity entry = result.getEvent();
- // verify uuid and version in both the MvccEntity and the entity itself
- // assertSame is used on purpose. We want to make sure the same instance is used, not a copy.
+ // verify uuid and version in both the MvccEntity and the entity itself. assertSame is
+ // used on purpose. We want to make sure the same instance is used, not a copy.
// this way the caller's runtime type is retained.
assertSame( "id correct", entity.getId(), entry.getId() );
assertSame( "version did not not match entityId", entity.getVersion(), entry.getVersion() );
@@ -119,20 +134,15 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uvstrat, scheduler, fig );
- CollectionIoEvent<MvccEntity> result =
- newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
- .last();
+ CollectionIoEvent<MvccEntity> result = newStage.call(
+ new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) )
+ .toBlockingObservable().last();
assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
}
-
- @Override
- protected void validateStage( final CollectionIoEvent<MvccEntity> event ) {
- new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig ).call( event );
- }
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
new file mode 100644
index 0000000..02b645f
--- /dev/null
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.usergrid.persistence.collection.util;
+
+import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
+import org.apache.usergrid.persistence.model.entity.Entity;
+import org.apache.usergrid.persistence.model.entity.Id;
+import org.junit.Assert;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+@RunWith( Theories.class )
+public class InvalidValueGeneratorTest {
+ private static final Logger LOG = LoggerFactory.getLogger( InvalidValueGeneratorTest.class );
+
+ @Theory
+ public void testInvalidValues(
+ @InvalidMvccEntityGenerator.IllegalFields final MvccEntity mvccEntityInvalid,
+ @InvalidEntityGenerator.IllegalFields final Entity entityInvalid,
+ @InvalidIdGenerator.IllegalFields final Id idInvalid) {
+
+ Assert.assertNotNull( mvccEntityInvalid.getId() );
+
+ Assert.assertNotNull( entityInvalid.getId() );
+
+ Assert.assertNotNull( idInvalid.getUuid() );
+ Assert.assertNotNull( idInvalid.getType() );
+ }
+}
[31/50] [abbrv] git commit: Rename PriamCluster to AWSCluster,
and move out of Core Persistence as it is no longer needed for
testing there.
Posted by sn...@apache.org.
Rename PriamCluster to AWSCluster, and move out of Core Persistence as it is no longer needed for testing there.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/56277504
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/56277504
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/56277504
Branch: refs/heads/optimistic-tx-semantics
Commit: 56277504a8e932493cd1159e33855db2b3069101
Parents: e578bb6
Author: Dave Johnson <dm...@apigee.com>
Authored: Wed Feb 12 09:03:51 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Wed Feb 12 09:03:51 2014 -0500
----------------------------------------------------------------------
stack/awscluster/README.md | 84 +++++
stack/awscluster/assembly.xml | 29 ++
stack/awscluster/aws-sample.properties | 2 +
stack/awscluster/cassandra-cf.json | 315 +++++++++++++++++++
stack/awscluster/pom.xml | 139 ++++++++
.../src/main/dist/conf/Priam.properties | 21 ++
.../src/main/dist/init_instance/create_raid0.sh | 32 ++
.../main/dist/init_instance/init_instance.sh | 54 ++++
.../dist/init_instance/install_cassandra.sh | 56 ++++
.../dist/init_instance/install_elasticsearch.sh | 24 ++
.../dist/init_instance/install_oraclejdk.sh | 31 ++
.../src/main/dist/lib/priam-agent-1.2.24.jar | Bin 0 -> 33020 bytes
.../dist/lib/priam-cass-extensions-1.2.24.jar | Bin 0 -> 5478 bytes
.../src/main/dist/webapps/priam-web-1.2.24.war | Bin 0 -> 31272443 bytes
.../src/main/groovy/configure_cassandra.groovy | 113 +++++++
.../main/groovy/configure_elasticsearch.groovy | 47 +++
.../src/main/groovy/configure_priam.groovy | 41 +++
.../src/main/groovy/registry_clear.groovy | 20 ++
.../src/main/groovy/registry_list.groovy | 24 ++
.../src/main/groovy/registry_register.groovy | 38 +++
.../src/main/groovy/tag_instance.groovy | 28 ++
.../src/main/groovy/wait_for_instances.groovy | 44 +++
22 files changed, 1142 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/README.md
----------------------------------------------------------------------
diff --git a/stack/awscluster/README.md b/stack/awscluster/README.md
new file mode 100644
index 0000000..1f3f7f5
--- /dev/null
+++ b/stack/awscluster/README.md
@@ -0,0 +1,84 @@
+AWS Cluster
+===
+
+*UNDER CONSTRUCTION*
+
+This project provides a AWS Cloud Formation template that launches a complete Usergrid installation
+on Amazon EC2. Currently it launches a set of instances running Cassanrda, Priam and Elastic Search.
+
+Two parts:
+
+1) A Maven assembly that builds an installer tarball and uploads it to S3.
+The tarball includes scripts to install Oracle JDK, Cassandra and Priam on EC2 instance.
+
+2) A CloudFormation script that creates an autoscaling cluster, security group and some
+number of EC2 instances, The template includes a CloudInit script that runs scipts from
+the installer tarball to configure and start Cassandra on each node.
+
+
+Getting set-up
+---
+To setup our AWS account to use PriamCluster here's what you need to do:
+
+* __Create an AWS EC2 key pair__. You will need this PEM file to login to your Cassandra instances.
+
+* __Create an AWS S3 bucket__ for the PriamCluster install bundle. Create an S3 bucket in your
+account with the name `ug-cloudformation-priam`.
+
+* __Upload the Oracle Java JDK__ to that same S3 bucket. Best practice is to use the Oracle Java u
+JDK with Cassandra, so you must upload the JDK to the S3 bucket that we created above. The JDK must
+be named `jdk-7u45-linux-x64.gz`.
+
+* __Create AWS SimpleDB domain for Priam__ properties and instance registration. It's best if you
+use a SimpleDB client (e.g. SDBNavigator for Chrome) to create these domains. You must create two
+domains named `PriamProperties` and `InstanceIdentity`. Just create the domains and Priam will create
+the attributes.
+
+* __Create an aws.properties file__ with your AWS credentials in the same directory as this
+README file. The file is git-ignored so you don't have to worry about accidentally committing it.
+
+* __Deploy this the PriamCluster assembly__ by running the Maven command `mvn depoy` in the same
+directory as this README file.
+
+
+Launching a new stack
+---
+Login to AWS Console and create a new CloudFormation stack. On the first screen, pick a short
+and simple name for your stack and choose the option to upload a template and upload
+the `cassandra-cf.json` file in this very directory.
+
+On the next screen, enter the number of servers you wish to create, the replication factor and
+the instance type you wish to use. Check the "I acknowlege that this will create IAM resources"
+and then click Next, Next, Next to take defaults and start the stack.
+
+Watch the EC2 console and see your instances come up. They will be tagged with the stack name
+that you provided.
+
+
+Exploring a Cassandra node
+---
+Take a look at your new cluster. Login to one of the instances and take a look at the Cassandra
+setup via `nodetool ring` and by looking at the following logs locations:
+
+ /var/log/usergrid-bootstrap.log - log created as instance was created
+
+ /var/log/cassandra - the Cassandra log files
+
+
+How things work
+---
+Here's what happens when the stack is started.
+
+CloudFormation reads the `cassanrda-cf.json` template and uses starts the EC2 instances that it
+specifies. When each instance comes up CloudFormation runs the CloudInit script specified in
+`cassandra-cf.json` and that script downloads the PriamCluster, sets up some environment scripts
+and calls the `init_instance/init_cass.sh` script to complete the setup.
+
+The `init_instance/init_cass.sh` calls `install_oraclejdk.sh` to download the JDK from S3 and
+install it. The script then installs Tomcat and Cassandra. Next it uses Groovy scripts to configure
+Priam and Cassandra and wait for other Cassandra nodes to come alive.
+
+When Tomcat starts up, Priam comes to life. Priam reads it's SimpleDB tables, writes a new
+cassandra.yaml file and with the right seends and initial token starts Cassandra.
+
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/assembly.xml
----------------------------------------------------------------------
diff --git a/stack/awscluster/assembly.xml b/stack/awscluster/assembly.xml
new file mode 100644
index 0000000..b5406dd
--- /dev/null
+++ b/stack/awscluster/assembly.xml
@@ -0,0 +1,29 @@
+<assembly>
+ <id>any</id>
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+
+ <includeBaseDirectory>false</includeBaseDirectory>
+
+ <fileSets>
+
+ <fileSet>
+ <outputDirectory>.</outputDirectory>
+ <directory>${project.basedir}/src/main/dist</directory>
+ <includes>
+ <include>**</include>
+ </includes>
+ </fileSet>
+
+ <fileSet>
+ <outputDirectory>./scripts</outputDirectory>
+ <directory>./src/main/groovy</directory>
+ <includes>
+ <include>**</include>
+ </includes>
+ </fileSet>
+
+ </fileSets>
+
+</assembly>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/aws-sample.properties
----------------------------------------------------------------------
diff --git a/stack/awscluster/aws-sample.properties b/stack/awscluster/aws-sample.properties
new file mode 100644
index 0000000..c3ade61
--- /dev/null
+++ b/stack/awscluster/aws-sample.properties
@@ -0,0 +1,2 @@
+accesskey=<YourServiceAccessKey>
+secretkey=<YourServiceSecretKey>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/cassandra-cf.json
----------------------------------------------------------------------
diff --git a/stack/awscluster/cassandra-cf.json b/stack/awscluster/cassandra-cf.json
new file mode 100644
index 0000000..a28cf48
--- /dev/null
+++ b/stack/awscluster/cassandra-cf.json
@@ -0,0 +1,315 @@
+{
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Description": "Cassandra Test Stack",
+ "Parameters": {
+ "ReleaseBucket": {
+ "Description": "S3 Bucket where Priam-Cluster assembly is to be found.",
+ "Type": "String",
+ "Default": "ug-cloudformation-priam"
+ },
+ "KeyPair": {
+ "Description": "EC2 key pair to be use for SSH access",
+ "Type": "String",
+ "Default": "ug-cloudformation"
+ },
+ "CassClusterName": {
+ "Description": "Name to be used for Cassandra cluster.",
+ "Type": "String",
+ "Default": "usergrid"
+ },
+ "CassNumServers": {
+ "Description": "Number of Cass servers to start.",
+ "Type": "Number",
+ "Default": "3",
+ "MinValue": "3"
+ },
+ "CassInstanceType": {
+ "Description": "Instance type for Cass servers",
+ "Type": "String",
+ "Default": "m1.xlarge",
+ "AllowedValues": ["m1.small", "m1.medium", "m1.large", "m1.xlarge", "m3.xlarge", "m3.2xlarge"],
+ "ConstraintDescription": "must be valid instance type."
+ },
+ "CassReplicationFactor": {
+ "Description": "Cassandra replication factor",
+ "Type": "Number",
+ "Default": "2",
+ "MinValue": "1"
+ },
+ "NotificationEmail": {
+ "Description": "Email for notifications",
+ "Type": "String",
+ "Default": "dmjohnson+cf@apigee.com"
+ }
+ },
+ "Mappings": {
+ "AWSInstanceType2Arch": {
+ "m1.small": {"Arch": "64"},
+ "m1.medium": {"Arch": "64"},
+ "m1.large": {"Arch": "64"},
+ "m1.xlarge": {"Arch": "64"}
+ },
+ "AWSRegionArch2AMI": {
+ "ap-southeast-2": {"64": "ami-db8611e1"},
+ "us-east-1": {"64": "ami-e864da81"},
+ "us-west-2": {"64": "ami-50f97060"}
+ }
+ },
+ "Resources": {
+ "CassUser": {
+ "Type": "AWS::IAM::User",
+ "Properties": {
+ "Path": "/",
+ "Policies": [{
+ "PolicyName": "root",
+ "PolicyDocument": {"Statement": [{
+ "Effect": "Allow",
+ "Action": "*",
+ "Resource": "*"
+ }]}
+ }]
+ }
+ },
+ "CassKey": {
+ "Type": "AWS::IAM::AccessKey",
+ "Properties": {
+ "UserName": {"Ref": "CassUser"}
+ }
+ },
+ "CassAutoScalingLaunchConfiguration": {
+ "Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {
+ "UserData": {
+ "Fn::Base64": {"Fn::Join": ["", [
+
+ "#!/bin/bash -ex\n",
+
+ "# CASSANDRA NODE STARTUP \n",
+
+ "exec >/var/log/usergrid-bootstrap.log 2>&1\n",
+ "\n",
+ "mkdir -p /usr/share/usergrid\n",
+ "\n",
+
+ "# create script that sets our environment variables\n",
+ "cat >/etc/profile.d/usergrid-env.sh <<EOF\n",
+ "alias sudo='sudo -E'\n",
+ "\n",
+ "export TYPE=cass\n",
+ "export STACK_NAME=", {"Ref": "AWS::StackName"}, "\n",
+ "\n",
+ "export PUBLIC_HOSTNAME=`(curl -s http://169.254.169.254/latest/meta-data/public-hostname)`\n",
+ "export INTERNAL_HOSTNAME=`(curl http://169.254.169.254/latest/meta-data/local-ipv4)`\n",
+ "\n",
+ "export EC2_INSTANCE_ID=`ec2metadata --instance-id`\n",
+ "export EC2_REGION=", {"Ref": "AWS::Region"}, "\n",
+ "export EC2_URL=https://ec2.amazonaws.com/\n",
+ "\n",
+ "export CASS_SECURITY_GROUP_NAME=", {"Ref": "CassSecurityGroup"}, "\n",
+ "\n",
+ "export JVM_EXTRA_OPTS=-javaagent:/usr/share/cassandra/lib/priam-cass-extensions-1.2.24.jar", "\n",
+ "\n",
+ "export CASSANDRA_CLUSTER_NAME=", {"Ref": "CassClusterName"}, "\n",
+ "export CASSANDRA_NUM_SERVERS=", {"Ref": "CassNumServers"}, "\n",
+ "export CASSANDRA_KEYSPACE_NAME=usergrid", "\n",
+ "export CASSANDRA_REPLICATION_FACTOR=", {"Ref": "CassReplicationFactor"}, "\n",
+ "\n",
+ "export RELEASE_BUCKET=", {"Ref": "ReleaseBucket"}, "\n",
+ "\n",
+ "EOF\n",
+ "\n",
+
+ "# put AWS creds in environment\n",
+ "cat >/etc/profile.d/aws-credentials.sh <<EOF\n",
+ "export AWS_ACCESS_KEY=", {"Ref": "CassKey"}, "\n",
+ "export AWS_SECRET_KEY=", {"Fn::GetAtt": ["CassKey", "SecretAccessKey"]}, "\n",
+ "EOF\n",
+ "\n",
+
+ "# put AWS creds Priam's config file\n",
+ "cat >/etc/awscredential.properties <<EOF\n",
+ "AWSACCESSID=", {"Ref": "CassKey"}, "\n",
+ "AWSKEY=", {"Fn::GetAtt": ["CassKey", "SecretAccessKey"]}, "\n",
+ "EOF\n",
+ "\n",
+
+ "# setup s3cmd (will be installed by init script) \n",
+ "cat >/etc/s3cfg <<EOF\n",
+ "access_key=", {"Ref": "CassKey"}, "\n",
+ "secret_key=", {"Fn::GetAtt": ["CassKey", "SecretAccessKey"]}, "\n",
+ "EOF\n",
+ "chmod 644 /etc/s3cfg\n",
+ "ln -s /etc/s3cfg ~ubuntu/.s3cfg\n",
+ "ln -s /etc/s3cfg ~root/.s3cfg\n",
+ "\n",
+
+ "# download usergrid and init script bundle from S3\n",
+ "apt-get update\n",
+ "apt-get -y install s3cmd\n",
+ "cd /usr/share/usergrid\n",
+ "s3cmd --config=/etc/s3cfg get s3://", {"Ref": "ReleaseBucket"}, "/priamcluster-1.0-SNAPSHOT-any.tar.gz\n",
+ "tar xvf priamcluster-1.0-SNAPSHOT-any.tar.gz\n",
+ "rm -fr priamcluster-1.0-SNAPSHOT-any.tar.gz\n",
+ "chmod 755 ./init_instance/*.sh\n",
+ "cd ./init_instance\n",
+
+ "# init as a Cassandra node \n",
+ "sh ./init_instance.sh\n"
+
+ ]]}
+ },
+ "KeyName": {"Ref": "KeyPair"},
+ "ImageId": {
+ "Fn::FindInMap": [
+ "AWSRegionArch2AMI",
+ {
+ "Ref": "AWS::Region"
+ },
+ {
+ "Fn::FindInMap": [
+ "AWSInstanceType2Arch",
+ {
+ "Ref": "CassInstanceType"
+ },
+ "Arch"
+ ]
+ }
+ ]
+ },
+ "InstanceType": {
+ "Ref": "CassInstanceType"
+ },
+ "IamInstanceProfile": {
+ "Ref": "RootInstanceProfile"
+ },
+ "SecurityGroups": [{"Ref": "CassSecurityGroup"}]
+ }
+ },
+ "CassAutoScalingGroup": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup",
+ "Version": "2009-05-15",
+ "Properties": {
+ "AvailabilityZones": {
+ "Fn::GetAZs": ""
+ },
+ "LaunchConfigurationName": {
+ "Ref": "CassAutoScalingLaunchConfiguration"
+ },
+ "MinSize": {"Ref": "CassNumServers"},
+ "MaxSize": {"Ref": "CassNumServers"},
+ "NotificationConfiguration": {
+ "TopicARN": {"Ref": "NotificationTopic"},
+ "NotificationTypes": [
+ "autoscaling:EC2_INSTANCE_LAUNCH",
+ "autoscaling:EC2_INSTANCE_LAUNCH_ERROR",
+ "autoscaling:EC2_INSTANCE_TERMINATE",
+ "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"
+ ]
+ }
+ }
+ },
+ "NotificationTopic": {
+ "Type": "AWS::SNS::Topic",
+ "Properties": {
+ "Subscription": [{
+ "Endpoint": {"Ref": "NotificationEmail"},
+ "Protocol": "email"
+ }]
+ }
+ },
+ "RootRole": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "AssumeRolePolicyDocument": {
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {
+ "Service": [
+ "ec2.amazonaws.com"
+ ]
+ },
+ "Action": [
+ "sts:AssumeRole"
+ ]
+ }
+ ]
+ },
+ "Path": "/"
+ }
+ },
+ "RolePolicies": {
+ "Type": "AWS::IAM::Policy",
+ "Properties": {
+ "PolicyName": "root",
+ "PolicyDocument": {
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": "*",
+ "Resource": "*"
+ }
+ ]
+ },
+ "Roles": [
+ {
+ "Ref": "RootRole"
+ }
+ ]
+ }
+ },
+ "RootInstanceProfile": {
+ "Type": "AWS::IAM::InstanceProfile",
+ "Properties": {
+ "Path": "/",
+ "Roles": [
+ {
+ "Ref": "RootRole"
+ }
+ ]
+ }
+ },
+ "CassSecurityGroup": {
+ "Type": "AWS::EC2::SecurityGroup",
+ "Properties": {
+ "GroupDescription": "Database Machines",
+ "SecurityGroupIngress": [{
+ "IpProtocol": "tcp",
+ "FromPort": "22",
+ "ToPort": "22",
+ "CidrIp": "0.0.0.0/0"
+ }]
+ }
+ },
+ "CassSecurityGroupPort7000": {
+ "Type": "AWS::EC2::SecurityGroupIngress",
+ "Properties": {
+ "GroupName": {"Ref": "CassSecurityGroup"},
+ "IpProtocol": "tcp",
+ "FromPort": "7000",
+ "ToPort": "7000",
+ "SourceSecurityGroupName": {"Ref": "CassSecurityGroup"}
+ }
+ },
+ "CassSecurityGroupPort9160": {
+ "Type": "AWS::EC2::SecurityGroupIngress",
+ "Properties": {
+ "GroupName": {"Ref": "CassSecurityGroup"},
+ "IpProtocol": "tcp",
+ "FromPort": "9160",
+ "ToPort": "9160",
+ "SourceSecurityGroupName": {"Ref": "CassSecurityGroup"}
+ }
+ },
+ "CassSecurityGroupPort9200": {
+ "Type": "AWS::EC2::SecurityGroupIngress",
+ "Properties": {
+ "GroupName": {"Ref": "CassSecurityGroup"},
+ "IpProtocol": "tcp",
+ "FromPort": "9200",
+ "ToPort": "9200",
+ "SourceSecurityGroupName": {"Ref": "CassSecurityGroup"}
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/pom.xml
----------------------------------------------------------------------
diff --git a/stack/awscluster/pom.xml b/stack/awscluster/pom.xml
new file mode 100644
index 0000000..358f24e
--- /dev/null
+++ b/stack/awscluster/pom.xml
@@ -0,0 +1,139 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>priamcluster</artifactId>
+ <groupId>org.usergrid</groupId>
+ <version>1.0-SNAPSHOT</version>
+
+ <name>priamcluster</name>
+ <description>Creates bundle for initializing a Cassandra and Priam cluster via CloudFormation</description>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <aws.s3.release-bucket>ug-cloudformation-priam</aws.s3.release-bucket>
+ </properties>
+
+ <build>
+
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>make-assembly</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <descriptors>
+ <descriptor>assembly.xml</descriptor>
+ </descriptors>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <version>1.2</version>
+ <executions>
+ <execution>
+ <phase>deploy</phase>
+ <goals>
+ <goal>java</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <includeProjectDependencies>true</includeProjectDependencies>
+ <includePluginDependencies>true</includePluginDependencies>
+ <classpathScope>runtime</classpathScope>
+ <executableDependency>
+ <groupId>net.java.dev.jets3t</groupId>
+ <artifactId>jets3t</artifactId>
+ </executableDependency>
+ <mainClass>org.jets3t.apps.synchronize.Synchronize</mainClass>
+ <arguments>
+ <argument>--nodelete</argument>
+ <argument>--properties</argument>
+ <argument>${project.basedir}/aws.properties</argument>
+ <argument>UP</argument>
+ <argument>${aws.s3.release-bucket}</argument>
+ <argument>${project.build.directory}/${project.build.finalName}-any.tar.gz</argument>
+ </arguments>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>net.java.dev.jets3t</groupId>
+ <artifactId>jets3t</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.8.1</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy-eclipse-compiler</artifactId>
+ <version>2.6.0-01</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <compilerId>groovy-eclipse-compiler</compilerId>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>groovy-eclipse-compiler</artifactId>
+ <groupId>org.codehaus.groovy</groupId>
+ <version>2.6.0-01</version>
+ <extensions>true</extensions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>net.java.dev.jets3t</groupId>
+ <artifactId>synchronize</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>net.java.dev.jets3t</groupId>
+ <artifactId>jets3t</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.amazonaws</groupId>
+ <artifactId>aws-java-sdk</artifactId>
+ <version>1.6.7</version>
+ </dependency>
+ <dependency>
+ <artifactId>groovy-all</artifactId>
+ <groupId>org.codehaus.groovy</groupId>
+ <version>2.0.5</version>
+ </dependency>
+ </dependencies>
+
+</project>
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/conf/Priam.properties
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/conf/Priam.properties b/stack/awscluster/src/main/dist/conf/Priam.properties
new file mode 100644
index 0000000..e327526
--- /dev/null
+++ b/stack/awscluster/src/main/dist/conf/Priam.properties
@@ -0,0 +1,21 @@
+
+# priam settings to be added to SimpleDB by configure_priam.groovy
+
+priam.clustername=usergrid2
+
+priam.cass.home=/etc/cassandra
+priam.cass.startscript=/etc/init.d/cassandra start
+priam.cass.stopscript=/etc/init.d/cassandra stop
+priam.yamlLocation=/etc/cassandra/cassandra.yaml
+
+priam.commitlog.location=/mnt/data/cassandra/commitlog
+priam.data.location=/mnt/data/cassandra/data
+priam.cache.location=/mnt/data/cassandra/saved_caches
+
+priam.s3.base_dir=priam-backup
+priam.s3.bucket=priam-cassandra-archive
+priam.backup.incremental.enable=false
+
+priam.partitioner=org.apache.cassandra.dht.RandomPartitioner
+
+priam.zones.available=us-east-1a,us-east-1b,us-east-1c,us-east-1d
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/init_instance/create_raid0.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/create_raid0.sh b/stack/awscluster/src/main/dist/init_instance/create_raid0.sh
new file mode 100644
index 0000000..401fcf4
--- /dev/null
+++ b/stack/awscluster/src/main/dist/init_instance/create_raid0.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+# install postfix first and prevent it from prompting the user
+debconf-set-selections <<< "postfix postfix/mailname string your.hostname.com"
+debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
+apt-get install -y postfix
+
+# install mdadm RAID controller
+apt-get -y install mdadm
+
+# m1.xlarge has four 414GB disks, but only /dev/xvdb is mounted
+# unmount /dev/xvdb so we can use it in our setup
+umount /mnt
+
+# create & format partition on each of our four disks
+(echo o; echo n; echo p; echo 1; echo ; echo; echo w) | fdisk /dev/xvdb
+(echo o; echo n; echo p; echo 1; echo ; echo; echo w) | fdisk /dev/xvdc
+(echo o; echo n; echo p; echo 1; echo ; echo; echo w) | fdisk /dev/xvdd
+(echo o; echo n; echo p; echo 1; echo ; echo; echo w) | fdisk /dev/xvde
+
+# create striped RAID0 device with our four disks
+mdadm --create --verbose /dev/md0 --level=stripe \
+--raid-devices=4 /dev/xvdb1 /dev/xvdc1 /dev/xvdd1 /dev/xvde1
+
+# save config
+mdadm --detail --scan | tee /etc/mdadm/mdadm.conf
+
+# create, mount and save disk to stab
+mkfs.ext4 -b 4096 -E stride=32,stripe-width=128 -L Stripe /dev/md0
+mkdir -p /mnt
+echo "/dev/md0 /mnt auto defaults,nobootwait,noatime 0 2" | tee /etc/fstab
+mount /mnt
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/init_instance/init_instance.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/init_instance.sh b/stack/awscluster/src/main/dist/init_instance/init_instance.sh
new file mode 100644
index 0000000..552df78
--- /dev/null
+++ b/stack/awscluster/src/main/dist/init_instance/init_instance.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+echo "${HOSTNAME}" > /etc/hostname
+echo "127.0.0.1 ${HOSTNAME}" >> /etc/hosts
+hostname `cat /etc/hostname`
+
+echo "US/Eastern" > /etc/timezone
+dpkg-reconfigure -f noninteractive tzdata
+
+# Build environment for scripts
+. /etc/profile.d/aws-credentials.sh
+. /etc/profile.d/usergrid-env.sh
+
+cd /usr/share/usergrid/init_instance
+./create_raid0.sh
+
+# Install the easy stuff
+PKGS="ntp unzip groovy tomcat7 curl"
+apt-get update
+apt-get -y install ${PKGS}
+/etc/init.d/tomcat7 stop
+
+# Install AWS Java SDK and get it into the Groovy classpath
+curl http://sdk-for-java.amazonwebservices.com/latest/aws-java-sdk.zip > /tmp/aws-sdk-java.zip
+cd /usr/share/
+unzip /tmp/aws-sdk-java.zip
+mkdir -p /home/ubuntu/.groovy/lib
+cp /usr/share/aws-java-sdk-*/third-party/*/*.jar /home/ubuntu/.groovy/lib
+cp /usr/share/aws-java-sdk-*/lib/* /home/ubuntu/.groovy/lib
+# except for evil stax
+rm /home/ubuntu/.groovy/lib/stax*
+ln -s /home/ubuntu/.groovy /root/.groovy
+
+cd /usr/share/usergrid/init_instance
+./install_oraclejdk.sh
+
+# Install and stop Cassandra
+cd /usr/share/usergrid/init_instance
+./install_cassandra.sh
+
+# Install and start ElasticSearch
+cd /usr/share/usergrid/init_instance
+./install_elasticsearch.sh
+/etc/init.d/elasticsearch start
+
+# Starting Tomcat starts Priam which starts Priam
+/etc/init.d/tomcat7 restart
+
+# Priam consistently craps out on first run
+# making this ugly kludge necessary
+sleep 90
+/etc/init.d/tomcat7 restart
+
+cd /usr/share/usergrid/scripts
+groovy tag_instance.groovy
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/init_instance/install_cassandra.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/install_cassandra.sh b/stack/awscluster/src/main/dist/init_instance/install_cassandra.sh
new file mode 100644
index 0000000..5bf7d04
--- /dev/null
+++ b/stack/awscluster/src/main/dist/init_instance/install_cassandra.sh
@@ -0,0 +1,56 @@
+#!/bin/bash
+
+# Install and stop Cassandra
+pushd /etc/apt/sources.list.d
+
+cat >> cassandra.sources.list << EOF
+deb http://www.apache.org/dist/cassandra/debian 12x main
+EOF
+apt-get update
+apt-get -y install libcap2
+apt-get --force-yes -y install cassandra
+/etc/init.d/cassandra stop
+
+mkdir -p /mnt/data/cassandra
+chown cassandra /mnt/data/cassandra
+
+# Wait for other instances to start up
+cd /usr/share/usergrid/scripts
+groovy registry_register.groovy
+groovy wait_for_instances.groovy
+
+# Configure Priam
+cd /usr/share/usergrid/scripts
+groovy configure_cassandra.groovy > /etc/cassandra/cassandra.yaml
+groovy configure_priam.groovy
+
+# Copy Priam extension into Cassandra and Priam WAR into Tomcat
+rm -rf /var/lib/tomcat7/webapps/*
+mkdir -p /usr/share/cassandra/lib
+cp /usr/share/usergrid/lib/priam-cass-extensions-1.2.24.jar /usr/share/cassandra/lib
+cp /usr/share/usergrid/webapps/priam-web-1.2.24.war /var/lib/tomcat7/webapps/Priam.war
+
+# Make sure Priam via Tomcat can write to /etc/cassandra
+# TODO: do this without 777
+chmod -R 777 /etc/cassandra
+chmod 777 /etc/init.d/cassandra
+
+# Configure sudo for no passwords to please Priam
+cat >> /tmp/sudoers.new << EOF
+Defaults env_reset
+Defaults mail_badpass
+Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
+root ALL=(ALL:ALL) ALL
+%admin ALL=(ALL) ALL
+%sudo ALL=(ALL:ALL) NOPASSWD:ALL
+EOF
+visudo -c -f /tmp/sudoers.new
+if [ "$?" -eq "0" ]; then
+ cp /tmp/sudoers.new /etc/sudoers
+fi
+# Add tomat user to sudoers to please Priam
+adduser tomcat7 sudo
+/etc/init.d/sudo restart
+
+popd
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
new file mode 100644
index 0000000..080fa9a
--- /dev/null
+++ b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+
+# Install and stop ElasticSearch
+pushd /etc/apt/sources.list.d
+
+cat >> elasticsearch.sources.list << EOF
+deb http://packages.elasticsearch.org/elasticsearch/1.0/debian stable main
+EOF
+apt-get update
+apt-get --force-yes -y install elasticsearch
+/etc/init.d/elasticsearch stop
+
+mkdir -p /mnt/data/elasticsearch
+chown elasticsearch /mnt/data/elasticsearch
+
+mkdir -p /mnt/log/elasticsearch
+chown elasticsearch /mnt/log/elasticsearch
+
+# Configure and restart ElasticSearch
+update-rc.d elasticsearch defaults 95 10
+cd /usr/share/usergrid/scripts
+groovy ./configure_elasticsearch.groovy > /etc/elasticsearch/elasticsearch.yml
+
+popd
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/init_instance/install_oraclejdk.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/install_oraclejdk.sh b/stack/awscluster/src/main/dist/init_instance/install_oraclejdk.sh
new file mode 100644
index 0000000..f81c5fa
--- /dev/null
+++ b/stack/awscluster/src/main/dist/init_instance/install_oraclejdk.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+pushd /tmp
+
+# Build environment for scripts
+. /etc/profile.d/aws-credentials.sh
+. /etc/profile.d/usergrid-env.sh
+
+echo ${RELEASE_BUCKET}
+
+# Get JDK from the release bucket
+s3cmd --config=/etc/s3cfg get s3://${RELEASE_BUCKET}/jdk-7u45-linux-x64.gz
+
+# Install it as they do here:
+# http://askubuntu.com/questions/56104/how-can-i-install-sun-oracles-proprietary-java-6-7-jre-or-jdk
+tar -xvf jdk-7u45-linux-x64.gz
+mkdir -p /usr/lib/jvm
+mv ./jdk1.7.0_45 /usr/lib/jvm/jdk1.7.0
+
+update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 2000
+update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 2000
+update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 2000
+
+chmod a+x /usr/bin/java
+chmod a+x /usr/bin/javac
+chmod a+x /usr/bin/javaws
+chown -R root:root /usr/lib/jvm/jdk1.7.0
+
+sudo rm /usr/lib/jvm/default-java
+sudo ln -s /usr/lib/jvm/jdk1.7.0 /usr/lib/jvm/default-java
+
+popd
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/lib/priam-agent-1.2.24.jar
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/lib/priam-agent-1.2.24.jar b/stack/awscluster/src/main/dist/lib/priam-agent-1.2.24.jar
new file mode 100644
index 0000000..21e6980
Binary files /dev/null and b/stack/awscluster/src/main/dist/lib/priam-agent-1.2.24.jar differ
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/lib/priam-cass-extensions-1.2.24.jar
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/lib/priam-cass-extensions-1.2.24.jar b/stack/awscluster/src/main/dist/lib/priam-cass-extensions-1.2.24.jar
new file mode 100644
index 0000000..77c4f7b
Binary files /dev/null and b/stack/awscluster/src/main/dist/lib/priam-cass-extensions-1.2.24.jar differ
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/dist/webapps/priam-web-1.2.24.war
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/webapps/priam-web-1.2.24.war b/stack/awscluster/src/main/dist/webapps/priam-web-1.2.24.war
new file mode 100644
index 0000000..016eed4
Binary files /dev/null and b/stack/awscluster/src/main/dist/webapps/priam-web-1.2.24.war differ
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/configure_cassandra.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/configure_cassandra.groovy b/stack/awscluster/src/main/groovy/configure_cassandra.groovy
new file mode 100644
index 0000000..a71e071
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/configure_cassandra.groovy
@@ -0,0 +1,113 @@
+//
+// configure_cassandra.groovy
+//
+// Emits Cassandra config file based on environment and Cassandra node
+// registry in SimpleDB
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+def clusterName = (String)System.getenv().get("CASSANDRA_CLUSTER_NAME")
+String domain = stackName
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+// build seed list by listing all Cassandra nodes found in SimpleDB domain with our stackName
+def selectResult = sdbClient.select(new SelectRequest((String)"select * from ${domain}"))
+def seeds = ""
+def sep = ""
+for (item in selectResult.getItems()) {
+ def att = item.getAttributes().get(0)
+ if (att.getValue().equals(stackName)) {
+ seeds = "${seeds}${sep}${item.getName()}"
+ sep = ","
+ }
+}
+
+def cassandraConfig = """
+cluster_name: '${clusterName}'
+listen_address: ${hostName}
+seed_provider:
+ - class_name: org.apache.cassandra.locator.SimpleSeedProvider
+ parameters:
+ - seeds: "${seeds}"
+auto_bootstrap: true
+initial_token:
+hinted_handoff_enabled: true
+hinted_handoff_throttle_in_kb: 1024
+max_hints_delivery_threads: 2
+authenticator: org.apache.cassandra.auth.AllowAllAuthenticator
+authorizer: org.apache.cassandra.auth.AllowAllAuthorizer
+partitioner: org.apache.cassandra.dht.RandomPartitioner
+data_file_directories:
+ - /mnt/data/cassandra/data
+commitlog_directory: /mnt/data/cassandra/commitlog
+disk_failure_policy: stop
+key_cache_size_in_mb:
+key_cache_save_period: 14400
+row_cache_size_in_mb: 0
+row_cache_save_period: 0
+row_cache_provider: SerializingCacheProvider
+saved_caches_directory: /mnt/data/cassandra/saved_caches
+commitlog_sync: periodic
+commitlog_sync_period_in_ms: 10000
+commitlog_segment_size_in_mb: 32
+flush_largest_memtables_at: 0.75
+reduce_cache_sizes_at: 0.85
+reduce_cache_capacity_to: 0.6
+concurrent_reads: 32
+concurrent_writes: 32
+memtable_flush_queue_size: 4
+trickle_fsync: false
+trickle_fsync_interval_in_kb: 10240
+storage_port: 7000
+ssl_storage_port: 7001
+rpc_address: 0.0.0.0
+start_native_transport: false
+native_transport_port: 9042
+start_rpc: true
+rpc_port: 9160
+rpc_keepalive: true
+rpc_server_type: sync
+thrift_framed_transport_size_in_mb: 15
+thrift_max_message_length_in_mb: 16
+incremental_backups: false
+snapshot_before_compaction: false
+auto_snapshot: true
+column_index_size_in_kb: 64
+in_memory_compaction_limit_in_mb: 64
+multithreaded_compaction: false
+compaction_throughput_mb_per_sec: 16
+compaction_preheat_key_cache: true
+read_request_timeout_in_ms: 10000
+range_request_timeout_in_ms: 10000
+write_request_timeout_in_ms: 10000
+truncate_request_timeout_in_ms: 60000
+request_timeout_in_ms: 10000
+cross_node_timeout: false
+endpoint_snitch: SimpleSnitch
+dynamic_snitch_update_interval_in_ms: 100
+dynamic_snitch_reset_interval_in_ms: 600000
+dynamic_snitch_badness_threshold: 0.1
+request_scheduler: org.apache.cassandra.scheduler.NoScheduler
+index_interval: 128
+server_encryption_options:
+ internode_encryption: none
+ keystore: conf/.keystore
+ keystore_password: cassandra
+ truststore: conf/.truststore
+ truststore_password: cassandra
+client_encryption_options:
+ enabled: false
+ keystore: conf/.keystore
+ keystore_password: cassandra
+internode_compression: all
+"""
+
+println cassandraConfig
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/configure_elasticsearch.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/configure_elasticsearch.groovy b/stack/awscluster/src/main/groovy/configure_elasticsearch.groovy
new file mode 100644
index 0000000..6b90e17
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/configure_elasticsearch.groovy
@@ -0,0 +1,47 @@
+
+//
+// configure_cassandra.groovy
+//
+// Emits Cassandra config file based on environment and Cassandra node
+// registry in SimpleDB
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+def clusterName = (String)System.getenv().get("CASSANDRA_CLUSTER_NAME")
+String domain = stackName
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+// build seed list by listing all Cassandra nodes found in SimpleDB domain with our stackName
+def selectResult = sdbClient.select(new SelectRequest((String)"select * from ${domain}"))
+def seeds = ""
+def sep = ""
+for (item in selectResult.getItems()) {
+ def att = item.getAttributes().get(0)
+ if (att.getValue().equals(stackName)) {
+ seeds = "${seeds}${sep}\"${item.getName()}\""
+ sep = ","
+ }
+}
+
+def elasticSearchConfig = """
+cluster.name: usergrid2
+discovery.zen.ping.multicast.enabled: false
+discovery.zen.ping.unicast.hosts: [${seeds}]
+node:
+ name: ${hostName}
+network:
+ host: ${hostName}
+path:
+ logs: /mnt/log/elasticsearch
+ data: /mnt/data/elasticsearch
+"""
+
+println elasticSearchConfig
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/configure_priam.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/configure_priam.groovy b/stack/awscluster/src/main/groovy/configure_priam.groovy
new file mode 100644
index 0000000..22f4661
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/configure_priam.groovy
@@ -0,0 +1,41 @@
+//
+// configure_priam.groovy
+//
+// Put our property overrides into Priam's SimpleDB table
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String domain = "PriamProperties"
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+// creates domain or no-op if it already exists
+sdbClient.createDomain(new CreateDomainRequest(domain))
+
+def props = new Properties()
+props.load(new FileInputStream("../conf/Priam.properties"))
+
+for (name in props.stringPropertyNames()) {
+
+ def value = props.getProperty(name)
+ def key = "${stackName}${name}"
+
+ def attrs = new ArrayList()
+ attrs.add(new ReplaceableAttribute("appId", stackName, true))
+ attrs.add(new ReplaceableAttribute("property", name, true))
+ attrs.add(new ReplaceableAttribute("value", value, true))
+
+ // this will set new or update existing attributes
+ def par = new PutAttributesRequest(domain, key, attrs)
+ sdbClient.putAttributes(par);
+}
+
+println "Configured Priam."
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/registry_clear.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/registry_clear.groovy b/stack/awscluster/src/main/groovy/registry_clear.groovy
new file mode 100644
index 0000000..5baa537
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/registry_clear.groovy
@@ -0,0 +1,20 @@
+//
+// registry_clear.groovy
+//
+// Deletes the Cassandra node registry
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+String domain = stackName
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+// TODO: this should only clear out items owned by our stack, i.e. those with the same stack name
+sdbClient.deleteDomain(new DeleteDomainRequest(domain))
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/registry_list.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/registry_list.groovy b/stack/awscluster/src/main/groovy/registry_list.groovy
new file mode 100644
index 0000000..9871a21
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/registry_list.groovy
@@ -0,0 +1,24 @@
+//
+// registry_list.groovy
+//
+// List contents of registry as debugging aid. Not used in any other scripts.
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+String domain = stackName
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+def selectResult = sdbClient.select(new SelectRequest((String)"select * from ${domain}"))
+
+for (item in selectResult.getItems()) {
+ def att = item.getAttributes().get(0)
+ println "${item.getName()} -> ${att.getName()} : ${att.getValue()}"
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/registry_register.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/registry_register.groovy b/stack/awscluster/src/main/groovy/registry_register.groovy
new file mode 100644
index 0000000..739c04e
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/registry_register.groovy
@@ -0,0 +1,38 @@
+//
+// configure_usergrid.groovy
+//
+// Register this host machine as a Cassandra node in our stack.
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String hostName = (String)System.getenv().get("PUBLIC_HOSTNAME")
+String domain = stackName
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+// creates domain or no-op if it already exists
+sdbClient.createDomain(new CreateDomainRequest(domain))
+
+def gar = new GetAttributesRequest(domain, hostName);
+def response = sdbClient.getAttributes(gar);
+if (response.getAttributes().size() == 1) {
+ println "Already registered"
+ def attrs = response.getAttributes()
+ for (att in attrs) {
+ println("${hostName} -> ${att.getName()} : ${att.getValue()}")
+ }
+} else {
+ println "Registering..."
+ def stackAtt = new ReplaceableAttribute("stackname", stackName, true)
+ def attrs = new ArrayList()
+ attrs.add(stackAtt)
+ def par = new PutAttributesRequest(domain, hostName, attrs)
+ sdbClient.putAttributes(par);
+ println "Registraition done."
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/tag_instance.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/tag_instance.groovy b/stack/awscluster/src/main/groovy/tag_instance.groovy
new file mode 100644
index 0000000..76c5e86
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/tag_instance.groovy
@@ -0,0 +1,28 @@
+//
+// tag_instance.groovy
+//
+// Tag instance so we can easily identify it in the EC2 console
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.ec2.*
+import com.amazonaws.services.ec2.model.*
+
+String type = (String)System.getenv().get("TYPE")
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String instanceId = (String)System.getenv().get("EC2_INSTANCE_ID")
+String stackName = (String)System.getenv().get("STACK_NAME")
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def ec2Client = new AmazonEC2Client(creds)
+
+def resources = new ArrayList()
+resources.add(instanceId)
+
+def tags = new ArrayList()
+def tag = "${stackName}-${type}-${instanceId}"
+tags.add(new Tag("Name", tag))
+
+ec2Client.createTags(new CreateTagsRequest(resources, tags))
+
+println "Tagged instance as ${tag}"
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/56277504/stack/awscluster/src/main/groovy/wait_for_instances.groovy
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/groovy/wait_for_instances.groovy b/stack/awscluster/src/main/groovy/wait_for_instances.groovy
new file mode 100644
index 0000000..4f125b6
--- /dev/null
+++ b/stack/awscluster/src/main/groovy/wait_for_instances.groovy
@@ -0,0 +1,44 @@
+//
+// wait_for_cassandra.groovy
+//
+// Wait for enough Cassandra servers are up before proceding,
+// Enough means count greater than or equal to replication factor.
+//
+import com.amazonaws.auth.*
+import com.amazonaws.services.simpledb.*
+import com.amazonaws.services.simpledb.model.*
+
+String accessKey = (String)System.getenv().get("AWS_ACCESS_KEY")
+String secretKey = (String)System.getenv().get("AWS_SECRET_KEY")
+String stackName = (String)System.getenv().get("STACK_NAME")
+String domain = stackName
+
+//def replicationFactor = System.getenv().get("CASSANDRA_REPLICATION_FACTOR")
+def cassNumServers = System.getenv().get("CASSANDRA_NUM_SERVERS")
+
+def creds = new BasicAWSCredentials(accessKey, secretKey)
+def sdbClient = new AmazonSimpleDBClient(creds)
+
+println "Waiting..."
+
+def count = 0
+while (true) {
+ try {
+ def selectResult = sdbClient.select(new SelectRequest((String)"select * from ${domain}"))
+ for (item in selectResult.getItems()) {
+ def att = item.getAttributes().get(0)
+ if (att.getValue().equals(stackName)) {
+ count++
+ }
+ }
+ if (count >= cassNumServers || count > 300) {
+ break
+ }
+ } catch (Exception e) {
+ println "ERROR waiting for Casasndra ${e.getMessage()}, will continue waiting"
+ return
+ }
+ Thread.sleep(1000)
+}
+
+println "Waiting done."
[23/50] [abbrv] git commit: Revert "removing 2 more as-yet unused
files"
Posted by sn...@apache.org.
Revert "removing 2 more as-yet unused files"
This reverts commit 2ab8ec4d2f69bf4b35ddf5087c47009078b404c5.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/a0a585ba
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/a0a585ba
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/a0a585ba
Branch: refs/heads/optimistic-tx-semantics
Commit: a0a585ba38cdb605f32cd04b1bcd1650da274eb8
Parents: 2ab8ec4
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 11:52:17 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 11:52:17 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/Gruntfile.js | 2 +
sdks/html5-javascript/lib/modules/util/Event.js | 33 +++++
.../lib/modules/util/Storable.js | 88 +++++++++++++
sdks/html5-javascript/usergrid.js | 132 +++++++++++++++++++
sdks/html5-javascript/usergrid.min.js | 4 +-
5 files changed, 257 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a0a585ba/sdks/html5-javascript/Gruntfile.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/Gruntfile.js b/sdks/html5-javascript/Gruntfile.js
index d48a950..cfa39e3 100644
--- a/sdks/html5-javascript/Gruntfile.js
+++ b/sdks/html5-javascript/Gruntfile.js
@@ -1,8 +1,10 @@
module.exports = function(grunt) {
var files = [
+ "lib/modules/util/Event.js",
"lib/modules/util/Logger.js",
"lib/modules/util/Promise.js",
"lib/modules/util/Ajax.js",
+ "lib/modules/util/Storable.js",
"lib/Usergrid.js",
"lib/modules/Client.js",
"lib/modules/Entity.js",
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a0a585ba/sdks/html5-javascript/lib/modules/util/Event.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Event.js b/sdks/html5-javascript/lib/modules/util/Event.js
new file mode 100644
index 0000000..146d03e
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/util/Event.js
@@ -0,0 +1,33 @@
+var UsergridEventable = function(){
+ throw Error("'UsergridEventable' is not intended to be invoked directly")
+}
+UsergridEventable.prototype = {
+ bind : function(event, fn){
+ this._events = this._events || {};
+ this._events[event] = this._events[event] || [];
+ this._events[event].push(fn);
+ },
+ unbind : function(event, fn){
+ this._events = this._events || {};
+ if( event in this._events === false ) return;
+ this._events[event].splice(this._events[event].indexOf(fn), 1);
+ },
+ trigger : function(event /* , args... */){
+ this._events = this._events || {};
+ if( event in this._events === false ) return;
+ for(var i = 0; i < this._events[event].length; i++){
+ this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1))
+ }
+ }
+};
+UsergridEventable.mixin = function(destObject){
+ var props = ['bind', 'unbind', 'trigger'];
+ for(var i = 0; i < props.length; i ++){
+ if(props[i] in destObject.prototype){
+ console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'.");
+ console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'.");
+ destObject.prototype['_'+props[i]]=destObject.prototype[props[i]];
+ }
+ destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]];
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a0a585ba/sdks/html5-javascript/lib/modules/util/Storable.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Storable.js b/sdks/html5-javascript/lib/modules/util/Storable.js
new file mode 100644
index 0000000..5c4da2e
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/util/Storable.js
@@ -0,0 +1,88 @@
+function UsergridStorable(storage, keyPrefix){
+ //throw Error("'UsergridStorable' is not intended to be invoked directly")
+}
+UsergridStorable.prototype.setStorage = function(storage) {
+ if(!(storage instanceof Storage)){
+ console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
+ storage=sessionStorage;
+ }
+ return this._storage=storage;
+};
+UsergridStorable.prototype.getStorage = function() {
+ if(!(this._storage instanceof Storage)){
+ console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
+ this._storage=sessionStorage;
+ }
+ return this._storage;
+};
+UsergridStorable.prototype.getStorageKey = function(key) {
+ if(!this._keyPrefix)this._keyPrefix='usergrid_js_sdk_';
+ return this._keyPrefix+key;
+};
+UsergridStorable.prototype.get=function(key){
+ var value;
+ if(arguments.length>1){
+ key=[].slice.call(arguments).reduce(function(p,c,i,a){
+ if(c instanceof Array){
+ p= p.concat(c);
+ }else{
+ p.push(c);
+ }
+ return p;
+ },[]);
+ }
+ if(this._storage instanceof Storage){
+ if(key instanceof Array){
+ var self=this;
+ value=key.map(function(k){return self.get(k)});
+ }else if("undefined" !== typeof key){
+ this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
+ value=this[key];
+ }
+ }
+ return value;
+}
+UsergridStorable.prototype.set=function(key, value){
+ if(this._storage instanceof Storage){
+ if(value){
+ this[key]=JSON.stringify(value);
+ this.getStorage().setItem(this.getStorageKey(key),this[key]);
+ }else{
+ delete this[key];
+ this.getStorage().removeItem(this.getStorageKey(key));
+ }
+ }
+}
+/*
+ * A public method to store the OAuth token for later use - uses localstorage if available
+ *
+ * @method setToken
+ * @public
+ * @params {string} token
+ * @return none
+ */
+UsergridStorable.prototype.setToken = function (token) {
+ return this.set('token', token);
+};
+
+/*
+ * A public method to get the OAuth token
+ *
+ * @method getToken
+ * @public
+ * @return {string} token
+ */
+UsergridStorable.prototype.getToken = function () {
+ return this.get('token');
+};
+UsergridStorable.mixin = function(destObject){
+ var props = ['getStorage', 'setStorage', 'getStorageKey', 'get', 'set', 'getToken', 'setToken'];
+ for(var i = 0; i < props.length; i ++){
+ if(props[i] in destObject.prototype){
+ console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'.");
+ console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'.");
+ destObject.prototype['_'+props[i]]=destObject.prototype[props[i]];
+ }
+ destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a0a585ba/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index b8debdf..ff83f6c 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -1,4 +1,40 @@
/*! usergrid@0.0.0 2014-02-11 */
+var UsergridEventable = function() {
+ throw Error("'UsergridEventable' is not intended to be invoked directly");
+};
+
+UsergridEventable.prototype = {
+ bind: function(event, fn) {
+ this._events = this._events || {};
+ this._events[event] = this._events[event] || [];
+ this._events[event].push(fn);
+ },
+ unbind: function(event, fn) {
+ this._events = this._events || {};
+ if (event in this._events === false) return;
+ this._events[event].splice(this._events[event].indexOf(fn), 1);
+ },
+ trigger: function(event) {
+ this._events = this._events || {};
+ if (event in this._events === false) return;
+ for (var i = 0; i < this._events[event].length; i++) {
+ this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
+ }
+ }
+};
+
+UsergridEventable.mixin = function(destObject) {
+ var props = [ "bind", "unbind", "trigger" ];
+ for (var i = 0; i < props.length; i++) {
+ if (props[i] in destObject.prototype) {
+ console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'.");
+ console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'.");
+ destObject.prototype["_" + props[i]] = destObject.prototype[props[i]];
+ }
+ destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]];
+ }
+};
+
//Logger
(function() {
var name = "Logger", global = this, overwrittenName = global[name], exports;
@@ -217,6 +253,102 @@
return global[name];
})();
+function UsergridStorable(storage, keyPrefix) {}
+
+UsergridStorable.prototype.setStorage = function(storage) {
+ if (!(storage instanceof Storage)) {
+ console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
+ storage = sessionStorage;
+ }
+ return this._storage = storage;
+};
+
+UsergridStorable.prototype.getStorage = function() {
+ if (!(this._storage instanceof Storage)) {
+ console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
+ this._storage = sessionStorage;
+ }
+ return this._storage;
+};
+
+UsergridStorable.prototype.getStorageKey = function(key) {
+ if (!this._keyPrefix) this._keyPrefix = "usergrid_js_sdk_";
+ return this._keyPrefix + key;
+};
+
+UsergridStorable.prototype.get = function(key) {
+ var value;
+ if (arguments.length > 1) {
+ key = [].slice.call(arguments).reduce(function(p, c, i, a) {
+ if (c instanceof Array) {
+ p = p.concat(c);
+ } else {
+ p.push(c);
+ }
+ return p;
+ }, []);
+ }
+ if (this._storage instanceof Storage) {
+ if (key instanceof Array) {
+ var self = this;
+ value = key.map(function(k) {
+ return self.get(k);
+ });
+ } else if ("undefined" !== typeof key) {
+ this[key] = JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
+ value = this[key];
+ }
+ }
+ return value;
+};
+
+UsergridStorable.prototype.set = function(key, value) {
+ if (this._storage instanceof Storage) {
+ if (value) {
+ this[key] = JSON.stringify(value);
+ this.getStorage().setItem(this.getStorageKey(key), this[key]);
+ } else {
+ delete this[key];
+ this.getStorage().removeItem(this.getStorageKey(key));
+ }
+ }
+};
+
+/*
+ * A public method to store the OAuth token for later use - uses localstorage if available
+ *
+ * @method setToken
+ * @public
+ * @params {string} token
+ * @return none
+ */
+UsergridStorable.prototype.setToken = function(token) {
+ return this.set("token", token);
+};
+
+/*
+ * A public method to get the OAuth token
+ *
+ * @method getToken
+ * @public
+ * @return {string} token
+ */
+UsergridStorable.prototype.getToken = function() {
+ return this.get("token");
+};
+
+UsergridStorable.mixin = function(destObject) {
+ var props = [ "getStorage", "setStorage", "getStorageKey", "get", "set", "getToken", "setToken" ];
+ for (var i = 0; i < props.length; i++) {
+ if (props[i] in destObject.prototype) {
+ console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'.");
+ console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'.");
+ destObject.prototype["_" + props[i]] = destObject.prototype[props[i]];
+ }
+ destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
+ }
+};
+
/*
* This module is a collection of classes designed to make working with
* the Appigee App Services API as easy as possible.
[19/50] [abbrv] git commit: Removing the indexeddb keystore as I
ended up not using it.
Posted by sn...@apache.org.
Removing the indexeddb keystore as I ended up not using it.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/0dc6c70b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/0dc6c70b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/0dc6c70b
Branch: refs/heads/optimistic-tx-semantics
Commit: 0dc6c70b7d5ce38b2985e6ef372a13aef0c6438f
Parents: 7b9048c
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 11:07:27 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 11:07:27 2014 -0500
----------------------------------------------------------------------
.../lib/modules/util/KeyStore.js | 199 -------------------
1 file changed, 199 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/0dc6c70b/sdks/html5-javascript/lib/modules/util/KeyStore.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/KeyStore.js b/sdks/html5-javascript/lib/modules/util/KeyStore.js
deleted file mode 100644
index 6a3ec1c..0000000
--- a/sdks/html5-javascript/lib/modules/util/KeyStore.js
+++ /dev/null
@@ -1,199 +0,0 @@
-//KeyStore
-var KeyStore = (function(global) {
- 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;
-
- var store="data",
- keyPath="key",
- database="test_keystore",
- version= 8,
- logger=new Logger('KeyStore');
- var db, objectStore;
- function createObjectStore(db, name, keyPath){
- var p = new Promise(), objectStore;
- try {
- objectStore = event.currentTarget.transaction.objectStore(store);
- //console.log(objectStore);
- if (!objectStore) throw "not found";
- } catch (e) {
- logger.warn("creating new objectStore",e);
- objectStore = db.createObjectStore(name, {
- keyPath: keyPath
- });
- } finally {
- objectStore.transaction.oncomplete = function(event) {
- // console.info("created ObjectStore: '%s'", store);
- p.done(null, objectStore);
- };
- }
- return p;
- }
- function createObjectStoreIndex(objectStore, keyPath){
- var p = new Promise(), index;
- try {
- index = objectStore.index(keyPath);
- if (!index) throw "not found";
- } catch (e) {
- objectStore.createIndex(keyPath, keyPath, {
- unique: true
- });
- } finally {
- // objectStore.transaction.oncomplete = function(event) {
- // console.info("created ObjectStore index: '%s'", keyPath);
- p.done(null, db);
- // };
- }
- return p;
- }
- function openDatabase(){
- var p = new Promise();
- var request = indexedDB.open(database, version);
- request.onerror = function(event) {
- console.error("internal keystore error: " + event.target.errorCode);
- p.done(event.target, null);
- };
- request.onupgradeneeded = function(event) {
- console.warn("upgrading internal keystore");
- Promise.chain([
- function(err, db){return createObjectStore(event.target.result, store, keyPath)},
- function(err, objectStore){return createObjectStoreIndex(objectStore, keyPath)}
- ])
- };
- request.onsuccess = function(event) {
- //console.info("successfully opened database %s", event.target.result);
- p.done(null, event.target.result);
- };
- return p;
- }
-
- function get(key) {
- var p=new Promise();
- openDatabase().then(function(err, db){
- var item = db.transaction(store, "readwrite").objectStore(store).index(keyPath).get(key);
- item.onsuccess = function(event) {
- // console.log(event.target.result);
- p.done(null, event.target.result);//request.result
- };
- item.onerror = function(event) {
- p.done(event.target.error, null);
- };
- })
- return p;
- }
- function save(key, value) {
- var p=new Promise();
- openDatabase().then(function(err, db){
- var _store=db.transaction(store, "readwrite").objectStore(store);
- var item = _store.index(keyPath).get(key);
- item.onsuccess = function(event) {
- //update
- _store.put({key:key,value:value}).onsuccess=function(){
- console.log("put");
- p.done(null, event.target.result);//request.result
- }
- };
- item.onerror = function(event) {
- _store.post({key:key,value:value}).onsuccess=function(){
- console.log("post");
- p.done(event.target.error, null);//request.result
- }
- //p.done(event.target.error, event.target.result);
- };
- })
- return p;
- }
- function remove(key) {
- var p=new Promise();
- openDatabase().then(function(err, db){
- var item = db.transaction(store, "readwrite").objectStore(store).delete(key);
- item.onsuccess = function(event) {
- p.done(null, event.target.result);//request.result
- };
- item.onerror = function(event) {
- p.done(event.target.error, event.target.result);
- };
- });
- return p;
- }
- function post(key, value) {
- var p=new Promise();
- openDatabase().then(function(err, db){
- var item = db.transaction(store, "readwrite").objectStore(store).add({key:key, value:value});
- item.onsuccess = function(event) {
- p.done(null, event.target.result);//request.result
- };
- item.onerror = function(event) {
- p.done(event.target.error, event.target.result);
- };
- })
- return p;
- }
- function put(key, value) {
- var p=new Promise();
- var item = db.transaction(store, "readwrite").objectStore(store).put(key, value);
- item.onsuccess = function(event) {
- p.done(null, event.target.result);//request.result
- };
- item.onerror = function(event) {
- p.done(event.target.error, event.target.result);
- };
- return p;
- }
- /*
- *
- * {databases:[{
- * name:'name'
- * version:1,
- * 'stores':[
- * {
- * name:'name',
- * options:{}
- * }
- * ]
- *
- * }]
- *
- */
- function KeyStoreFactory(options){
- this.data=options;
- var self=this;
- self.data.databases.forEach(function(database){
- console.log(database);
- //make DB request;
- });
- }
- KeyStoreFactory.prototype=new UsergridEvent();
- KeyStoreFactory.prototype.openDatabase=function(database){
- var self=this, p=new Promise();
- var request = indexedDB.open(database, version);
- request.onerror = function(event) {
- console.error("internal keystore error: " + event.target.errorCode);
- p.done(event.target, null);
- };
- request.onupgradeneeded = function(event) {
- console.warn("upgrading internal keystore");
- throw new UsergridKeystoreDatabaseUpgradeNeededError("internal keystore requires upgrade");
- /*Promise.chain([
- function(err, db){return createObjectStore(event.target.result, store, keyPath)},
- function(err, objectStore){return createObjectStoreIndex(objectStore, keyPath)}
- ])*/
- };
- request.onsuccess = function(event) {
- //console.info("successfully opened database %s", event.target.result);
- p.done(null, event.target.result);
- };
- return p;
- }
- global['KeyStoreFactory']=KeyStoreFactory;
- global['KeyStore']={
- openDatabase:openDatabase,
- get:get,
- put:put,
- post:post,
- save:save,
- remove:remove
- };
- return global['KeyStore'];
-}(this));
[48/50] [abbrv] git commit: Break WriteUniqueVerify tests into two
classes, one that uses Theories and one that uses Jukito.
Posted by sn...@apache.org.
Break WriteUniqueVerify tests into two classes, one that uses Theories and one that uses Jukito.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/2f786eba
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/2f786eba
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/2f786eba
Branch: refs/heads/two-dot-o
Commit: 2f786ebac2f9743bb3fe8fecd4df24fc7a3793be
Parents: 528afe5
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 14:51:09 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 14:51:09 2014 -0500
----------------------------------------------------------------------
.../mvcc/stage/write/WriteUniqueVerify.java | 54 +++++++++-----------
.../changelog/ChangeLogGeneratorImplTest.java | 4 +-
.../stage/write/WriteUniqueVerifyStageTest.java | 49 ++++++++++++++++++
.../mvcc/stage/write/WriteUniqueVerifyTest.java | 46 ++++++++++-------
.../util/InvalidValueGeneratorTest.java | 48 +++++++++++++++++
5 files changed, 152 insertions(+), 49 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
index 370fd0a..32dc577 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
@@ -48,7 +48,8 @@ import rx.util.functions.FuncN;
* This phase execute all unique value verification on the MvccEntity.
*/
@Singleton
-public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, Observable<? extends CollectionIoEvent<MvccEntity>>> {
+public class WriteUniqueVerify implements
+ Func1<CollectionIoEvent<MvccEntity>, Observable<? extends CollectionIoEvent<MvccEntity>>> {
private static final Logger LOG = LoggerFactory.getLogger( WriteUniqueVerify.class );
@@ -61,64 +62,58 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
@Inject
- public WriteUniqueVerify( final UniqueValueSerializationStrategy uniqueValueSerializiationStrategy,
+ public WriteUniqueVerify( final UniqueValueSerializationStrategy uvstrat,
final Scheduler scheduler, final SerializationFig serializationFig ) {
- Preconditions.checkNotNull( uniqueValueSerializiationStrategy, "uniqueValueSerializationStrategy is required" );
+ Preconditions.checkNotNull( uvstrat, "uniqueValueSerializationStrategy is required" );
Preconditions.checkNotNull( scheduler, "scheduler is required" );
Preconditions.checkNotNull( serializationFig, "serializationFig is required" );
- this.uniqueValueStrat = uniqueValueSerializiationStrategy;
+ this.uniqueValueStrat = uvstrat;
this.scheduler = scheduler;
this.serializationFig = serializationFig;
}
@Override
- public Observable<? extends CollectionIoEvent<MvccEntity>> call(final CollectionIoEvent<MvccEntity> ioevent ) {
+ public Observable<? extends CollectionIoEvent<MvccEntity>> call(
+ final CollectionIoEvent<MvccEntity> ioevent ) {
ValidationUtils.verifyMvccEntityWithEntity( ioevent.getEvent() );
final Entity entity = ioevent.getEvent().getEntity().get();
- // use simple thread pool to verify fields in parallel
-
- //TODO Dave: We don't want to use custom thread pools and futures here.
- // We want to use concurrent to fork all validations this way they're wrapped by timeouts and
- // Hystrix thread pools for JMX operations. See the WriteCommand in the EntityCollectionManagerImpl
- // I think it still needs added to the Concurrent utility class
-
-
final List<Observable<FieldUniquenessResult>> fields =
new ArrayList<Observable<FieldUniquenessResult>>();
-
-
- /**
- * Construct all the functions for verifying we're unique
- */
+ // Construct all the functions for verifying we're unique
for ( final Field field : entity.getFields() ) {
- //if it's unique, create a function to validate it and add it to the list of concurrent validations
- if ( !field.isUnique() ) {
+ // if it's unique, add a function to validate it
+ if ( field.isUnique() ) {
+
+ Observable<FieldUniquenessResult> result =
+ Observable.from( field ).subscribeOn( scheduler )
+ .map(new Func1<Field, FieldUniquenessResult>() {
- Observable<FieldUniquenessResult> result = Observable.from( field ).subscribeOn( scheduler ).map(new Func1<Field, FieldUniquenessResult>() {
@Override
public FieldUniquenessResult call(Field field ) {
// use write-first then read strategy
- UniqueValue written = new UniqueValueImpl( ioevent.getEntityCollection(), field, entity.getId(),
+ UniqueValue written = new UniqueValueImpl(
+ ioevent.getEntityCollection(), field, entity.getId(),
entity.getVersion() );
// use TTL in case something goes wrong before entity is finally committed
- MutationBatch mb = uniqueValueStrat.write( written, serializationFig.getTimeout() );
+ MutationBatch mb = uniqueValueStrat.write(
+ written, serializationFig.getTimeout() );
try {
mb.execute();
}
catch ( ConnectionException ex ) {
- throw new CollectionRuntimeException( "Error writing unique value " + field.toString(),
- ex );
+ throw new CollectionRuntimeException(
+ "Error writing unique value " + field.toString(), ex );
}
// does the database value match what we wrote?
@@ -146,12 +141,12 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
/**
* Zip the results up
*/
- final FuncN<CollectionIoEvent<MvccEntity>> zipFunction = new FuncN<CollectionIoEvent<MvccEntity>>() {
+ final FuncN<CollectionIoEvent<MvccEntity>> zipFunction =
+ new FuncN<CollectionIoEvent<MvccEntity>>() {
+
@Override
public CollectionIoEvent<MvccEntity> call( final Object... args ) {
-
-
for ( Object resultObj : args ) {
FieldUniquenessResult result = ( FieldUniquenessResult ) resultObj;
@@ -159,7 +154,8 @@ public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, O
if ( !result.isUnique() ) {
Field field = result.getField();
throw new CollectionRuntimeException(
- "Duplicate field value " + field.getName() + " = " + field.getValue().toString() );
+ "Duplicate field value " + field.getName()
+ + " = " + field.getValue().toString() );
}
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
index d64cc44..db79739 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/changelog/ChangeLogGeneratorImplTest.java
@@ -78,8 +78,8 @@ public class ChangeLogGeneratorImplTest {
/**
* Test that change log creation follows Todd's example.
- * TODO, can we do this without doing serialization I/O on the entities? This seems out of the scope of the changelog
- * itself
+ * TODO, can we do this without doing serialization I/O on the entities?
+ * This seems out of the scope of the changelog itself
*/
@Test
public void testBasicOperation() throws ConnectionException {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
new file mode 100644
index 0000000..78b7d13
--- /dev/null
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyStageTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.usergrid.persistence.collection.mvcc.stage.write;
+
+
+import org.jukito.UseModules;
+
+import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
+import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
+import org.apache.usergrid.persistence.collection.mvcc.stage.AbstractMvccEntityStageTest;
+import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
+import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
+import static org.mockito.Mockito.mock;
+import rx.Scheduler;
+
+
+/**
+ * TODO: Update the test to correctly test for detecting more than 1 duplicate and exception handling correctly
+ *
+ * @author tnine
+ */
+@UseModules( TestCollectionModule.class )
+public class WriteUniqueVerifyStageTest extends AbstractMvccEntityStageTest {
+
+ @Override
+ protected void validateStage( final CollectionIoEvent<MvccEntity> event ) {
+ UniqueValueSerializationStrategy uvstrat = mock( UniqueValueSerializationStrategy.class );
+ Scheduler scheduler = mock( Scheduler.class );
+ SerializationFig fig = mock( SerializationFig.class );
+ new WriteUniqueVerify( uvstrat, scheduler, fig ).call( event );
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
index da16a21..20dfa91 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
@@ -14,6 +14,22 @@
* limitations under the License. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
+ *//*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
*/
package org.apache.usergrid.persistence.collection.mvcc.stage.write;
@@ -30,7 +46,6 @@ import org.apache.usergrid.persistence.collection.cassandra.CassandraRule;
import org.apache.usergrid.persistence.collection.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
-import org.apache.usergrid.persistence.collection.mvcc.stage.AbstractMvccEntityStageTest;
import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
import org.apache.usergrid.persistence.model.entity.Entity;
@@ -52,13 +67,13 @@ import static org.mockito.Mockito.mock;
*/
@RunWith( JukitoRunner.class )
@UseModules( TestCollectionModule.class )
-public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
+public class WriteUniqueVerifyTest {
@ClassRule
public static CassandraRule rule = new CassandraRule();
@Inject
- private UniqueValueSerializationStrategy uniqueValueSerializiationStrategy;
+ private UniqueValueSerializationStrategy uvstrat;
@Inject
@@ -88,19 +103,19 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uvstrat, scheduler, fig );
- CollectionIoEvent<MvccEntity> result =
- newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
- .last();
+ CollectionIoEvent<MvccEntity> result = newStage.call(
+ new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) )
+ .toBlockingObservable().last();
assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
// verify the log entry is correct
MvccEntity entry = result.getEvent();
- // verify uuid and version in both the MvccEntity and the entity itself
- // assertSame is used on purpose. We want to make sure the same instance is used, not a copy.
+ // verify uuid and version in both the MvccEntity and the entity itself. assertSame is
+ // used on purpose. We want to make sure the same instance is used, not a copy.
// this way the caller's runtime type is retained.
assertSame( "id correct", entity.getId(), entry.getId() );
assertSame( "version did not not match entityId", entity.getVersion(), entry.getVersion() );
@@ -119,20 +134,15 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uvstrat, scheduler, fig );
- CollectionIoEvent<MvccEntity> result =
- newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
- .last();
+ CollectionIoEvent<MvccEntity> result = newStage.call(
+ new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) )
+ .toBlockingObservable().last();
assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
}
-
- @Override
- protected void validateStage( final CollectionIoEvent<MvccEntity> event ) {
- new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig ).call( event );
- }
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2f786eba/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
new file mode 100644
index 0000000..02b645f
--- /dev/null
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/util/InvalidValueGeneratorTest.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.usergrid.persistence.collection.util;
+
+import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
+import org.apache.usergrid.persistence.model.entity.Entity;
+import org.apache.usergrid.persistence.model.entity.Id;
+import org.junit.Assert;
+import org.junit.experimental.theories.Theories;
+import org.junit.experimental.theories.Theory;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+@RunWith( Theories.class )
+public class InvalidValueGeneratorTest {
+ private static final Logger LOG = LoggerFactory.getLogger( InvalidValueGeneratorTest.class );
+
+ @Theory
+ public void testInvalidValues(
+ @InvalidMvccEntityGenerator.IllegalFields final MvccEntity mvccEntityInvalid,
+ @InvalidEntityGenerator.IllegalFields final Entity entityInvalid,
+ @InvalidIdGenerator.IllegalFields final Id idInvalid) {
+
+ Assert.assertNotNull( mvccEntityInvalid.getId() );
+
+ Assert.assertNotNull( entityInvalid.getId() );
+
+ Assert.assertNotNull( idInvalid.getUuid() );
+ Assert.assertNotNull( idInvalid.getType() );
+ }
+}
[03/50] [abbrv] git commit: Merge pull request #50 from
timanglade/master
Posted by sn...@apache.org.
Merge pull request #50 from timanglade/master
Update contribution blurb
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/3d3ebf53
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/3d3ebf53
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/3d3ebf53
Branch: refs/heads/optimistic-tx-semantics
Commit: 3d3ebf532333bc81f4cb4e42921b5fb82a5bea8c
Parents: ad8d78f f9da5bb
Author: Nate McCall <zz...@gmail.com>
Authored: Mon Feb 10 09:57:44 2014 -0600
Committer: Nate McCall <zz...@gmail.com>
Committed: Mon Feb 10 09:57:44 2014 -0600
----------------------------------------------------------------------
stack/README.md | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
----------------------------------------------------------------------
[38/50] [abbrv] git commit: Missed a couple of package-rename spots
in query-validator,
there still one compilation problem in QueryValidatorRunner.
Posted by sn...@apache.org.
Missed a couple of package-rename spots in query-validator, there still one compilation problem in QueryValidatorRunner.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/482c5cef
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/482c5cef
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/482c5cef
Branch: refs/heads/optimistic-tx-semantics
Commit: 482c5ceffc9492af2828444d712492607a3baa32
Parents: ad8d78f
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 08:33:43 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 08:33:43 2014 -0500
----------------------------------------------------------------------
stack/query-validator/pom.xml | 33 +-
.../query/validator/ApiServerRunner.java | 212 ++++++++++++
.../usergrid/query/validator/QueryEntity.java | 34 ++
.../usergrid/query/validator/QueryRequest.java | 74 ++++
.../usergrid/query/validator/QueryResponse.java | 103 ++++++
.../usergrid/query/validator/QueryRunner.java | 28 ++
.../validator/QueryValidationConfiguration.java | 74 ++++
.../query/validator/QueryValidator.java | 77 +++++
.../usergrid/query/validator/SqliteRunner.java | 160 +++++++++
.../query/validator/ApiServerRunner.java | 212 ------------
.../usergrid/query/validator/QueryEntity.java | 34 --
.../usergrid/query/validator/QueryRequest.java | 74 ----
.../usergrid/query/validator/QueryResponse.java | 103 ------
.../usergrid/query/validator/QueryRunner.java | 28 --
.../validator/QueryValidationConfiguration.java | 74 ----
.../query/validator/QueryValidator.java | 77 -----
.../usergrid/query/validator/SqliteRunner.java | 160 ---------
.../query/validator/CassandraRunner.java | 199 +++++++++++
.../query/validator/QueryValidationTest.java | 339 +++++++++++++++++++
.../query/validator/QueryValidatorRunner.java | 207 +++++++++++
.../query/validator/QueryValidationTest.java | 339 -------------------
.../query/validator/QueryValidatorRunner.java | 209 ------------
stack/rest/pom.xml | 4 +-
23 files changed, 1513 insertions(+), 1341 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/pom.xml b/stack/query-validator/pom.xml
index 4f523a6..33c61f9 100644
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@ -5,7 +5,7 @@
<parent>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid</artifactId>
- <version>0.0.16-SNAPSHOT</version>
+ <version>0.0.29-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -97,16 +97,6 @@
</dependency>
<dependency>
<groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-count-batcher</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-count-common</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-test-utils</artifactId>
<version>${project.version}</version>
<scope>test</scope>
@@ -124,11 +114,6 @@
</dependency>
<dependency>
<groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-scheduler</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
<scope>test</scope>
@@ -212,22 +197,12 @@
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
+ <dependency>
+ <groupId>org.usergrid</groupId>
<artifactId>usergrid-java-client</artifactId>
<version>0.0.3</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-standalone</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
- </dependency>
</dependencies>
+
</project>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
new file mode 100644
index 0000000..c5f28e6
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
@@ -0,0 +1,212 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.lang.StringUtils;
+import org.codehaus.jackson.JsonNode;
+import org.springframework.http.HttpMethod;
+import org.springframework.stereotype.Component;
+import org.apache.usergrid.persistence.Entity;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import org.apache.usergrid.persistence.Schema;
+
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.usergrid.java.client.Client;
+import org.usergrid.java.client.response.ApiResponse;
+
+import static org.usergrid.java.client.utils.ObjectUtils.isEmpty;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+@Component
+public class ApiServerRunner implements QueryRunner {
+
+ private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
+ private Client client;
+
+ private String org;
+ private String app;
+ private String baseUri;
+ private String email;
+ private String password;
+ private String collection;
+ private List<Entity> entities;
+
+ @Override
+ public boolean setup() {
+ client = new Client(getOrg(), getApp()).withApiUrl(getBaseUri());
+ String accessToken = authorize(email, password);
+ if(!StringUtils.isEmpty(accessToken))
+ client.setAccessToken(accessToken);
+ return insertDatas();
+ }
+
+ public String authorize(String email, String password) {
+ String accessToken = null;
+ Map<String, Object> formData = new HashMap<String, Object>();
+ formData.put("grant_type", "password");
+ formData.put("username", email);
+ formData.put("password", password);
+ ApiResponse response = client.apiRequest(HttpMethod.POST, null, formData,
+ "management", "token");
+ if (!isEmpty(response.getAccessToken())) {
+ accessToken = response.getAccessToken();
+ logger.info("Access token: " + accessToken);
+ } else {
+ logger.info("Response: " + response);
+ }
+ return accessToken;
+ }
+
+ public boolean insertDatas() {
+ List<org.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
+ for(org.usergrid.java.client.entities.Entity entity : clientEntities) {
+ ApiResponse response = client.createEntity(entity);
+ if( response == null || !StringUtils.isEmpty(response.getError()) ) {
+ logger.log(Level.SEVERE, response.getErrorDescription());
+ //throw new RuntimeException(response.getErrorDescription());
+ } else {
+ logger.log(Level.INFO, response.toString());
+ }
+ }
+ return true;
+ }
+
+ private List<org.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
+ List<org.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.usergrid.java.client.entities.Entity>();
+ for(Entity entity : entities) {
+ org.usergrid.java.client.entities.Entity clientEntity = new org.usergrid.java.client.entities.Entity();
+ clientEntity.setType(entity.getType());
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ Object value = entity.getProperty(key);
+ if( value instanceof String )
+ clientEntity.setProperty(key,(String)value );
+ else if( value instanceof Long )
+ clientEntity.setProperty(key,(Long)value );
+ else if( value instanceof Integer )
+ clientEntity.setProperty(key,(Integer)value );
+ else if( value instanceof Float )
+ clientEntity.setProperty(key,(Float)value );
+ else if( value instanceof Boolean )
+ clientEntity.setProperty(key,(Boolean)value );
+ }
+ clientEntities.add(clientEntity);
+ }
+ return clientEntities;
+ }
+
+ @Override
+ public List<Entity> execute(String query) {
+ return execute(query, 10);
+ }
+
+ @Override
+ public List<Entity> execute(String query, int limit) {
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put("ql", query);
+ params.put("limit", limit);
+ ApiResponse response = client.apiRequest(HttpMethod.GET, params, null, getOrg(), getApp(), getCollection());
+ List<Entity> entities = new ArrayList<Entity>();
+ if( response.getEntities() == null )
+ return entities;
+
+ for(org.usergrid.java.client.entities.Entity clientEntitity : response.getEntities()) {
+ Entity entity = new QueryEntity();
+ entity.setUuid(clientEntitity.getUuid());
+ entity.setType(clientEntitity.getType());
+ Map<String, JsonNode> values = clientEntitity.getProperties();
+ for( String key : values.keySet() ) {
+ JsonNode node = values.get(key);
+ if( node.isBoolean() ) {
+ entity.setProperty(key, node.asBoolean());
+ } else if( node.isInt() ) {
+ entity.setProperty(key, node.asInt());
+ } else if( node.isLong() ) {
+ entity.setProperty(key, node.asLong());
+ } else if( node.isDouble() ) {
+ entity.setProperty(key, node.asDouble());
+ } else {
+ entity.setProperty(key, node.asText());
+ }
+ }
+ entities.add(entity);
+ }
+ return entities;
+ }
+
+ public String getOrg() {
+ return org;
+ }
+
+ public void setOrg(String org) {
+ this.org = org;
+ }
+
+ public String getApp() {
+ return app;
+ }
+
+ public void setApp(String app) {
+ this.app = app;
+ }
+
+ public String getBaseUri() {
+ return baseUri;
+ }
+
+ public void setBaseUri(String baseUri) {
+ this.baseUri = baseUri;
+ }
+
+ public String getCollection() {
+ return collection;
+ }
+
+ public void setCollection(String collection) {
+ this.collection = collection;
+ }
+
+ public List<Entity> getEntities() {
+ return entities;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
new file mode 100644
index 0000000..77893bd
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
@@ -0,0 +1,34 @@
+package org.apache.usergrid.query.validator;
+
+import org.apache.usergrid.persistence.DynamicEntity;
+
+import java.util.Map;
+
+public class QueryEntity extends DynamicEntity {
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ if(!(obj instanceof QueryEntity))
+ return false;
+
+ QueryEntity other = (QueryEntity)obj;
+ Map<String, Object> properties = this.getProperties();
+ Map<String, Object> otherProperties = other.getProperties();
+ for(String key : properties.keySet()) {
+ if( "created".equals(key) || "modified".equals(key) )
+ continue;
+
+ Object value = properties.get(key);
+ Object otherValue = otherProperties.get(key);
+ if( otherValue == null || !value.equals(otherValue) )
+ return false;
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
new file mode 100644
index 0000000..d2989c7
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+public class QueryRequest {
+ private String dbQuery;
+ private ApiQuery apiQuery;
+ private boolean ignoreOrdering;
+
+ public QueryRequest() {
+ this.apiQuery = new ApiQuery();
+ }
+
+ public String getDbQuery() {
+ return dbQuery;
+ }
+
+ public void setDbQuery(String dbQuery) {
+ this.dbQuery = dbQuery;
+ }
+
+ public ApiQuery getApiQuery() {
+ return apiQuery;
+ }
+
+ static public class ApiQuery {
+ private String query;
+ private int limit;
+
+ public ApiQuery() {
+ limit = 10;
+ }
+
+ public String getQuery() {
+ return query;
+ }
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ public int getLimit() {
+ return limit;
+ }
+
+ public void setLimit(int limit) {
+ this.limit = limit;
+ }
+ }
+
+ public boolean isIgnoreOrdering() {
+ return ignoreOrdering;
+ }
+
+ public void setIgnoreOrdering(boolean ignoreOrdering) {
+ this.ignoreOrdering = ignoreOrdering;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
new file mode 100644
index 0000000..aa152d5
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
@@ -0,0 +1,103 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.usergrid.persistence.Entity;
+
+import java.util.List;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+public class QueryResponse {
+
+ boolean result;
+ List<Entity> expacted;
+ List<Entity> actually;
+ String description;
+ QueryRequest request;
+
+ public boolean result() {
+ return result;
+ }
+
+ public void setResult(boolean result) {
+ this.result = result;
+ }
+
+ public List<Entity> getExpacted() {
+ return expacted;
+ }
+
+ public void setExpacted(List<Entity> expacted) {
+ this.expacted = expacted;
+ }
+
+ public List<Entity> getActually() {
+ return actually;
+ }
+
+ public void setActually(List<Entity> actually) {
+ this.actually = actually;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public QueryRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(QueryRequest request) {
+ this.request = request;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("", 20, "-"));
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("* Expected", 20, " "));
+ builder.append("\n");
+ builder.append("list size : " + expacted.size());
+ builder.append("\n");
+ for(Entity entity : expacted) {
+ builder.append(entity.toString());
+ builder.append("\n");
+ }
+
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("* Actually", 20, " "));
+ builder.append("\n");
+ builder.append("list size : " + actually.size());
+ builder.append("\n");
+ for(Entity entity : actually) {
+ builder.append(entity.toString());
+ builder.append("\n");
+ }
+
+ builder.append(StringUtils.rightPad("", 20, "-"));
+ builder.append("\n");
+ return builder.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
new file mode 100644
index 0000000..06341d6
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import java.util.List;
+import org.apache.usergrid.persistence.Entity;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+public interface QueryRunner {
+ public boolean setup();
+ public List<Entity> execute(String query);
+ public List<Entity> execute(String query, int limit);
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
new file mode 100644
index 0000000..8b14737
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
@@ -0,0 +1,74 @@
+package org.apache.usergrid.query.validator;
+
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.utils.InflectionUtils;
+
+import java.util.List;
+
+public class QueryValidationConfiguration {
+
+ String org;
+ String app;
+ String endpointUri;
+ String email;
+ String password;
+ String collection;
+ List<Entity> entities;
+
+ public String getCollection() {
+ return collection;
+ }
+
+ public void setCollection(String collection) {
+ String pluralizeName = InflectionUtils.pluralize(collection);
+ this.collection = pluralizeName;
+ }
+
+ public String getOrg() {
+ return org;
+ }
+
+ public void setOrg(String org) {
+ this.org = org;
+ }
+
+ public String getApp() {
+ return app;
+ }
+
+ public void setApp(String app) {
+ this.app = app;
+ }
+
+ public String getEndpointUri() {
+ return endpointUri;
+ }
+
+ public void setEndpointUri(String endpointUri) {
+ this.endpointUri = endpointUri;
+ }
+
+ public List<Entity> getEntities() {
+ return entities;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
new file mode 100644
index 0000000..180a8e5
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.apache.usergrid.persistence.Entity;
+
+import java.util.List;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+@Component
+public class QueryValidator {
+
+ QueryValidationConfiguration configuration;
+ @Autowired
+ ApiServerRunner api;
+ @Autowired
+ SqliteRunner sql;
+
+ public QueryValidator() {
+ }
+
+ public QueryValidator(QueryValidationConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public boolean setup() {
+ return api.setup() && sql.setup();
+ }
+
+ public QueryResponse execute(QueryRequest request) {
+ List<Entity> sqlEntities = sql.execute(request.getDbQuery());
+ List<Entity> apiEntities = api.execute(request.getApiQuery().getQuery(), request.getApiQuery().getLimit());
+ boolean equals = false;
+ if( request.isIgnoreOrdering() ) {
+ equals = sqlEntities.size() == apiEntities.size();
+ } else {
+ equals = sqlEntities.equals(apiEntities);
+ }
+
+ QueryResponse response = new QueryResponse();
+ response.setResult(equals);
+ response.setExpacted(sqlEntities);
+ response.setActually(apiEntities);
+ return response;
+ }
+
+ public void setConfiguration(QueryValidationConfiguration configuration) {
+ this.configuration = configuration;
+ sql.setCollection(configuration.getCollection());
+ sql.setEntities(configuration.getEntities());
+
+ api.setOrg(configuration.getOrg());
+ api.setApp(configuration.getApp());
+ api.setBaseUri(configuration.getEndpointUri());
+ api.setCollection(configuration.getCollection());
+ api.setEntities(configuration.getEntities());
+ api.setEmail(configuration.getEmail());
+ api.setPassword(configuration.getPassword());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
new file mode 100644
index 0000000..a1932a0
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
@@ -0,0 +1,160 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.RowMapper;
+import org.springframework.stereotype.Component;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.persistence.Schema;
+
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+@Component
+public class SqliteRunner implements QueryRunner {
+
+ private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
+
+ @Autowired
+ private JdbcTemplate jdbcTemplate;
+ private String collection;
+ private List<Entity> entities;
+
+ @Override
+ public boolean setup() {
+ createTable();
+ insertDatas();
+
+ return true;
+ }
+
+ private void insertDatas() {
+ for( Entity entity : entities ) {
+ insertData(entity);
+ }
+ }
+
+ private void insertData(Entity entity) {
+ StringBuilder feilds = new StringBuilder();
+ StringBuilder values = new StringBuilder();
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ feilds.append(key);
+ feilds.append(",");
+
+ Object value = entity.getProperty(key);
+ Class type = value.getClass();
+ String sqlType = getSqlDatatype(type);
+ if( StringUtils.equals("TEXT", sqlType) ) {
+ values.append("'");
+ values.append(value);
+ values.append("'");
+ } else {
+ values.append(value);
+ }
+ values.append(",");
+ }
+ feilds.deleteCharAt(feilds.length()-1);
+ values.deleteCharAt(values.length()-1);
+
+ StringBuilder builder = new StringBuilder();
+ builder.append("INSERT INTO ");
+ builder.append(collection);
+ builder.append("(");
+ builder.append(feilds);
+ builder.append(")");
+ builder.append(" VALUES(");
+ builder.append(values);
+ builder.append(")");
+ logger.info(builder.toString());
+ jdbcTemplate.execute(builder.toString());
+ }
+
+ private void createTable() {
+ Entity entity = entities.get(0);
+ StringBuilder builder = new StringBuilder();
+ builder.append("CREATE TABLE ");
+ builder.append(collection);
+ builder.append("(");
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ builder.append(key);
+ builder.append(" ");
+
+ Class type = entity.getProperty(key).getClass();
+ String sqlType = getSqlDatatype(type);
+ builder.append(sqlType);
+ builder.append(",");
+ }
+ builder.deleteCharAt(builder.length()-1);
+ builder.append(")");
+
+ jdbcTemplate.execute("DROP TABLE IF EXISTS " + collection);
+ logger.info(builder.toString());
+ jdbcTemplate.execute(builder.toString());
+ }
+
+ @Override
+ public List<Entity> execute(String query) {
+ List<Entity> entities = jdbcTemplate.query(query, new RowMapper<Entity>() {
+ @Override
+ public Entity mapRow(ResultSet rs, int i) throws SQLException {
+ ResultSetMetaData rsmd = rs.getMetaData();
+ Entity entity = new QueryEntity();
+ for( int j = 1 ; j <= rsmd.getColumnCount() ; j++) {
+ entity.setProperty(rsmd.getColumnName(j), rs.getObject(j));
+ }
+ return entity;
+ }
+ });
+ return entities;
+ }
+
+ @Override
+ public List<Entity> execute(String query, int limit) {
+ return execute(query);
+ }
+
+ // based on sqlite (http://www.sqlite.org/datatype3.html)
+ private String getSqlDatatype(Class clz) {
+ if( clz == Integer.class || clz == Long.class || clz == Boolean.class ) {
+ return "INTEGER";
+ } else if( clz == Double.class ) {
+ return "REAL";
+ } else if( clz == Byte.class ) {
+ return "BLOB";
+ }
+ return "TEXT";
+ }
+
+ public void setCollection(String collection) {
+ this.collection = collection;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
deleted file mode 100644
index c53d08b..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.jackson.JsonNode;
-import org.springframework.http.HttpMethod;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.java.client.response.ApiResponse;
-import org.apache.usergrid.persistence.Entity;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import org.apache.usergrid.java.client.Client;
-import org.apache.usergrid.persistence.Schema;
-
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.apache.usergrid.java.client.utils.ObjectUtils.isEmpty;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-@Component
-public class ApiServerRunner implements QueryRunner {
-
- private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
- private Client client;
-
- private String org;
- private String app;
- private String baseUri;
- private String email;
- private String password;
- private String collection;
- private List<Entity> entities;
-
- @Override
- public boolean setup() {
- client = new Client(getOrg(), getApp()).withApiUrl(getBaseUri());
- String accessToken = authorize(email, password);
- if(!StringUtils.isEmpty(accessToken))
- client.setAccessToken(accessToken);
- return insertDatas();
- }
-
- public String authorize(String email, String password) {
- String accessToken = null;
- Map<String, Object> formData = new HashMap<String, Object>();
- formData.put("grant_type", "password");
- formData.put("username", email);
- formData.put("password", password);
- ApiResponse response = client.apiRequest(HttpMethod.POST, null, formData,
- "management", "token");
- if (!isEmpty(response.getAccessToken())) {
- accessToken = response.getAccessToken();
- logger.info("Access token: " + accessToken);
- } else {
- logger.info("Response: " + response);
- }
- return accessToken;
- }
-
- public boolean insertDatas() {
- List<org.apache.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
- for(org.apache.usergrid.java.client.entities.Entity entity : clientEntities) {
- ApiResponse response = client.createEntity(entity);
- if( response == null || !StringUtils.isEmpty(response.getError()) ) {
- logger.log(Level.SEVERE, response.getErrorDescription());
- //throw new RuntimeException(response.getErrorDescription());
- } else {
- logger.log(Level.INFO, response.toString());
- }
- }
- return true;
- }
-
- private List<org.apache.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
- List<org.apache.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.apache.usergrid.java.client.entities.Entity>();
- for(Entity entity : entities) {
- org.apache.usergrid.java.client.entities.Entity clientEntity = new org.apache.usergrid.java.client.entities.Entity();
- clientEntity.setType(entity.getType());
- Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
- for(String key : properties.keySet()) {
- Object value = entity.getProperty(key);
- if( value instanceof String )
- clientEntity.setProperty(key,(String)value );
- else if( value instanceof Long )
- clientEntity.setProperty(key,(Long)value );
- else if( value instanceof Integer )
- clientEntity.setProperty(key,(Integer)value );
- else if( value instanceof Float )
- clientEntity.setProperty(key,(Float)value );
- else if( value instanceof Boolean )
- clientEntity.setProperty(key,(Boolean)value );
- }
- clientEntities.add(clientEntity);
- }
- return clientEntities;
- }
-
- @Override
- public List<Entity> execute(String query) {
- return execute(query, 10);
- }
-
- @Override
- public List<Entity> execute(String query, int limit) {
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("ql", query);
- params.put("limit", limit);
- ApiResponse response = client.apiRequest(HttpMethod.GET, params, null, getOrg(), getApp(), getCollection());
- List<Entity> entities = new ArrayList<Entity>();
- if( response.getEntities() == null )
- return entities;
-
- for(org.apache.usergrid.java.client.entities.Entity clientEntitity : response.getEntities()) {
- Entity entity = new QueryEntity();
- entity.setUuid(clientEntitity.getUuid());
- entity.setType(clientEntitity.getType());
- Map<String, JsonNode> values = clientEntitity.getProperties();
- for( String key : values.keySet() ) {
- JsonNode node = values.get(key);
- if( node.isBoolean() ) {
- entity.setProperty(key, node.asBoolean());
- } else if( node.isInt() ) {
- entity.setProperty(key, node.asInt());
- } else if( node.isLong() ) {
- entity.setProperty(key, node.asLong());
- } else if( node.isDouble() ) {
- entity.setProperty(key, node.asDouble());
- } else {
- entity.setProperty(key, node.asText());
- }
- }
- entities.add(entity);
- }
- return entities;
- }
-
- public String getOrg() {
- return org;
- }
-
- public void setOrg(String org) {
- this.org = org;
- }
-
- public String getApp() {
- return app;
- }
-
- public void setApp(String app) {
- this.app = app;
- }
-
- public String getBaseUri() {
- return baseUri;
- }
-
- public void setBaseUri(String baseUri) {
- this.baseUri = baseUri;
- }
-
- public String getCollection() {
- return collection;
- }
-
- public void setCollection(String collection) {
- this.collection = collection;
- }
-
- public List<Entity> getEntities() {
- return entities;
- }
-
- public void setEntities(List<Entity> entities) {
- this.entities = entities;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
deleted file mode 100644
index 77893bd..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package org.apache.usergrid.query.validator;
-
-import org.apache.usergrid.persistence.DynamicEntity;
-
-import java.util.Map;
-
-public class QueryEntity extends DynamicEntity {
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- if(!(obj instanceof QueryEntity))
- return false;
-
- QueryEntity other = (QueryEntity)obj;
- Map<String, Object> properties = this.getProperties();
- Map<String, Object> otherProperties = other.getProperties();
- for(String key : properties.keySet()) {
- if( "created".equals(key) || "modified".equals(key) )
- continue;
-
- Object value = properties.get(key);
- Object otherValue = otherProperties.get(key);
- if( otherValue == null || !value.equals(otherValue) )
- return false;
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
deleted file mode 100644
index d2989c7..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-public class QueryRequest {
- private String dbQuery;
- private ApiQuery apiQuery;
- private boolean ignoreOrdering;
-
- public QueryRequest() {
- this.apiQuery = new ApiQuery();
- }
-
- public String getDbQuery() {
- return dbQuery;
- }
-
- public void setDbQuery(String dbQuery) {
- this.dbQuery = dbQuery;
- }
-
- public ApiQuery getApiQuery() {
- return apiQuery;
- }
-
- static public class ApiQuery {
- private String query;
- private int limit;
-
- public ApiQuery() {
- limit = 10;
- }
-
- public String getQuery() {
- return query;
- }
-
- public void setQuery(String query) {
- this.query = query;
- }
-
- public int getLimit() {
- return limit;
- }
-
- public void setLimit(int limit) {
- this.limit = limit;
- }
- }
-
- public boolean isIgnoreOrdering() {
- return ignoreOrdering;
- }
-
- public void setIgnoreOrdering(boolean ignoreOrdering) {
- this.ignoreOrdering = ignoreOrdering;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
deleted file mode 100644
index aa152d5..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.usergrid.persistence.Entity;
-
-import java.util.List;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-public class QueryResponse {
-
- boolean result;
- List<Entity> expacted;
- List<Entity> actually;
- String description;
- QueryRequest request;
-
- public boolean result() {
- return result;
- }
-
- public void setResult(boolean result) {
- this.result = result;
- }
-
- public List<Entity> getExpacted() {
- return expacted;
- }
-
- public void setExpacted(List<Entity> expacted) {
- this.expacted = expacted;
- }
-
- public List<Entity> getActually() {
- return actually;
- }
-
- public void setActually(List<Entity> actually) {
- this.actually = actually;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public QueryRequest getRequest() {
- return request;
- }
-
- public void setRequest(QueryRequest request) {
- this.request = request;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("\n");
- builder.append(StringUtils.rightPad("", 20, "-"));
- builder.append("\n");
- builder.append(StringUtils.rightPad("* Expected", 20, " "));
- builder.append("\n");
- builder.append("list size : " + expacted.size());
- builder.append("\n");
- for(Entity entity : expacted) {
- builder.append(entity.toString());
- builder.append("\n");
- }
-
- builder.append("\n");
- builder.append(StringUtils.rightPad("* Actually", 20, " "));
- builder.append("\n");
- builder.append("list size : " + actually.size());
- builder.append("\n");
- for(Entity entity : actually) {
- builder.append(entity.toString());
- builder.append("\n");
- }
-
- builder.append(StringUtils.rightPad("", 20, "-"));
- builder.append("\n");
- return builder.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
deleted file mode 100644
index 06341d6..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import java.util.List;
-import org.apache.usergrid.persistence.Entity;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-public interface QueryRunner {
- public boolean setup();
- public List<Entity> execute(String query);
- public List<Entity> execute(String query, int limit);
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
deleted file mode 100644
index 8b14737..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package org.apache.usergrid.query.validator;
-
-import org.apache.usergrid.persistence.Entity;
-import org.apache.usergrid.utils.InflectionUtils;
-
-import java.util.List;
-
-public class QueryValidationConfiguration {
-
- String org;
- String app;
- String endpointUri;
- String email;
- String password;
- String collection;
- List<Entity> entities;
-
- public String getCollection() {
- return collection;
- }
-
- public void setCollection(String collection) {
- String pluralizeName = InflectionUtils.pluralize(collection);
- this.collection = pluralizeName;
- }
-
- public String getOrg() {
- return org;
- }
-
- public void setOrg(String org) {
- this.org = org;
- }
-
- public String getApp() {
- return app;
- }
-
- public void setApp(String app) {
- this.app = app;
- }
-
- public String getEndpointUri() {
- return endpointUri;
- }
-
- public void setEndpointUri(String endpointUri) {
- this.endpointUri = endpointUri;
- }
-
- public List<Entity> getEntities() {
- return entities;
- }
-
- public void setEntities(List<Entity> entities) {
- this.entities = entities;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
deleted file mode 100644
index 180a8e5..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.persistence.Entity;
-
-import java.util.List;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-@Component
-public class QueryValidator {
-
- QueryValidationConfiguration configuration;
- @Autowired
- ApiServerRunner api;
- @Autowired
- SqliteRunner sql;
-
- public QueryValidator() {
- }
-
- public QueryValidator(QueryValidationConfiguration configuration) {
- this.configuration = configuration;
- }
-
- public boolean setup() {
- return api.setup() && sql.setup();
- }
-
- public QueryResponse execute(QueryRequest request) {
- List<Entity> sqlEntities = sql.execute(request.getDbQuery());
- List<Entity> apiEntities = api.execute(request.getApiQuery().getQuery(), request.getApiQuery().getLimit());
- boolean equals = false;
- if( request.isIgnoreOrdering() ) {
- equals = sqlEntities.size() == apiEntities.size();
- } else {
- equals = sqlEntities.equals(apiEntities);
- }
-
- QueryResponse response = new QueryResponse();
- response.setResult(equals);
- response.setExpacted(sqlEntities);
- response.setActually(apiEntities);
- return response;
- }
-
- public void setConfiguration(QueryValidationConfiguration configuration) {
- this.configuration = configuration;
- sql.setCollection(configuration.getCollection());
- sql.setEntities(configuration.getEntities());
-
- api.setOrg(configuration.getOrg());
- api.setApp(configuration.getApp());
- api.setBaseUri(configuration.getEndpointUri());
- api.setCollection(configuration.getCollection());
- api.setEntities(configuration.getEntities());
- api.setEmail(configuration.getEmail());
- api.setPassword(configuration.getPassword());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
deleted file mode 100644
index a1932a0..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.core.RowMapper;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.persistence.Entity;
-import org.apache.usergrid.persistence.Schema;
-
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Logger;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-@Component
-public class SqliteRunner implements QueryRunner {
-
- private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
-
- @Autowired
- private JdbcTemplate jdbcTemplate;
- private String collection;
- private List<Entity> entities;
-
- @Override
- public boolean setup() {
- createTable();
- insertDatas();
-
- return true;
- }
-
- private void insertDatas() {
- for( Entity entity : entities ) {
- insertData(entity);
- }
- }
-
- private void insertData(Entity entity) {
- StringBuilder feilds = new StringBuilder();
- StringBuilder values = new StringBuilder();
- Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
- for(String key : properties.keySet()) {
- feilds.append(key);
- feilds.append(",");
-
- Object value = entity.getProperty(key);
- Class type = value.getClass();
- String sqlType = getSqlDatatype(type);
- if( StringUtils.equals("TEXT", sqlType) ) {
- values.append("'");
- values.append(value);
- values.append("'");
- } else {
- values.append(value);
- }
- values.append(",");
- }
- feilds.deleteCharAt(feilds.length()-1);
- values.deleteCharAt(values.length()-1);
-
- StringBuilder builder = new StringBuilder();
- builder.append("INSERT INTO ");
- builder.append(collection);
- builder.append("(");
- builder.append(feilds);
- builder.append(")");
- builder.append(" VALUES(");
- builder.append(values);
- builder.append(")");
- logger.info(builder.toString());
- jdbcTemplate.execute(builder.toString());
- }
-
- private void createTable() {
- Entity entity = entities.get(0);
- StringBuilder builder = new StringBuilder();
- builder.append("CREATE TABLE ");
- builder.append(collection);
- builder.append("(");
- Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
- for(String key : properties.keySet()) {
- builder.append(key);
- builder.append(" ");
-
- Class type = entity.getProperty(key).getClass();
- String sqlType = getSqlDatatype(type);
- builder.append(sqlType);
- builder.append(",");
- }
- builder.deleteCharAt(builder.length()-1);
- builder.append(")");
-
- jdbcTemplate.execute("DROP TABLE IF EXISTS " + collection);
- logger.info(builder.toString());
- jdbcTemplate.execute(builder.toString());
- }
-
- @Override
- public List<Entity> execute(String query) {
- List<Entity> entities = jdbcTemplate.query(query, new RowMapper<Entity>() {
- @Override
- public Entity mapRow(ResultSet rs, int i) throws SQLException {
- ResultSetMetaData rsmd = rs.getMetaData();
- Entity entity = new QueryEntity();
- for( int j = 1 ; j <= rsmd.getColumnCount() ; j++) {
- entity.setProperty(rsmd.getColumnName(j), rs.getObject(j));
- }
- return entity;
- }
- });
- return entities;
- }
-
- @Override
- public List<Entity> execute(String query, int limit) {
- return execute(query);
- }
-
- // based on sqlite (http://www.sqlite.org/datatype3.html)
- private String getSqlDatatype(Class clz) {
- if( clz == Integer.class || clz == Long.class || clz == Boolean.class ) {
- return "INTEGER";
- } else if( clz == Double.class ) {
- return "REAL";
- } else if( clz == Byte.class ) {
- return "BLOB";
- }
- return "TEXT";
- }
-
- public void setCollection(String collection) {
- this.collection = collection;
- }
-
- public void setEntities(List<Entity> entities) {
- this.entities = entities;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/CassandraRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/CassandraRunner.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/CassandraRunner.java
new file mode 100644
index 0000000..802f842
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/CassandraRunner.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2014 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.InitializationError;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+import java.io.File;
+import java.lang.annotation.Annotation;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.apache.cassandra.service.CassandraDaemon;
+import org.apache.usergrid.cassandra.DataControl;
+import org.apache.usergrid.cassandra.SchemaManager;
+
+public class CassandraRunner extends BlockJUnit4ClassRunner {
+
+ private static final String TMP = "tmp";
+ private static Logger logger = LoggerFactory.getLogger(CassandraRunner.class);
+ private static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
+ private static ContextHolder contextHolder;
+ private SchemaManager schemaManager;
+
+ // TODO maybe put a 'holder' object in the executor and provide access to application context thusly?
+ // TODO assume a static 'usergrid-test-context.xml' primer/starter file
+
+ public CassandraRunner(Class<?> klass) throws InitializationError {
+ super(klass);
+ logger.info("CassandraRunner started with class {}", klass.getName());
+ }
+
+
+ public static <T> T getBean(String name, Class<T> requiredType) {
+ return contextHolder.applicationContext.getBean(name, requiredType);
+ }
+
+ public static <T> T getBean(Class<T> requiredType) {
+ return contextHolder.applicationContext.getBean(requiredType);
+ }
+
+ /**
+ * Class-level run. The order of events are as follows:
+ * - load spring (if not loaded)
+ * - init cassandra (if not started)
+ * - look for DataControl annotation on class and delegate
+ * @param notifier
+ */
+ @Override
+ public void run(RunNotifier notifier) {
+ DataControl control = preTest(notifier);
+ super.run(notifier);
+ postTest(notifier, control);
+
+ }
+
+ protected DataControl preTest(RunNotifier notifier){
+ maybeInit();
+
+ // check for SchemaManager annotation
+ DataControl control = null;
+ for(Annotation ann : getTestClass().getAnnotations() ) {
+ logger.info("examining annotation " + ann);
+ if ( ann instanceof DataControl ) {
+ logger.info("founda dataCOntrol annotation");
+ control = (DataControl)ann;
+ }
+ }
+ loadDataControl(control);
+ maybeCreateSchema();
+
+ return control;
+ }
+
+ protected void postTest(RunNotifier notifier, DataControl control){
+ if ( control == null || !control.skipTruncate() ) {
+ schemaManager.destroy();
+ }
+ logger.info("shutting down context");
+ contextHolder.applicationContext.stop();
+
+ }
+
+
+ private void loadDataControl(DataControl dataControl) {
+ if ( !contextHolder.applicationContext.isActive() ) {
+ logger.info("restarting context...");
+ contextHolder.applicationContext.refresh();
+ }
+
+ if ( dataControl != null ) {
+ // TODO check for classpath and go static?
+ logger.info("dataControl found - looking upma SchemaManager impl");
+ schemaManager = getBean(dataControl.schemaManager(), SchemaManager.class);
+ } else {
+ logger.info("dataControl not found - using default SchemaManager impl");
+ schemaManager = getBean(SchemaManager.class);
+ }
+
+
+ }
+
+ private boolean maybeCreateSchema() {
+ if ( schemaManager.exists() ) {
+ logger.info("Schema existed");
+ return false;
+ }
+ schemaManager.create();
+ schemaManager.populateBaseData();
+
+ return true;
+ }
+
+
+
+ private static void maybeInit() {
+ if ( contextHolder != null ) {
+ return;
+ }
+ logger.info("Initing CassandraRunner...");
+
+ // TODO these should all be passed in as config options ... via spring?
+ // TODO make sure these match up with configs
+ // TODO one cassandra config in this project!
+ // TODO log4j.properties required to be present
+
+ System.setProperty("cassandra-foreground", "true");
+ System.setProperty("log4j.defaultInitOverride","true");
+ System.setProperty("log4j.configuration", "log4j.properties");
+ //System.setProperty("cassandra.load_ring_state", "false");so
+ //System.setProperty("cassandra.join_ring","false");
+ System.setProperty("cassandra.ring_delay_ms","100");
+
+ FileUtils.deleteQuietly(new File(TMP));
+
+ contextHolder = new ContextHolder();
+ try {
+ executor.schedule(contextHolder, 3, TimeUnit.SECONDS).get();
+ } catch (Exception ex) {
+ logger.error("Could not schedule cassandra runner",ex);
+ }
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+ try {
+ logger.error("In shutdownHook");
+ stopCassandra();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ });
+ }
+
+ private static void stopCassandra() throws Exception {
+ if (contextHolder != null && contextHolder.cassandraDaemon != null) {
+ contextHolder.cassandraDaemon.deactivate();
+ }
+ executor.shutdown();
+ executor.shutdownNow();
+ }
+
+ static class ContextHolder implements Runnable {
+ ConfigurableApplicationContext applicationContext;
+ CassandraDaemon cassandraDaemon;
+
+ @Override
+ public void run() {
+ cassandraDaemon = new CassandraDaemon();
+ cassandraDaemon.activate();
+ String[] locations = {"usergrid-test-context.xml"};
+ applicationContext = new ClassPathXmlApplicationContext(locations);
+
+
+
+ //acbf.autowire(getTestClass().getJavaClass(),AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidationTest.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidationTest.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidationTest.java
new file mode 100644
index 0000000..5054e45
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidationTest.java
@@ -0,0 +1,339 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.Assert;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+@RunWith(QueryValidatorRunner.class)
+public class QueryValidationTest {
+
+ private QueryValidator validator;
+
+ @Before
+ public void setup() {
+ validator = QueryValidatorRunner.getValidator();
+ }
+
+ @Test
+ public void sexEqualAndNameEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and name = 'judekim' LIMIT 10";
+ String api = "SELECT * WHERE sex = 'male' AND name = 'judekim'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameEqualAndSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 10";
+ String api = "select * where name = 'judekim' and sex = 'male'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameEqualAndSexEqual_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 20";
+ String api = "select * where name = 'judekim' and sex = 'male'";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndNameEqualExtra1() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'female' and name = 'curioe' LIMIT 10";
+ String api = "select * where sex = 'female' and name = 'curioe'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualOrNameEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'female' or name = 'curioe' LIMIT 10";
+ String api = "select * where sex = 'female' or name = 'curioe'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc_limitL4() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqual_sortAgeDescExtra1() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqual_sortAgeDescExtra2() {
+ String sqlite = " SELECT * FROM users WHERE sex = 'female' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'female' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal() {
+ String sqlite = " SELECT * FROM users WHERE sex = 'male' and age >= 35 LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAgeDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAgeDesc_limitL100() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 100";
+ String api = "select * where sex = 'male' and age >= 35 order by age desc";
+ int limit = 100;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlSexEqualAndAgeGreaterthanequal_sortNameDesc_limitL100() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 100";
+ String api = "select * where sex = 'male' and age >= 35 order by name desc";
+ int limit = 100;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortAgeDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void limitL12() {
+ String sqlite = "SELECT * FROM users LIMIT 12";
+ String api = null;
+ int limit = 12;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc_limitL100() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 100";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+ int limit = 100;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void limitL11() {
+ String sqlite = "SELECT * FROM users LIMIT 11";
+ String api = null;
+ int limit = 11;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 10";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 20";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAddressDesc_limitL100() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY address desc LIMIT 100";
+ String api = "select * where sex = 'male' and age >= 35 order by address desc";
+ int limit = 100;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+}
[07/50] [abbrv] git commit: Test cases for Ajax,
Usergrid.Request and Usergrid.Response
Posted by sn...@apache.org.
Test cases for Ajax, Usergrid.Request and Usergrid.Response
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/650cfd5c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/650cfd5c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/650cfd5c
Branch: refs/heads/optimistic-tx-semantics
Commit: 650cfd5c03033546a07e4935cedec499ef7bf886
Parents: 017cf30
Author: ryan bridges <rb...@apigee.com>
Authored: Mon Feb 10 16:34:19 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Mon Feb 10 16:34:19 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/lib/Usergrid.js | 7 +-
sdks/html5-javascript/lib/modules/Asset.js | 10 +-
sdks/html5-javascript/lib/modules/Client.js | 115 ++------------------
sdks/html5-javascript/lib/modules/Entity.js | 5 +-
sdks/html5-javascript/lib/modules/Folder.js | 6 +-
sdks/html5-javascript/lib/modules/Group.js | 2 +-
sdks/html5-javascript/lib/modules/util/Ajax.js | 114 ++++++++++---------
sdks/html5-javascript/tests/mocha/test.js | 70 ++++++++++++
sdks/html5-javascript/usergrid.js | 61 ++++++-----
sdks/html5-javascript/usergrid.min.js | 4 +-
10 files changed, 185 insertions(+), 209 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index f545964..e607075 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -133,19 +133,18 @@ function isFunction(f) {
* @return Returns whatever would be returned by the callback. or false.
*/
function doCallback(callback, params, context) {
- console.info("CALLED FROM", this.name||(context)?context.name:"UNKNOWN");
var returnValue;
if (isFunction(callback)) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- //try {
+ try {
returnValue = callback.apply(context, params);
- /*} catch (ex) {
+ } catch (ex) {
if (console && console.error) {
console.error("Callback error:", ex);
}
- }*/
+ }
}
return returnValue;
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/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
index 8af84e1..f40618e 100644
--- a/sdks/html5-javascript/lib/modules/Asset.js
+++ b/sdks/html5-javascript/lib/modules/Asset.js
@@ -79,7 +79,7 @@ Usergrid.Asset.prototype.addToFolder = function(options, callback) {
this._client.request(options, callback);
});
} else {
- doCallback(callback, [true, new Usergrid.Error('folder not specified')], self);
+ doCallback(callback, [true, new UsergridError('folder not specified')], self);
}
};
@@ -93,7 +93,7 @@ Usergrid.Asset.prototype.addToFolder = function(options, callback) {
*/
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);
+ return doCallback(callback, [true, new UsergridError('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"));
@@ -102,11 +102,11 @@ Usergrid.Asset.prototype.upload = function(data, callback) {
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)
+ doCallback(callback, [true, new UsergridError('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)
+ doCallback(callback, [true, new UsergridError(JSON.parse(xhr.responseText))], self)
} else {
doCallback(callback, [null, self], self)
}
@@ -142,7 +142,7 @@ Usergrid.Asset.prototype.download = function(callback) {
};
xhr.onerror = function(err) {
callback(true, err);
- doCallback(callback, [true, new Usergrid.Error(err)], self)
+ doCallback(callback, [true, new UsergridError(err)], self)
};
xhr.send();
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/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
index cf78df7..88ff623 100644
--- a/sdks/html5-javascript/lib/modules/Client.js
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -49,10 +49,13 @@
var orgName = this.get('orgName');
var appName = this.get('appName');
var uri;
+ var logoutCallback=function(){
+ if (typeof(this.logoutCallback) === 'function') {
+ return this.logoutCallback(true, 'no_org_or_app_name_specified');
+ }
+ }.bind(this);
if(!mQuery && !orgName && !appName){
- if (typeof(this.logoutCallback) === 'function') {
- return this.logoutCallback(true, 'no_org_or_app_name_specified');
- }
+ return logoutCallback();
}
if (mQuery) {
uri = this.URI + '/' + endpoint;
@@ -76,115 +79,11 @@
"unauthorized",
"auth_invalid"
].indexOf(response.error) !== -1) {
- //throw err;
+ return logoutCallback();
}
doCallback(callback, [err, response]);
//p.done(err, response);
});
- /*//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);*/
}
/*
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/lib/modules/Entity.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Entity.js b/sdks/html5-javascript/lib/modules/Entity.js
index 05ea970..b1225a3 100644
--- a/sdks/html5-javascript/lib/modules/Entity.js
+++ b/sdks/html5-javascript/lib/modules/Entity.js
@@ -1,3 +1,5 @@
+var ENTITY_SYSTEM_PROPERTIES=['metadata','created','modified','oldpassword','newpassword','type','activated','uuid'];
+
/*
* A class to Model a Usergrid Entity.
* Set the type and uuid of entity in the 'data' json object
@@ -140,7 +142,6 @@ Usergrid.Entity.prototype.save = function (callback) {
/*password = this.get('password'),
oldpassword = this.get('oldpassword'),
newpassword = this.get('newpassword'),*/
- SYSTEM_PROPERTIES=['metadata','created','modified','oldpassword','newpassword','type','activated','uuid'],
options={
method:method,
endpoint:type
@@ -155,7 +156,7 @@ Usergrid.Entity.prototype.save = function (callback) {
//remove system-specific properties
Object.keys(entityData)
- .filter(function(key){return (SYSTEM_PROPERTIES.indexOf(key)===-1)})
+ .filter(function(key){return (ENTITY_SYSTEM_PROPERTIES.indexOf(key)===-1)})
.forEach(function(key){
data[key]= entityData[key];
});
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/lib/modules/Folder.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Folder.js b/sdks/html5-javascript/lib/modules/Folder.js
index 7e2821f..d57d4b9 100644
--- a/sdks/html5-javascript/lib/modules/Folder.js
+++ b/sdks/html5-javascript/lib/modules/Folder.js
@@ -49,13 +49,13 @@ Usergrid.Folder.prototype.fetch = function(callback) {
if (!err) {
self.getAssets(function(err, data) {
if (err) {
- doCallback(callback, [true, new Usergrid.Error(data)], self);
+ doCallback(callback, [true, new UsergridError(data)], self);
} else {
doCallback(callback, [null, self], self);
}
});
} else {
- doCallback(callback, [true, new Usergrid.Error(data)], self)
+ doCallback(callback, [true, new UsergridError(data)], self)
}
})
};
@@ -93,7 +93,7 @@ Usergrid.Folder.prototype.addAsset = function(options, callback) {
if (asset && asset instanceof Usergrid.Entity) {
asset.fetch(function(err, data) {
if (err) {
- doCallback(callback, [err, new Usergrid.Error(data)], self)
+ doCallback(callback, [err, new UsergridError(data)], self)
} else {
var endpoint = ["folders", self.get("uuid"), "assets", asset.get("uuid")].join('/');
var options = {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/lib/modules/Group.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Group.js b/sdks/html5-javascript/lib/modules/Group.js
index 2a853be..7ae183c 100644
--- a/sdks/html5-javascript/lib/modules/Group.js
+++ b/sdks/html5-javascript/lib/modules/Group.js
@@ -52,7 +52,7 @@ Usergrid.Group.prototype.fetch = function(callback) {
callback(err, data);
}
} else {
- if(data.entities) {
+ if(data.entities && data.entities.length) {
var groupData = data.entities[0];
self._data = groupData || {};
self._client.request(memberOptions, function(err, data) {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/lib/modules/util/Ajax.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Ajax.js b/sdks/html5-javascript/lib/modules/util/Ajax.js
index 5b36ad5..a9cf16c 100644
--- a/sdks/html5-javascript/lib/modules/util/Ajax.js
+++ b/sdks/html5-javascript/lib/modules/util/Ajax.js
@@ -2,69 +2,67 @@
(function() {
var name = 'Ajax', global = this, overwrittenName = global[name], exports;
- /*Function.prototype.partial = function() {
- var fn = this,b = [].slice.call(arguments);
- return fn.bind(undefined, b);
- }*/
- function partial(fn){
- var args = Array.prototype.slice.call(arguments,1);
- return function(){
- return fn.apply(this, args.concat(Array.prototype.slice(arguments,0)))
- }
+ function partial(){
+ var args = Array.prototype.slice.call(arguments);
+ var fn=args.shift();
+ return fn.bind(this, args)
}
- 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]);
- }
+ 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;
}
- function request(m, u, d) {
- var p = new Promise(), timeout;
- self.logger.time(m + ' ' + u);
- self.logger.timeEnd(m + ' ' + u);
- (function(xhr) {
- xhr.onreadystatechange = function() {
- this.readyState ^ 4 || (self.logger.timeEnd(m + ' ' + u), clearTimeout(timeout), p.done(null, this));
- };
- xhr.onerror=function(response){
- clearTimeout(timeout);
- p.done(response, null);
- }
- xhr.oncomplete=function(response){
- clearTimeout(timeout);
- self.info("%s request to %s returned %s", m, u, this.status );
- }
- xhr.open(m, u);
- if (d) {
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.setRequestHeader("Accept", "application/json");
- }
- timeout = setTimeout(function() {
- xhr.abort();
- p.done("API Call timed out.", null)
- }, 30000);
- //TODO stick that timeout in a config variable
- xhr.send(encode(d));
- }(new XMLHttpRequest()));
- return p;
- };
- this.request=request;
- this.get = partial(request, 'GET');
- this.post = partial(request, 'POST');
- this.put = partial(request, 'PUT');
- this.delete = partial(request, 'DELETE');
+ return result;
}
+ function request(m, u, d) {
+ var p = new Promise(), timeout;
+ self.logger.time(m + ' ' + u);
+ (function(xhr) {
+ xhr.onreadystatechange = function() {
+ this.readyState ^ 4 || (self.logger.timeEnd(m + ' ' + u), clearTimeout(timeout), p.done(null, this));
+ };
+ xhr.onerror=function(response){
+ clearTimeout(timeout);
+ p.done(response, null);
+ }
+ xhr.oncomplete=function(response){
+ clearTimeout(timeout);
+ self.logger.timeEnd(m + ' ' + u);
+ self.info("%s request to %s returned %s", m, u, this.status );
+ }
+ xhr.open(m, u);
+ if (d) {
+ if("object"===typeof d){
+ d=JSON.stringify(d);
+ }
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.setRequestHeader("Accept", "application/json");
+ }
+ timeout = setTimeout(function() {
+ xhr.abort();
+ p.done("API Call timed out.", null)
+ }, 30000);
+ //TODO stick that timeout in a config variable
+ xhr.send(encode(d));
+ }(new XMLHttpRequest()));
+ return p;
+ };
+ this.request=request;
+ this.get = partial(request,'GET');
+ this.post = partial(request,'POST');
+ this.put = partial(request,'PUT');
+ this.delete = partial(request,'DELETE');
+ }
global[name] = new Ajax();
global[name].noConflict = function() {
if(overwrittenName){
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index 50229e1..f3cb9e4 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -29,6 +29,76 @@ function usergridTestHarness(err, data, done, tests, ignoreError) {
}
done();
}
+describe('Ajax', function() {
+ var dogName="dog"+Math.floor(Math.random()*10000);
+ var dogData=JSON.stringify({type:"dog",name:dogName});
+ var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs'
+ it('should POST to a URI',function(done){
+ Ajax.post(dogURI, dogData).then(function(err, data){
+ assert(!err, err);
+ done();
+ })
+ })
+ it('should GET a URI',function(done){
+ Ajax.get(dogURI+'/'+dogName).then(function(err, data){
+ assert(!err, err);
+ done();
+ })
+ })
+ it('should PUT to a URI',function(done){
+ Ajax.put(dogURI+'/'+dogName, {"favorite":true}).then(function(err, data){
+ assert(!err, err);
+ done();
+ })
+ })
+ it('should DELETE a URI',function(done){
+ Ajax.delete(dogURI+'/'+dogName, dogData).then(function(err, data){
+ assert(!err, err);
+ done();
+ })
+ })
+});
+describe('Usergrid Request/Response', function() {
+ var dogName="dog"+Math.floor(Math.random()*10000);
+ var dogData=JSON.stringify({type:"dog",name:dogName});
+ var dogURI='https://api.usergrid.com/yourorgname/sandbox/dogs'
+ it('should POST to a URI',function(done){
+ var req=new Usergrid.Request("POST", dogURI, {}, dogData, function(err, response){
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ done();
+ })
+ })
+ it('should GET a URI',function(done){
+ var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ done();
+ })
+ })
+ it('should PUT to a URI',function(done){
+ var req=new Usergrid.Request("PUT", dogURI+'/'+dogName, {}, {favorite:true}, function(err, response){
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ done();
+ })
+ })
+ it('should DELETE a URI',function(done){
+ var req=new Usergrid.Request("DELETE", dogURI+'/'+dogName, {}, null, function(err, response){
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ done();
+ })
+ })
+ it('should return a UsergridError object on an invalid URI',function(done){
+ var req=new Usergrid.Request("GET", dogURI+'/'+dogName+'zzzzz', {}, null, function(err, response){
+ assert(err, "Should have returned an error");
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ assert(err instanceof UsergridError, "Error is not and instance of UsergridError");
+ done();
+ })
+ })
+});
describe('Usergrid', function() {
var client = getClient();
describe('Usergrid CRUD', function() {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 542fb38..7d4bc06 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -181,15 +181,10 @@ UsergridEventable.mixin = function(destObject) {
//Ajax
(function() {
var name = "Ajax", global = this, overwrittenName = global[name], exports;
- /*Function.prototype.partial = function() {
- var fn = this,b = [].slice.call(arguments);
- return fn.bind(undefined, b);
- }*/
- function partial(fn) {
- var args = Array.prototype.slice.call(arguments, 1);
- return function() {
- return fn.apply(this, args.concat(Array.prototype.slice(arguments, 0)));
- };
+ function partial() {
+ var args = Array.prototype.slice.call(arguments);
+ var fn = args.shift();
+ return fn.bind(this, args);
}
function Ajax() {
this.logger = new global.Logger(name);
@@ -211,7 +206,6 @@ UsergridEventable.mixin = function(destObject) {
function request(m, u, d) {
var p = new Promise(), timeout;
self.logger.time(m + " " + u);
- self.logger.timeEnd(m + " " + u);
(function(xhr) {
xhr.onreadystatechange = function() {
this.readyState ^ 4 || (self.logger.timeEnd(m + " " + u), clearTimeout(timeout),
@@ -223,10 +217,14 @@ UsergridEventable.mixin = function(destObject) {
};
xhr.oncomplete = function(response) {
clearTimeout(timeout);
+ self.logger.timeEnd(m + " " + u);
self.info("%s request to %s returned %s", m, u, this.status);
};
xhr.open(m, u);
if (d) {
+ if ("object" === typeof d) {
+ d = JSON.stringify(d);
+ }
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
}
@@ -494,14 +492,18 @@ function isFunction(f) {
* @return Returns whatever would be returned by the callback. or false.
*/
function doCallback(callback, params, context) {
- console.info("CALLED FROM", this.name || context ? context.name : "UNKNOWN");
var returnValue;
if (isFunction(callback)) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- //try {
- returnValue = callback.apply(context, params);
+ try {
+ returnValue = callback.apply(context, params);
+ } catch (ex) {
+ if (console && console.error) {
+ console.error("Callback error:", ex);
+ }
+ }
}
return returnValue;
}
@@ -688,10 +690,13 @@ function doCallback(callback, params, context) {
var orgName = this.get("orgName");
var appName = this.get("appName");
var uri;
- if (!mQuery && !orgName && !appName) {
+ var logoutCallback = function() {
if (typeof this.logoutCallback === "function") {
return this.logoutCallback(true, "no_org_or_app_name_specified");
}
+ }.bind(this);
+ if (!mQuery && !orgName && !appName) {
+ return logoutCallback();
}
if (mQuery) {
uri = this.URI + "/" + endpoint;
@@ -702,7 +707,9 @@ function doCallback(callback, params, context) {
qs.access_token = self.getToken();
}
var req = new Usergrid.Request(method, uri, 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) {}
+ if ([ "auth_expired_session_token", "auth_missing_credentials", "auth_unverified_oath", "expired_token", "unauthorized", "auth_invalid" ].indexOf(response.error) !== -1) {
+ return logoutCallback();
+ }
doCallback(callback, [ err, response ]);
});
};
@@ -1329,6 +1336,8 @@ function doCallback(callback, params, context) {
return global[name];
})();
+var ENTITY_SYSTEM_PROPERTIES = [ "metadata", "created", "modified", "oldpassword", "newpassword", "type", "activated", "uuid" ];
+
/*
* A class to Model a Usergrid Entity.
* Set the type and uuid of entity in the 'data' json object
@@ -1470,7 +1479,7 @@ Usergrid.Entity.prototype.save = function(callback) {
var self = this, type = this.get("type"), method = "POST", entityId = this.get("uuid"), data = {}, entityData = this.get(), /*password = this.get('password'),
oldpassword = this.get('oldpassword'),
newpassword = this.get('newpassword'),*/
- SYSTEM_PROPERTIES = [ "metadata", "created", "modified", "oldpassword", "newpassword", "type", "activated", "uuid" ], options = {
+ options = {
method: method,
endpoint: type
};
@@ -1482,7 +1491,7 @@ Usergrid.Entity.prototype.save = function(callback) {
}
//remove system-specific properties
Object.keys(entityData).filter(function(key) {
- return SYSTEM_PROPERTIES.indexOf(key) === -1;
+ return ENTITY_SYSTEM_PROPERTIES.indexOf(key) === -1;
}).forEach(function(key) {
data[key] = entityData[key];
});
@@ -2394,7 +2403,7 @@ Usergrid.Group.prototype.fetch = function(callback) {
callback(err, data);
}
} else {
- if (data.entities) {
+ if (data.entities && data.entities.length) {
var groupData = data.entities[0];
self._data = groupData || {};
self._client.request(memberOptions, function(err, data) {
@@ -2806,13 +2815,13 @@ Usergrid.Folder.prototype.fetch = function(callback) {
if (!err) {
self.getAssets(function(err, data) {
if (err) {
- doCallback(callback, [ true, new Usergrid.Error(data) ], self);
+ doCallback(callback, [ true, new UsergridError(data) ], self);
} else {
doCallback(callback, [ null, self ], self);
}
});
} else {
- doCallback(callback, [ true, new Usergrid.Error(data) ], self);
+ doCallback(callback, [ true, new UsergridError(data) ], self);
}
});
};
@@ -2852,7 +2861,7 @@ Usergrid.Folder.prototype.addAsset = function(options, callback) {
if (asset && asset instanceof Usergrid.Entity) {
asset.fetch(function(err, data) {
if (err) {
- doCallback(callback, [ err, new Usergrid.Error(data) ], self);
+ doCallback(callback, [ err, new UsergridError(data) ], self);
} else {
var endpoint = [ "folders", self.get("uuid"), "assets", asset.get("uuid") ].join("/");
var options = {
@@ -3004,7 +3013,7 @@ Usergrid.Asset.prototype.addToFolder = function(options, callback) {
this._client.request(options, callback);
});
} else {
- doCallback(callback, [ true, new Usergrid.Error("folder not specified") ], self);
+ doCallback(callback, [ true, new UsergridError("folder not specified") ], self);
}
};
@@ -3018,7 +3027,7 @@ Usergrid.Asset.prototype.addToFolder = function(options, callback) {
*/
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);
+ return doCallback(callback, [ true, new UsergridError("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("/");
@@ -3027,11 +3036,11 @@ Usergrid.Asset.prototype.upload = function(data, callback) {
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);
+ doCallback(callback, [ true, new UsergridError("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);
+ doCallback(callback, [ true, new UsergridError(JSON.parse(xhr.responseText)) ], self);
} else {
doCallback(callback, [ null, self ], self);
}
@@ -3067,7 +3076,7 @@ Usergrid.Asset.prototype.download = function(callback) {
};
xhr.onerror = function(err) {
callback(true, err);
- doCallback(callback, [ true, new Usergrid.Error(err) ], self);
+ doCallback(callback, [ true, new UsergridError(err) ], self);
};
xhr.send();
};
[35/50] [abbrv] Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/.gitignore
----------------------------------------------------------------------
diff --cc .gitignore
index 5427973,3684d76..b14275b
--- a/.gitignore
+++ b/.gitignore
@@@ -18,5 -18,4 +18,3 @@@ Ico
/portal/dist
/portal/bower_components
/portal/.idea
- .Trashes
--/stack/corepersistence/priamcluster/aws.properties
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
----------------------------------------------------------------------
diff --cc stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
index bc456dc,0000000..2586285
mode 100644,000000..100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
@@@ -1,254 -1,0 +1,253 @@@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.usergrid.persistence.collection.impl;
+
+
+import java.util.UUID;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.usergrid.persistence.collection.CollectionScope;
+import org.apache.usergrid.persistence.collection.EntityCollectionManager;
+import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
+import org.apache.usergrid.persistence.collection.mvcc.entity.ValidationUtils;
+import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
+import org.apache.usergrid.persistence.collection.mvcc.stage.delete.DeleteCommit;
+import org.apache.usergrid.persistence.collection.mvcc.stage.delete.DeleteStart;
+import org.apache.usergrid.persistence.collection.mvcc.stage.load.Load;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteCommit;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteOptimisticVerify;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteStart;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteUniqueVerify;
- import org.apache.usergrid.persistence.collection.rx.Concurrent;
+import org.apache.usergrid.persistence.collection.service.UUIDService;
+import org.apache.usergrid.persistence.collection.util.EntityUtils;
+import org.apache.usergrid.persistence.model.entity.Entity;
+import org.apache.usergrid.persistence.model.entity.Id;
+
+import com.google.common.base.Preconditions;
+import com.google.inject.Inject;
+import com.google.inject.assistedinject.Assisted;
+
+import rx.Observable;
+import rx.Scheduler;
+import rx.util.functions.Func1;
+import rx.util.functions.Func2;
+import rx.util.functions.FuncN;
+
+
+/**
+ * Simple implementation. Should perform writes, delete and load.
+ *
+ * TODO T.N. maybe refactor the stage operations into their own classes for clarity and organization?
+ *
+ * @author tnine
+ */
+public class EntityCollectionManagerImpl implements EntityCollectionManager {
+
+ private static final Logger logger = LoggerFactory.getLogger( EntityCollectionManagerImpl.class );
+
+ private final CollectionScope collectionScope;
+ private final UUIDService uuidService;
+ private final Scheduler scheduler;
+
+
+ //start stages
+ private final WriteStart writeStart;
+ private final WriteUniqueVerify writeVerifyUnique;
+ private final WriteOptimisticVerify writeOptimisticVerify;
+ private final WriteCommit writeCommit;
+
+ //load stages
+ private final Load load;
+
+
+ //delete stages
+ private final DeleteStart deleteStart;
+ private final DeleteCommit deleteCommit;
+
+
+ @Inject
+ public EntityCollectionManagerImpl( final UUIDService uuidService, final WriteStart writeStart,
+ final Scheduler scheduler, final WriteUniqueVerify writeVerifyUnique,
+ final WriteOptimisticVerify writeOptimisticVerify,
+ final WriteCommit writeCommit, final Load load, final DeleteStart deleteStart,
+ final DeleteCommit deleteCommit,
+ @Assisted final CollectionScope collectionScope ) {
+
+
+ Preconditions.checkNotNull( uuidService, "uuidService must be defined" );
+ ValidationUtils.validateCollectionScope( collectionScope );
+
+
+ this.writeStart = writeStart;
+ this.writeVerifyUnique = writeVerifyUnique;
+ this.writeOptimisticVerify = writeOptimisticVerify;
+ this.writeCommit = writeCommit;
+ this.load = load;
+ this.deleteStart = deleteStart;
+ this.deleteCommit = deleteCommit;
+
+
+ this.uuidService = uuidService;
+ this.scheduler = scheduler;
+ this.collectionScope = collectionScope;
+ }
+
+
+ @Override
+ public Observable<Entity> write( final Entity entity ) {
+ //do our input validation
+
+ Preconditions.checkNotNull( entity, "Entity is required in the new stage of the mvcc write" );
+
+ final Id entityId = entity.getId();
+
+ Preconditions.checkNotNull( entityId, "The entity id is required to be set for an update operation" );
+
+ Preconditions
+ .checkNotNull( entityId.getUuid(), "The entity id uuid is required to be set for an update operation" );
+
+ Preconditions
+ .checkNotNull( entityId.getType(), "The entity id type required to be set for an update operation" );
+
+
+ final UUID version = uuidService.newTimeUUID();
+
+ EntityUtils.setVersion( entity, version );
+
+
+ /**
+ *fire the stages
+ * TODO use our own scheduler to help with multitenancy here.
+ * TODO writeOptimisticVerify and writeVerifyUnique should happen concurrently to reduce user wait time
+ */
+
+ //these 3 lines could be done in a single line, but they are on multiple lines for clarity
+
+ //create our observable and start the write
+ CollectionIoEvent<Entity> writeData = new CollectionIoEvent<Entity>( collectionScope, entity );
+
+ Observable<CollectionIoEvent<MvccEntity>> observable =
+ Observable.from( writeData ).subscribeOn( scheduler ).map( writeStart ).flatMap(
+ new Func1<CollectionIoEvent<MvccEntity>, Observable<CollectionIoEvent<MvccEntity>>>() {
+
+
+ @Override
+ public Observable<CollectionIoEvent<MvccEntity>> call(
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent ) {
+
+ //do the unique and optimistic steps in parallel
+
+ /**
+ *unique function. Since there can be more than 1 unique value in this entity
+ * the unique verification step itself is multiple parallel executions.
+ * This is why we use "flatMap" instead of "map", which allows the
+ * WriteVerifyUnique stage to execute multiple verification steps in parallel and
+ * zip the results
+ */
+
+
+ Observable<CollectionIoEvent<MvccEntity>> unique =
+ Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
+ .flatMap( writeVerifyUnique);
+
+
+ //optimistic verification
+ Observable<CollectionIoEvent<MvccEntity>> optimistic =
+ Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
+ .map( writeOptimisticVerify );
+
+
+ //zip the results
+ /**
+ * TODO: Should the zip only return errors here, and if errors are present, we throw during the zip phase? I couldn't find "
+ */
+
+ return Observable.zip( unique, optimistic, new Func2<CollectionIoEvent<MvccEntity>,
+ CollectionIoEvent<MvccEntity>, CollectionIoEvent<MvccEntity>>() {
+ @Override
+ public CollectionIoEvent<MvccEntity> call(
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent,
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent2 ) {
+
+ return mvccEntityCollectionIoEvent;
+ }
+ } );
+ }
+ } );
+
+
+// //execute all validation stages concurrently. Needs refactored when this is done. https://github
+// // .com/Netflix/RxJava/issues/627
+// observable =
+// Concurrent.concurrent( observable, scheduler, new WaitZip(), writeVerifyUnique, writeOptimisticVerify );
+
+ //return the commit result.
+ return observable.map( writeCommit );
+ }
+
+
+ @Override
+ public Observable<Void> delete( final Id entityId ) {
+
+
+ Preconditions.checkNotNull( entityId, "Entity id is required in this stage" );
+ Preconditions.checkNotNull( entityId.getUuid(), "Entity id is required in this stage" );
+ Preconditions.checkNotNull( entityId.getType(), "Entity type is required in this stage" );
+
+
+ return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
+ .map( deleteStart ).map( deleteCommit );
+ }
+
+
+ @Override
+ public Observable<Entity> load( final Id entityId ) {
+
+ Preconditions.checkNotNull( entityId, "Entity id required in the load stage" );
+ Preconditions.checkNotNull( entityId.getUuid(), "Entity id uuid required in the load stage" );
+ Preconditions.checkNotNull( entityId.getType(), "Entity id type required in the load stage" );
+
+ return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
+ .map( load );
+ }
+
+
+ /**
+ * Class that validates all results are equal then proceeds
+ */
+ private static class WaitZip<R> implements FuncN<R> {
+
+
+ private WaitZip() {
+ }
+
+
+ @Override
+ public R call( final Object... args ) {
+
+ for ( int i = 0; i < args.length - 1; i++ ) {
+ assert args[i] == args[i + 1];
+ }
+
+ return ( R ) args[0];
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/pom.xml
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/pom.xml
index 30bb3dd,4f523a6..22158b5
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@@ -3,9 -3,9 +3,9 @@@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
- <groupId>org.usergrid</groupId>
+ <groupId>org.apache.usergrid</groupId>
<artifactId>usergrid</artifactId>
- <version>0.0.16-SNAPSHOT</version>
+ <version>0.0.28-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@@ -81,8 -77,9 +81,8 @@@
<goal>test-jar</goal>
</goals>
<configuration>
- <classifier>tests</classifier>
<includes>
- <include>**/org/usergrid/**</include>
+ <include>**/org/apache/usergrid/**</include>
</includes>
</configuration>
</execution>
@@@ -92,94 -89,47 +92,94 @@@
</build>
<dependencies>
<dependency>
- <groupId>org.usergrid</groupId>
+ <groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-config</artifactId>
<version>${project.version}</version>
- <scope>test</scope>
- <classifier>tests</classifier>
</dependency>
+
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-core</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-count-batcher</artifactId>
<version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <artifactId>commons-logging</artifactId>
+ <groupId>commons-logging</groupId>
+ </exclusion>
+ </exclusions>
</dependency>
+
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-rest</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-count-common</artifactId>
<version>${project.version}</version>
+ <classifier>classes</classifier>
+ <exclusions>
+ <exclusion>
+ <artifactId>servlet-api</artifactId>
+ <groupId>javax.servlet</groupId>
+ </exclusion>
+ </exclusions>
</dependency>
+
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-rest</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-test-utils</artifactId>
<version>${project.version}</version>
- <scope>test</scope>
+ <classifier>compiled-jsp</classifier>
</dependency>
+
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-rest</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
+ <classifier>tests</classifier>
+ <scope>test</scope>
</dependency>
+
+ <!-- Apache Dependencies -->
+
<dependency>
- <groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-scheduler</artifactId>
- <version>${project.version}</version>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ </dependency>
+
+ <!-- SUN, Javax Package, and Other Com Dependencies -->
+
+
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>jstl</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-webmvc</artifactId>
+ </dependency>
+
+ <!--<dependency>-->
+ <!--<!– TODO - should not scope be 'test' ? –>-->
+ <!--<groupId>org.slf4j</groupId>-->
+ <!--<artifactId>jcl-over-slf4j</artifactId>-->
+ <!--</dependency>-->
+
+ <!--<dependency>-->
+ <!--<!– TODO - should not scope be 'test' ? –>-->
+ <!--<groupId>org.slf4j</groupId>-->
+ <!--<artifactId>jul-to-slf4j</artifactId>-->
+ <!--</dependency>-->
+
+ <!-- Testing and Logging Dependencies -->
+
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-config</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<classifier>tests</classifier>
@@@ -285,12 -212,22 +285,29 @@@
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
- <dependency>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-jdbc</artifactId>
+ <version>${org.springframework.version}</version>
+ </dependency>
++ <dependency>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-java-client</artifactId>
+ <version>0.0.3</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-standalone</artifactId>
+ <version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <artifactId>commons-logging</artifactId>
+ <groupId>commons-logging</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
</dependencies>
- </project>
+ </project>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
index 7a7015e,c53d08b..796b1bf
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
@@@ -14,29 -12,30 +14,29 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
-
- import org.apache.commons.lang.StringUtils;
- import org.codehaus.jackson.JsonNode;
- import org.springframework.http.HttpMethod;
- import org.springframework.stereotype.Component;
- import org.usergrid.java.client.Client;
- import org.usergrid.java.client.response.ApiResponse;
- import org.usergrid.persistence.Entity;
- import org.usergrid.persistence.Schema;
+ package org.apache.usergrid.query.validator;
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.jackson.JsonNode;
-import org.springframework.http.HttpMethod;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.java.client.response.ApiResponse;
-import org.apache.usergrid.persistence.Entity;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
--
- import static org.usergrid.java.client.utils.ObjectUtils.isEmpty;
-import static org.apache.usergrid.java.client.utils.ObjectUtils.isEmpty;
++import org.apache.commons.lang.StringUtils;
++import static org.apache.commons.lang.StringUtils.isEmpty;
++import org.apache.usergrid.persistence.Entity;
++import org.apache.usergrid.persistence.Schema;
++import org.codehaus.jackson.JsonNode;
++import org.springframework.http.HttpMethod;
++import org.springframework.stereotype.Component;
++import org.usergrid.java.client.Client;
++import org.usergrid.java.client.response.ApiResponse;
++import org.usergrid.query.validator.QueryEntity;
++import org.usergrid.query.validator.QueryRunner;
/**
- * @author Sung-ju Jin(realbeast)
+ * @author Sungju Jin
*/
@Component
public class ApiServerRunner implements QueryRunner {
@@@ -79,23 -78,23 +79,24 @@@
}
public boolean insertDatas() {
- List<org.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
- for(org.usergrid.java.client.entities.Entity entity : clientEntities) {
- ApiResponse response = client.createEntity(entity);
- if( response == null || !StringUtils.isEmpty(response.getError()) ) {
- logger.log(Level.SEVERE, response.getErrorDescription());
- //throw new RuntimeException(response.getErrorDescription());
- } else {
- logger.log(Level.INFO, response.toString());
- }
- }
- return true;
- }
+
- private List<org.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
- List<org.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.usergrid.java.client.entities.Entity>();
+ List<org.apache.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
+ for(org.apache.usergrid.java.client.entities.Entity entity : clientEntities) {
+ ApiResponse response = client.createEntity(entity);
+ if( response == null || !StringUtils.isEmpty(response.getError()) ) {
+ logger.log(Level.SEVERE, response.getErrorDescription());
+ //throw new RuntimeException(response.getErrorDescription());
+ } else {
+ logger.log(Level.INFO, response.toString());
+ }
+ }
+ return true;
+ }
+
+ private List<org.apache.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
+ List<org.apache.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.apache.usergrid.java.client.entities.Entity>();
for(Entity entity : entities) {
- org.usergrid.java.client.entities.Entity clientEntity = new org.usergrid.java.client.entities.Entity();
+ org.apache.usergrid.java.client.entities.Entity clientEntity = new org.apache.usergrid.java.client.entities.Entity();
clientEntity.setType(entity.getType());
Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
for(String key : properties.keySet()) {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
index c43afe7,77893bd..5790204
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
@@@ -1,23 -1,6 +1,23 @@@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
- import org.usergrid.persistence.DynamicEntity;
+ import org.apache.usergrid.persistence.DynamicEntity;
import java.util.Map;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
index 59032ba,d2989c7..eecc0d2
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
@@@ -14,11 -12,11 +14,11 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
/**
- * @author Sung-ju Jin(realbeast)
+ * @author Sungju Jin
*/
public class QueryRequest {
private String dbQuery;
@@@ -64,4 -63,12 +64,4 @@@
this.limit = limit;
}
}
- }
-
- public boolean isIgnoreOrdering() {
- return ignoreOrdering;
- }
-
- public void setIgnoreOrdering(boolean ignoreOrdering) {
- this.ignoreOrdering = ignoreOrdering;
- }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
index 6a05c13,aa152d5..b3669ff
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
@@@ -14,11 -12,11 +14,11 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
import org.apache.commons.lang.StringUtils;
- import org.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.Entity;
import java.util.List;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
index fbc6220,06341d6..b99038d
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
@@@ -14,15 -12,14 +14,15 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
- import org.usergrid.persistence.Entity;
-import java.util.List;
+ import org.apache.usergrid.persistence.Entity;
+import java.util.List;
+
/**
- * @author Sung-ju Jin(realbeast)
+ * @author Sungju Jin
*/
public interface QueryRunner {
public boolean setup();
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
index 35f3994,8b14737..6f7b9e6
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
@@@ -1,24 -1,7 +1,24 @@@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
- import org.usergrid.persistence.Entity;
- import org.usergrid.utils.InflectionUtils;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.utils.InflectionUtils;
import java.util.List;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
index 0e7f89a,180a8e5..4d46950
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
@@@ -14,8 -12,8 +14,8 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
index dd728c8,a1932a0..7c7aa55
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
@@@ -14,16 -12,16 +14,14 @@@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- ******************************************************************************/
+ */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
--import org.springframework.jdbc.core.JdbcTemplate;
--import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
- import org.usergrid.persistence.Entity;
- import org.usergrid.persistence.Schema;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.Schema;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@@ -31,9 -29,9 +29,12 @@@ import java.sql.SQLException
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
++import javax.swing.tree.RowMapper;
++import org.usergrid.query.validator.QueryEntity;
++import org.usergrid.query.validator.QueryRunner;
/**
- * @author Sung-ju Jin(realbeast)
+ * @author Sungju Jin
*/
@Component
public class SqliteRunner implements QueryRunner {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
index 89679d7,36355a8..3a8c577
--- a/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
+++ b/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
@@@ -1,14 -1,16 +1,14 @@@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
- <context:annotation-config />
- <context:component-scan base-package="org.usergrid.query.validator" />
+ <context:annotation-config />
+ <context:component-scan base-package="org.apache.usergrid.query.validator" />
- <import resource="classpath:/usergrid-core-context.xml" />
-
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.sqlite.JDBC" />
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/test/resources/usergrid-test-context.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/src/test/resources/usergrid-test-context.xml
index bec5638,5df1815..b07cc2d
--- a/stack/query-validator/src/test/resources/usergrid-test-context.xml
+++ b/stack/query-validator/src/test/resources/usergrid-test-context.xml
@@@ -20,17 -17,9 +20,17 @@@
</property>
</bean>
- <import resource="classpath:/usergrid-query-validator-context.xml" />
+ <import resource="usergrid-rest-context.xml"/>
+
+ <bean id="traceTagManager" class="org.usergrid.persistence.cassandra.util.TraceTagManager">
+ <property name="reportUnattached" value="false"/>
+ <property name="traceEnabled" value="false"/>
+ </bean>
+
+
+ <bean id="binaryStore" class="org.usergrid.services.assets.data.LocalFileBinaryStore"/>
- <bean id="setup" class="org.usergrid.persistence.cassandra.Setup">
+ <bean id="setup" class="org.apache.usergrid.persistence.cassandra.Setup">
<constructor-arg ref="entityManagerFactory"/>
<constructor-arg ref="cassandraService"/>
</bean>
@@@ -41,6 -30,5 +41,6 @@@
<constructor-arg ref="cassandraCluster"/>
</bean>
+ <import resource="usergrid-query-validator-context.xml"/>
- </beans>
+ </beans>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/pom.xml
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
----------------------------------------------------------------------
diff --cc stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
index 0000000,552d501..3583b88
mode 000000,100644..100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
@@@ -1,0 -1,610 +1,610 @@@
+ /*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+ package org.apache.usergrid.rest.applications;
+
+
+ import java.io.UnsupportedEncodingException;
+ import java.net.URLEncoder;
+ import java.util.Map;
+ import java.util.UUID;
+
+ import javax.ws.rs.Consumes;
+ import javax.ws.rs.DELETE;
+ import javax.ws.rs.DefaultValue;
+ import javax.ws.rs.FormParam;
+ import javax.ws.rs.GET;
+ import javax.ws.rs.HeaderParam;
+ import javax.ws.rs.POST;
+ import javax.ws.rs.Path;
+ import javax.ws.rs.Produces;
+ import javax.ws.rs.QueryParam;
+ import javax.ws.rs.core.Context;
+ import javax.ws.rs.core.MediaType;
+ import javax.ws.rs.core.PathSegment;
+ import javax.ws.rs.core.Response;
+ import javax.ws.rs.core.UriInfo;
+
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+ import org.springframework.context.annotation.Scope;
+ import org.springframework.stereotype.Component;
+ import org.apache.usergrid.exception.NotImplementedException;
+ import org.apache.usergrid.management.ApplicationInfo;
+ import org.apache.usergrid.management.exceptions.DisabledAdminUserException;
+ import org.apache.usergrid.management.exceptions.DisabledAppUserException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAdminUserException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAppUserException;
+ import org.apache.usergrid.mq.QueueManager;
+ import org.apache.usergrid.persistence.EntityManager;
+ import org.apache.usergrid.persistence.Identifier;
+ import org.apache.usergrid.persistence.SimpleEntityRef;
+ import org.apache.usergrid.persistence.entities.Application;
+ import org.apache.usergrid.persistence.entities.User;
+ import org.apache.usergrid.rest.AbstractContextResource;
+ import org.apache.usergrid.rest.applications.assets.AssetsResource;
+ import org.apache.usergrid.rest.applications.events.EventsResource;
+ import org.apache.usergrid.rest.applications.queues.QueueResource;
+ import org.apache.usergrid.rest.applications.users.UsersResource;
+ import org.apache.usergrid.rest.exceptions.AuthErrorInfo;
+ import org.apache.usergrid.rest.exceptions.RedirectionException;
+ import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
+ import org.apache.usergrid.security.oauth.AccessInfo;
+ import org.apache.usergrid.security.oauth.ClientCredentialsInfo;
+
+ import org.apache.amber.oauth2.common.error.OAuthError;
+ import org.apache.amber.oauth2.common.exception.OAuthProblemException;
+ import org.apache.amber.oauth2.common.message.OAuthResponse;
+ import org.apache.amber.oauth2.common.message.types.GrantType;
+ import org.apache.shiro.authz.UnauthorizedException;
+ import org.apache.shiro.codec.Base64;
+
+ import com.sun.jersey.api.json.JSONWithPadding;
+ import com.sun.jersey.api.view.Viewable;
+
+ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
+ import static javax.servlet.http.HttpServletResponse.SC_OK;
+ import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
+ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+ import static org.apache.commons.lang.StringUtils.isNotBlank;
+ import static org.apache.usergrid.rest.exceptions.SecurityException.mappableSecurityException;
+ import static org.apache.usergrid.security.oauth.ClientCredentialsInfo.getUUIDFromClientId;
+ import static org.apache.usergrid.security.shiro.utils.SubjectUtils.isApplicationAdmin;
+ import static org.apache.usergrid.services.ServiceParameter.addParameter;
+ import static org.apache.usergrid.utils.StringUtils.stringOrSubstringAfterFirst;
+ import static org.apache.usergrid.utils.StringUtils.stringOrSubstringBeforeFirst;
+
+
+ @Component("org.apache.usergrid.rest.applications.ApplicationResource")
+ @Scope("prototype")
+ @Produces({
+ MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript",
+ "application/ecmascript", "text/jscript"
+ })
+ public class ApplicationResource extends ServiceResource {
+
+ public static final Logger logger = LoggerFactory.getLogger( ApplicationResource.class );
+
+ UUID applicationId;
+ QueueManager queues;
+
+
+ public ApplicationResource() {
+ }
+
+
+ public ApplicationResource init( UUID applicationId ) throws Exception {
+ this.applicationId = applicationId;
+ services = smf.getServiceManager( applicationId );
+ queues = qmf.getQueueManager( applicationId );
+ return this;
+ }
+
+
+ public QueueManager getQueues() {
+ return queues;
+ }
+
+
+ @Override
+ public UUID getApplicationId() {
+ return applicationId;
+ }
+
+
+ @Path("auth")
+ public AuthResource getAuthResource() throws Exception {
+ return getSubResource( AuthResource.class );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("queues")
+ public QueueResource getQueueResource() throws Exception {
+ return getSubResource( QueueResource.class ).init( queues, "" );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("events")
+ public EventsResource getEventsResource( @Context UriInfo ui ) throws Exception {
+ addParameter( getServiceParameters(), "events" );
+
+ PathSegment ps = getFirstPathSegment( "events" );
+ if ( ps != null ) {
+ addMatrixParams( getServiceParameters(), ui, ps );
+ }
+
+ return getSubResource( EventsResource.class );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("event")
+ public EventsResource getEventResource( @Context UriInfo ui ) throws Exception {
+ return getEventsResource( ui );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("assets")
+ public AssetsResource getAssetsResource( @Context UriInfo ui ) throws Exception {
+ logger.debug( "in assets n applicationResource" );
+ addParameter( getServiceParameters(), "assets" );
+
+ PathSegment ps = getFirstPathSegment( "assets" );
+ if ( ps != null ) {
+ addMatrixParams( getServiceParameters(), ui, ps );
+ }
+
+ return getSubResource( AssetsResource.class );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("asset")
+ public AssetsResource getAssetResource( @Context UriInfo ui ) throws Exception {
+ // TODO change to singular
+ logger.debug( "in asset in applicationResource" );
+ return getAssetsResource( ui );
+ }
+
+
+ @Path("users")
+ public UsersResource getUsers( @Context UriInfo ui ) throws Exception {
+ logger.debug( "ApplicationResource.getUsers" );
+ addParameter( getServiceParameters(), "users" );
+
+ PathSegment ps = getFirstPathSegment( "users" );
+ if ( ps != null ) {
+ addMatrixParams( getServiceParameters(), ui, ps );
+ }
+
+ return getSubResource( UsersResource.class );
+ }
+
+
+ @Path("user")
+ public UsersResource getUsers2( @Context UriInfo ui ) throws Exception {
+ return getUsers( ui );
+ }
+
+
+ @GET
+ @Path("token")
+ public Response getAccessToken( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+ @QueryParam("grant_type") String grant_type,
+ @QueryParam("username") String username, @QueryParam("password") String password,
+ @QueryParam("pin") String pin, @QueryParam("client_id") String client_id,
+ @QueryParam("client_secret") String client_secret, @QueryParam("code") String code,
+ @QueryParam("ttl") long ttl, @QueryParam("redirect_uri") String redirect_uri,
+ @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {
+
+ logger.debug( "ApplicationResource.getAccessToken" );
+
+ User user = null;
+
+ try {
+
+ if ( authorization != null ) {
+ String type = stringOrSubstringBeforeFirst( authorization, ' ' ).toUpperCase();
+ if ( "BASIC".equals( type ) ) {
+ String token = stringOrSubstringAfterFirst( authorization, ' ' );
+ String[] values = Base64.decodeToString( token ).split( ":" );
+ if ( values.length >= 2 ) {
+ client_id = values[0];
+ client_secret = values[1];
+ }
+ }
+ }
+
+ // do checking for different grant types
+ String errorDescription = "invalid username or password";
+ if ( GrantType.PASSWORD.toString().equals( grant_type ) ) {
+ try {
+ user = management
+ .verifyAppUserPasswordCredentials( services.getApplicationId(), username, password );
+ }
+ catch ( UnactivatedAppUserException uaue ) {
+ errorDescription = "user not activated";
+ }
+ catch ( DisabledAppUserException daue ) {
+ errorDescription = "user disabled";
+ }
+ catch ( Exception e1 ) {
++ logger.warn( "Unexpected exception during token username/password verification", e1 );
++
+ }
+ }
+ else if ( "pin".equals( grant_type ) ) {
+ try {
+ user = management.verifyAppUserPinCredentials( services.getApplicationId(), username, pin );
+ }
+ catch ( Exception e1 ) {
++ logger.warn( "Unexpected exception during token pin verification", e1 );
++
+ }
+ }
+ else if ( "client_credentials".equals( grant_type ) ) {
+ try {
+ AccessInfo access_info = management.authorizeClient( client_id, client_secret, ttl );
+ if ( access_info != null ) {
+ return Response.status( SC_OK ).type( jsonMediaType( callback ) )
+ .entity( wrapWithCallback( access_info, callback ) ).build();
+ }
+ }
+ catch ( Exception e1 ) {
++ logger.warn( "Unexpected exception during token client authentication", e1 );
+ }
+ }
- else if ( "authorization_code".equals( grant_type ) ) {
- AccessInfo access_info = new AccessInfo();
- access_info.setAccessToken( code );
- return Response.status( SC_OK ).type( jsonMediaType( callback ) )
- .entity( wrapWithCallback( access_info, callback ) ).build();
- }
+
+ if ( user == null ) {
+ OAuthResponse response =
+ OAuthResponse.errorResponse( SC_BAD_REQUEST ).setError( OAuthError.TokenResponse.INVALID_GRANT )
+ .setErrorDescription( errorDescription ).buildJSONMessage();
+ return Response.status( response.getResponseStatus() ).type( jsonMediaType( callback ) )
+ .entity( wrapWithCallback( response.getBody(), callback ) ).build();
+ }
+
+ String token = management.getAccessTokenForAppUser( services.getApplicationId(), user.getUuid(), ttl );
+
+ AccessInfo access_info =
+ new AccessInfo().withExpiresIn( tokens.getMaxTokenAgeInSeconds( token ) ).withAccessToken( token )
+ .withProperty( "user", user );
+
+ return Response.status( SC_OK ).type( jsonMediaType( callback ) )
+ .entity( wrapWithCallback( access_info, callback ) ).build();
+ }
+ catch ( OAuthProblemException e ) {
+ logger.error( "OAuth Error", e );
+ OAuthResponse res = OAuthResponse.errorResponse( SC_BAD_REQUEST ).error( e ).buildJSONMessage();
+ return Response.status( res.getResponseStatus() ).type( jsonMediaType( callback ) )
+ .entity( wrapWithCallback( res.getBody(), callback ) ).build();
+ }
+ }
+
+
+ @POST
+ @Path("token")
+ @Consumes(APPLICATION_FORM_URLENCODED)
+ public Response getAccessTokenPost( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+ @FormParam("grant_type") String grant_type,
+ @FormParam("username") String username, @FormParam("password") String password,
+ @FormParam("pin") String pin, @FormParam("client_id") String client_id,
+ @FormParam("client_secret") String client_secret,
+ @FormParam("code") String code, @FormParam("ttl") long ttl,
+ @FormParam("redirect_uri") String redirect_uri,
+ @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {
+
+ logger.debug( "ApplicationResource.getAccessTokenPost" );
+
+ return getAccessToken( ui, authorization, grant_type, username, password, pin, client_id, client_secret, code,
+ ttl, redirect_uri, callback );
+ }
+
+
+ @POST
+ @Path("token")
+ @Consumes(APPLICATION_JSON)
+ public Response getAccessTokenPostJson( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+ Map<String, Object> json,
+ @QueryParam("callback") @DefaultValue("") String callback )
+ throws Exception {
+
+ String grant_type = ( String ) json.get( "grant_type" );
+ String username = ( String ) json.get( "username" );
+ String password = ( String ) json.get( "password" );
+ String client_id = ( String ) json.get( "client_id" );
+ String client_secret = ( String ) json.get( "client_secret" );
+ String pin = ( String ) json.get( "pin" );
+ String code = ( String ) json.get( "code" );
+ String redirect_uri = ( String ) json.get( "redirect_uri" );
+ long ttl = 0;
+
+ if ( json.get( "ttl" ) != null ) {
+ try {
+ ttl = Long.parseLong( json.get( "ttl" ).toString() );
+ }
+ catch ( NumberFormatException nfe ) {
+ throw new IllegalArgumentException( "ttl must be a number >= 0" );
+ }
+ }
+
+ return getAccessToken( ui, authorization, grant_type, username, password, pin, client_id, client_secret, code,
+ ttl, redirect_uri, callback );
+ }
+
+
+ @GET
+ @Path("credentials")
+ @RequireApplicationAccess
+ public JSONWithPadding getKeys( @Context UriInfo ui,
+ @QueryParam("callback") @DefaultValue("callback") String callback )
+ throws Exception {
+
+ logger.debug( "AuthResource.keys" );
+
+ if ( !isApplicationAdmin( Identifier.fromUUID( applicationId ) ) ) {
+ throw new UnauthorizedException();
+ }
+
+ ClientCredentialsInfo kp =
+ new ClientCredentialsInfo( management.getClientIdForApplication( services.getApplicationId() ),
+ management.getClientSecretForApplication( services.getApplicationId() ) );
+
+ return new JSONWithPadding(
+ createApiResponse().withCredentials( kp ).withAction( "get application keys" ).withSuccess(),
+ callback );
+ }
+
+
+ @POST
+ @Path("credentials")
+ @RequireApplicationAccess
+ @Produces(MediaType.APPLICATION_JSON)
+ public JSONWithPadding generateKeys( @Context UriInfo ui,
+ @QueryParam("callback") @DefaultValue("callback") String callback )
+ throws Exception {
+
+ logger.debug( "AuthResource.keys" );
+
+ if ( !isApplicationAdmin( Identifier.fromUUID( applicationId ) ) ) {
+ throw new UnauthorizedException();
+ }
+
+ ClientCredentialsInfo kp =
+ new ClientCredentialsInfo( management.getClientIdForApplication( services.getApplicationId() ),
+ management.newClientSecretForApplication( services.getApplicationId() ) );
+
+ return new JSONWithPadding(
+ createApiResponse().withCredentials( kp ).withAction( "generate application keys" ).withSuccess(),
+ callback );
+ }
+
+
+ @GET
+ @Path("authorize")
+ public Viewable showAuthorizeForm( @Context UriInfo ui, @QueryParam("response_type") String response_type,
+ @QueryParam("client_id") String client_id,
+ @QueryParam("redirect_uri") String redirect_uri,
+ @QueryParam("scope") String scope, @QueryParam("state") String state ) {
+
+ try {
+ UUID uuid = getUUIDFromClientId( client_id );
+ if ( uuid == null ) {
+ throw mappableSecurityException( AuthErrorInfo.OAUTH2_INVALID_CLIENT,
+ "Unable to authenticate (OAuth). Invalid client_id" );
+ }
+
+ responseType = response_type;
+ clientId = client_id;
+ redirectUri = redirect_uri;
+ this.scope = scope;
+ this.state = state;
+
+ ApplicationInfo app = management.getApplicationInfo( applicationId );
+ applicationName = app.getName();
+
+ return handleViewable( "authorize_form", this );
+ }
+ catch ( RedirectionException e ) {
+ throw e;
+ }
+ catch ( Exception e ) {
+ return handleViewable( "error", e );
+ }
+ }
+
+
+ @POST
+ @Path("authorize")
+ @Produces(MediaType.TEXT_HTML)
+ public Viewable handleAuthorizeForm( @Context UriInfo ui, @FormParam("response_type") String response_type,
+ @FormParam("client_id") String client_id,
+ @FormParam("redirect_uri") String redirect_uri,
+ @FormParam("scope") String scope, @FormParam("state") String state,
+ @FormParam("username") String username,
+ @FormParam("password") String password ) {
+
+ try {
+ responseType = response_type;
+ clientId = client_id;
+ redirectUri = redirect_uri;
+ this.scope = scope;
+ this.state = state;
+
+ User user = null;
+ String errorDescription = "Username or password do not match";
+ try {
+ user = management.verifyAppUserPasswordCredentials( services.getApplicationId(), username, password );
+ }
+ catch ( UnactivatedAdminUserException uaue ) {
+ errorDescription = "user not activated";
+ }
+ catch ( DisabledAdminUserException daue ) {
+ errorDescription = "user disabled";
+ }
+ catch ( Exception e1 ) {
++ logger.warn("Unexpected exception in authorize username/password verification", e1);
+ }
+
+ if ( ( user != null ) && isNotBlank( redirect_uri ) ) {
+ String authorizationCode =
+ management.getAccessTokenForAppUser( services.getApplicationId(), user.getUuid(), 0 );
+ redirect_uri = buildRedirectUriWithAuthCode( redirect_uri, state, authorizationCode );
+
+ throw new RedirectionException( redirect_uri );
+ }
+ else {
+ errorMsg = errorDescription;
+ }
+
+ ApplicationInfo app = management.getApplicationInfo( applicationId );
+ applicationName = app.getName();
+
+ return handleViewable( "authorize_form", this );
+ }
+ catch ( RedirectionException e ) {
+ throw e;
+ }
+ catch ( Exception e ) {
+ return handleViewable( "error", e );
+ }
+ }
+
+
+ @DELETE
+ @RequireApplicationAccess
+ @Override
+ public JSONWithPadding executeDelete( @Context UriInfo ui,
+ @QueryParam("callback") @DefaultValue("callback") String callback )
+ throws Exception {
+
+ logger.debug( "ApplicationResource.executeDelete" );
+
+ throw new NotImplementedException( "Application delete is not allowed yet" );
+ }
+
+
+ String errorMsg = "";
+ String applicationName;
+ String responseType;
+ String clientId;
+ String redirectUri;
+ String scope;
+ String state;
+
+
+ public String getErrorMsg() {
+ return errorMsg;
+ }
+
+
+ public String getApplicationName() {
+ return applicationName;
+ }
+
+
+ public String getResponseType() {
+ return responseType;
+ }
+
+
+ public String getClientId() {
+ return clientId;
+ }
+
+
+ public String getRedirectUri() {
+ return redirectUri;
+ }
+
+
+ public String getScope() {
+ return scope;
+ }
+
+
+ public String getState() {
+ return state;
+ }
+
+
+ // todo: find a mechanism to move these methods into the push notifications
+ // project
+ @RequireApplicationAccess
+ @Path("notifiers")
+ public AbstractContextResource getNotifiersResource( @Context UriInfo ui ) throws Exception {
+
+ Class cls = Class.forName( "org.apache.usergrid.rest.applications.notifiers.NotifiersResource" );
+
+ logger.debug( "NotifiersResource.getNotifiersResource" );
+ addParameter( getServiceParameters(), "notifiers" );
+
+ PathSegment ps = getFirstPathSegment( "notifiers" );
+ if ( ps != null ) {
+ addMatrixParams( getServiceParameters(), ui, ps );
+ }
+
+ return getSubResource( cls );
+ }
+
+
+ @RequireApplicationAccess
+ @Path("notifier")
+ public AbstractContextResource getNotifierResource( @Context UriInfo ui ) throws Exception {
+ return getNotifiersResource( ui );
+ }
+
+
+ private String buildRedirectUriWithAuthCode( String redirect_uri, String state, String authorizationCode )
+ throws UnsupportedEncodingException {
+ if ( !redirect_uri.contains( "?" ) ) {
+ redirect_uri += "?";
+ }
+ else {
+ redirect_uri += "&";
+ }
+ redirect_uri += "code=" + authorizationCode;
+
+ if ( isNotBlank( state ) ) {
+ redirect_uri += "&state=" + URLEncoder.encode( state, "UTF-8" );
+ }
+
+ return redirect_uri;
+ }
+
+
+ //mAX /APM integration
+ public static final String APIGEE_MOBILE_APM_CONFIG_JSON_KEY = "apigeeMobileConfig";
+
+
+ @GET
+ @Path("apm/apigeeMobileConfig")
+ public JSONWithPadding getAPMConfig( @Context UriInfo ui,
+ @QueryParam("callback") @DefaultValue("callback") String callback )
+ throws Exception {
+ EntityManager em = ( EntityManager ) emf.getEntityManager( applicationId );
+ Object value = em.getProperty( new SimpleEntityRef( Application.ENTITY_TYPE, applicationId ),
+ APIGEE_MOBILE_APM_CONFIG_JSON_KEY );
+ //If there is no apm configuration then try to create apm config on the fly
+ if ( value == null ) {
+ value = management.registerAppWithAPM( management.getOrganizationForApplication( applicationId ),
+ management.getApplicationInfo( applicationId ) );
+ }
+ return new JSONWithPadding( value, callback );
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
----------------------------------------------------------------------
diff --cc stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
index 0000000,677b384..0dae405
mode 000000,100644..100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
@@@ -1,0 -1,74 +1,69 @@@
+ package org.apache.usergrid.rest;
+
+
+ import java.io.File;
+
+ import org.junit.rules.ExternalResource;
+ import org.apache.usergrid.cassandra.AvailablePortFinder;
+
+ import org.apache.catalina.startup.Tomcat;
+ import org.apache.commons.lang.math.RandomUtils;
+
+ import com.google.common.io.Files;
+
+
+ /** @author tnine */
+ public class TomcatResource extends ExternalResource {
+
++ public static final TomcatResource instance = new TomcatResource();
+ private static Object mutex = new Object();
-
+ private static final String CONTEXT = "/";
-
++ private String webAppsPath;
+ private int port;
-
-
-
-
+ private Tomcat tomcat;
+
+ protected TomcatResource(){
-
-
+ }
+
+ @Override
+ protected void before() throws Throwable {
+ if ( tomcat != null ) {
+ return;
+ }
+
+ synchronized ( mutex ) {
+ //second into mutex
+ if ( tomcat != null ) {
+ return;
+ }
+
+ File dataDir = Files.createTempDir();
+ dataDir.deleteOnExit();
+
+ port = AvailablePortFinder.getNextAvailable( 9998 + RandomUtils.nextInt(10) );
+
+ tomcat = new Tomcat();
+ tomcat.setBaseDir( dataDir.getAbsolutePath() );
+ tomcat.setPort( port );
- tomcat.addWebapp( CONTEXT, new File( "src/main/webapp" ).getAbsolutePath() );
-
-
++ tomcat.addWebapp( CONTEXT, new File( getWebAppsPath() ).getAbsolutePath() );
+ tomcat.start();
+ }
+ }
+
+
+ /**
+ * Get the port tomcat runs on
+ * @return
+ */
+ public int getPort(){
+ return port;
+ }
+
++ public String getWebAppsPath() {
++ return webAppsPath;
++ }
+
- public static final TomcatResource instance = new TomcatResource();
-
-
++ public void setWebAppsPath(String webAppsPath) {
++ this.webAppsPath = webAppsPath;
++ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --cc stack/rest/src/test/resources/log4j.properties
index 34e591b,3a9f9bb..27a8de9
--- a/stack/rest/src/test/resources/log4j.properties
+++ b/stack/rest/src/test/resources/log4j.properties
@@@ -39,4 -39,4 +39,4 @@@ log4j.logger.org.apache.usergrid.rest.s
log4j.logger.me.prettyprint.hector.api.beans.AbstractComposite=ERROR, stdout
- log4j.logger.org.usergrid.rest.management=DEBUG
-#log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG, stdout
++log4j.logger.org.usergrid.rest.management=DEBUG
[15/50] [abbrv] git commit: finished fleshing out Client tests with a
few exceptions.
Posted by sn...@apache.org.
finished fleshing out Client tests with a few exceptions.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/8dcc1de8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/8dcc1de8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/8dcc1de8
Branch: refs/heads/optimistic-tx-semantics
Commit: 8dcc1de8c7862148f5abe0a82d68ab4a707df6f3
Parents: 4978333
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 00:50:36 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 00:50:36 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/lib/Usergrid.js | 4 +-
sdks/html5-javascript/lib/modules/Client.js | 43 +++---
sdks/html5-javascript/lib/modules/Entity.js | 2 +-
sdks/html5-javascript/tests/mocha/test.js | 173 +++++++++++++++++++++--
sdks/html5-javascript/usergrid.js | 53 ++++---
sdks/html5-javascript/usergrid.min.js | 4 +-
6 files changed, 207 insertions(+), 72 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index 3fca37a..7b28d4f 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -172,9 +172,9 @@ function doCallback(callback, params, context) {
/*
Validate our input
*/
- this.endpoint=endpoint;
+ this.endpoint=endpoint+'?'+encodeParams(query_params);
this.method = method.toUpperCase();
- this.query_params = query_params;
+ //this.query_params = query_params;
this.data = ("object" === typeof data) ? JSON.stringify(data) : data;
if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) {
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/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
index 4efae5a..683b78c 100644
--- a/sdks/html5-javascript/lib/modules/Client.js
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -62,9 +62,8 @@
} else {
uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint;
}
-
- if (self.getToken()) {
- qs.access_token = self.getToken();
+ if (this.getToken()) {
+ qs.access_token = this.getToken();
/* //could also use headers for the token
xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
xhr.withCredentials = true;
@@ -277,13 +276,11 @@
};
this.request(options, function(err, data){
- if(typeof(callback) === "function") {
if(err) {
- callback(err);
+ doCallback(callback, [err]);
} else {
- callback(err, data, data.entities);
+ doCallback(callback, [err, data, data.data.entities]);
}
- }
});
};
@@ -330,9 +327,7 @@
}
var entity = new Usergrid.Entity(options);
entity.save(function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, entity);
- }
+ doCallback(callback, [err, entity]);
});
};
@@ -491,10 +486,11 @@
grant_type: 'password'
}
};
- this.request(options, function(err, data) {
+ self.request(options, function(err, response) {
var user = {};
- if (err && self.logging) {
- console.log('error trying to log user in');
+ var data=response.data;
+ if (err) {
+ if(self.logging)console.log('error trying to log user in');
} else {
var options = {
client:self,
@@ -503,9 +499,7 @@
user = new Usergrid.Entity(options);
self.setToken(data.access_token);
}
- if (typeof(callback) === 'function') {
- callback(err, data, user);
- }
+ doCallback(callback, [err, data, user]);
});
};
@@ -523,12 +517,11 @@
} else {
//save the re-authed token and current email/username
- self.setToken(response.access_token);
+ self.setToken(response.data.access_token);
}
- if (typeof(callback) === 'function') {
- callback(err);
- }
+ doCallback(callback, [err]);
+
});
};
@@ -652,7 +645,8 @@
method:'GET',
endpoint:'users/me'
};
- this.request(options, function(err, data) {
+ this.request(options, function(err, response) {
+ var data=response.data;
if (err) {
if (self.logging) {
console.log('error trying to log user in');
@@ -667,7 +661,7 @@
};
var user = new Usergrid.Entity(options);
if (typeof(callback) === 'function') {
- callback(err, data, user);
+ callback(null, data, user);
}
}
});
@@ -683,7 +677,8 @@
* @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();
+ var token=this.getToken();
+ return "undefined" !== typeof token && token!==null;
};
/*
@@ -694,7 +689,7 @@
* @return none
*/
Usergrid.Client.prototype.logout = function () {
- this.setToken(null);
+ this.setToken();
};
/*
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/sdks/html5-javascript/lib/modules/Entity.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Entity.js b/sdks/html5-javascript/lib/modules/Entity.js
index b1225a3..8b21bd5 100644
--- a/sdks/html5-javascript/lib/modules/Entity.js
+++ b/sdks/html5-javascript/lib/modules/Entity.js
@@ -112,7 +112,7 @@ Usergrid.Entity.prototype.getEndpoint = function () {
var nameProperties=['uuid', 'name'];
if (type === undefined) {
throw new UsergridError('cannot fetch entity, no entity type specified', 'no_type_specified');
- }else if(type==="users"){
+ }else if(type==="users"||type==="user"){
nameProperties.unshift('username');
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index 8bcd19a..be4bdf6 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -344,56 +344,201 @@ describe('Usergrid Client', function() {
assert(dogs._list.length===dogCollection._list.length, "The collections have a different number of entities")
done();
})
- it('getFeedForUser',function(done){
- done();
+ var activityUser;
+ before(function(done){
+ activityUser=new Usergrid.Entity({client:client,data:{"type":"user",username:"testActivityUser"}});
+ activityUser.fetch(function(err, data){
+ if(err){
+ activityUser.save(function(err, data){
+ activityUser.set(data);
+ done();
+ });
+ }else{
+ activityUser.set(data);
+ done();
+ }
+ })
+// client.request({
+// method: 'GET',
+// endpoint: 'users/testActivityUser'
+// }, function(err, data) {
+// if(err){
+// client.request({
+// method: 'POST',
+// endpoint: 'users',
+// body: {
+// username: 'testActivityUser',
+// password: 'secret'
+// }
+// }, function(err, data) {
+// activityUser=data;
+// console.log(activityUser);
+// done();
+// });
+// }else{
+// activityUser=data;
+// console.log(activityUser);
+// done();
+// }
+// });
})
it('createUserActivity',function(done){
- done();
+ var options = {
+ "actor" : {
+ "displayName" :"Test Activity User",
+ "uuid" : activityUser.get("uuid"),
+ "username" : "testActivityUser",
+ "email" : "usergrid@apigee.com",
+ "image" : {
+ "height" : 80,
+ "url" : "http://placekitten.com/80/80",
+ "width" : 80
+ }
+ },
+ "verb" : "post",
+ "content" : "test post for createUserActivity",
+ "lat" : 48.856614,
+ "lon" : 2.352222
+ };
+ client.createUserActivity("testActivityUser", options, function(err, activity){
+ assert(!err, "createUserActivity returned an error");
+ assert(activity, "createUserActivity returned no activity object")
+ done();
+ })
})
it('createUserActivityWithEntity',function(done){
- done();
+ console.log(activityUser.get("username"));
+ client.createUserActivityWithEntity(activityUser, "Another test activity with createUserActivityWithEntity", function(err, activity){
+ assert(!err, "createUserActivityWithEntity returned an error "+err);
+ assert(activity, "createUserActivityWithEntity returned no activity object")
+ done();
+ })
})
+ it('getFeedForUser',function(done){
+ client.getFeedForUser('testActivityUser', function(err, data, items){
+ console.error(err, JSON.stringify(data.data, null, 4));
+ assert(!err, "getFeedForUser returned an error");
+ assert(data, "getFeedForUser returned no data object")
+ assert(items, "getFeedForUser returned no items array")
+ done();
+ })
+ })
+ /*after(function(done){
+ client.request({
+ method: 'DELETE',
+ endpoint: 'users/testActivityUser'
+ }, function(err, data) {
+ done();
+ });
+
+ })*/
+ var testProperty="____test_item"+Math.floor(Math.random()*10000),
+ testPropertyValue="test"+Math.floor(Math.random()*10000),
+ testPropertyObjectValue={test:testPropertyValue};
it('set',function(done){
+ client.set(testProperty, testPropertyValue);
done();
})
it('get',function(done){
+ var retrievedValue=client.get(testProperty);
+ assert(retrievedValue===testPropertyValue, "Get is not working properly");
done();
})
it('setObject',function(done){
+ client.set(testProperty, testPropertyObjectValue);
done();
})
it('getObject',function(done){
+ var retrievedValue=client.get(testProperty);
+ assert(retrievedValue==testPropertyObjectValue, "getObject is not working properly");
done();
})
- it('setToken',function(done){
+ /*it('setToken',function(done){
+ client.setToken("dummytoken");
done();
})
it('getToken',function(done){
+ assert(client.getToken()==="dummytoken");
+ done();
+ })*/
+ it('remove property',function(done){
+ client.set(testProperty);
+ assert(client.get(testProperty)===null);
done();
})
+ var newUser;
it('signup',function(done){
- done();
+ client.signup("newUsergridUser", "Us3rgr1d15Aw3s0m3!", "usergrid@apigee.com", "Another Satisfied Developer", function(err, user){
+ assert(!err, "signup returned an error");
+ assert(user, "signup returned no user object")
+ newUser=user;
+ done();
+ })
})
it('login',function(done){
- done();
+ client.login("newUsergridUser", "Us3rgr1d15Aw3s0m3!", function(err, data, user){
+ assert(!err, "login returned an error");
+ assert(user, "login returned no user object")
+ done();
+ })
})
- it('reAuthenticateLite',function(done){
+ /*it('reAuthenticateLite',function(done){
+ client.reAuthenticateLite(function(err){
+ assert(!err, "reAuthenticateLite returned an error");
+ done();
+ })
+ })*/
+ /*it('reAuthenticate',function(done){
+ client.reAuthenticate("usergrid@apigee.com", function(err, data, user, organizations, applications){
+ assert(!err, "reAuthenticate returned an error");
+ done();
+ })
+ })*/
+ /*it('loginFacebook',function(done){
+ assert(true, "Not sure how feasible it is to test this with Mocha")
done();
- })
- it('reAuthenticate',function(done){
+ })*/
+ it('isLoggedIn',function(done){
+ assert(client.isLoggedIn()===true, "isLoggedIn is not detecting that we have logged in.")
done();
})
- it('loginFacebook',function(done){
+ it('getLoggedInUser',function(done){
+ setTimeout(function(){
+ client.getLoggedInUser(function(err, data, user){
+ assert(!err, "getLoggedInUser returned an error");
+ assert(user, "getLoggedInUser returned no user object")
+ done();
+ })
+ },1000);
+ })
+ before(function(done){
+ //please enjoy this musical interlude.
+ setTimeout(function(){done()},1000);
+ })
+ it('logout',function(done){
+ client.logout();
+ assert(null===client.getToken(), "we logged out, but the token still remains.")
done();
})
it('getLoggedInUser',function(done){
- done();
+ client.getLoggedInUser(function(err, data, user){
+ assert(err, "getLoggedInUser should return an error after logout");
+ assert(!user, "getLoggedInUser should not return data after logout")
+ done();
+ })
})
it('isLoggedIn',function(done){
+ assert(client.isLoggedIn()===false, "isLoggedIn still returns true after logout.")
done();
})
- it('logout',function(done){
- done();
+ after(function (done) {
+ client.request({
+ method: 'DELETE',
+ endpoint: 'users/newUsergridUser'
+ }, function (err, data) {
+ done();
+ });
+
})
it('buildCurlCall',function(done){
done();
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 093e847..d8a888f 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -1,4 +1,4 @@
-/*! usergrid@0.0.0 2014-02-10 */
+/*! usergrid@0.0.0 2014-02-11 */
var UsergridEventable = function() {
throw Error("'UsergridEventable' is not intended to be invoked directly");
};
@@ -524,9 +524,9 @@ function doCallback(callback, params, context) {
/*
Validate our input
*/
- this.endpoint = endpoint;
+ this.endpoint = endpoint + "?" + encodeParams(query_params);
this.method = method.toUpperCase();
- this.query_params = query_params;
+ //this.query_params = query_params;
this.data = "object" === typeof data ? JSON.stringify(data) : data;
if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) {
throw new UsergridInvalidHTTPMethodError("invalid request method '" + this.method + "'");
@@ -683,8 +683,8 @@ function doCallback(callback, params, context) {
} else {
uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
}
- if (self.getToken()) {
- qs.access_token = self.getToken();
+ if (this.getToken()) {
+ qs.access_token = this.getToken();
}
var req = new Usergrid.Request(method, uri, 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) {
@@ -873,12 +873,10 @@ function doCallback(callback, params, context) {
endpoint: "users/" + username + "/feed"
};
this.request(options, function(err, data) {
- if (typeof callback === "function") {
- if (err) {
- callback(err);
- } else {
- callback(err, data, data.entities);
- }
+ if (err) {
+ doCallback(callback, [ err ]);
+ } else {
+ doCallback(callback, [ err, data, data.data.entities ]);
}
});
};
@@ -925,9 +923,7 @@ function doCallback(callback, params, context) {
};
var entity = new Usergrid.Entity(options);
entity.save(function(err, data) {
- if (typeof callback === "function") {
- callback(err, entity);
- }
+ doCallback(callback, [ err, entity ]);
});
};
/*
@@ -1073,10 +1069,11 @@ function doCallback(callback, params, context) {
grant_type: "password"
}
};
- this.request(options, function(err, data) {
+ self.request(options, function(err, response) {
var user = {};
- if (err && self.logging) {
- console.log("error trying to log user in");
+ var data = response.data;
+ if (err) {
+ if (self.logging) console.log("error trying to log user in");
} else {
var options = {
client: self,
@@ -1085,9 +1082,7 @@ function doCallback(callback, params, context) {
user = new Usergrid.Entity(options);
self.setToken(data.access_token);
}
- if (typeof callback === "function") {
- callback(err, data, user);
- }
+ doCallback(callback, [ err, data, user ]);
});
};
Usergrid.Client.prototype.reAuthenticateLite = function(callback) {
@@ -1102,11 +1097,9 @@ function doCallback(callback, params, context) {
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);
+ self.setToken(response.data.access_token);
}
+ doCallback(callback, [ err ]);
});
};
Usergrid.Client.prototype.reAuthenticate = function(email, callback) {
@@ -1220,7 +1213,8 @@ function doCallback(callback, params, context) {
method: "GET",
endpoint: "users/me"
};
- this.request(options, function(err, data) {
+ this.request(options, function(err, response) {
+ var data = response.data;
if (err) {
if (self.logging) {
console.log("error trying to log user in");
@@ -1235,7 +1229,7 @@ function doCallback(callback, params, context) {
};
var user = new Usergrid.Entity(options);
if (typeof callback === "function") {
- callback(err, data, user);
+ callback(null, data, user);
}
}
});
@@ -1250,7 +1244,8 @@ function doCallback(callback, params, context) {
* @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();
+ var token = this.getToken();
+ return "undefined" !== typeof token && token !== null;
};
/*
* A public method to log out an app user - clears all user fields from client
@@ -1260,7 +1255,7 @@ function doCallback(callback, params, context) {
* @return none
*/
Usergrid.Client.prototype.logout = function() {
- this.setToken(null);
+ this.setToken();
};
/*
* A private method to build the curl call to display on the command line
@@ -1429,7 +1424,7 @@ Usergrid.Entity.prototype.getEndpoint = function() {
var nameProperties = [ "uuid", "name" ];
if (type === undefined) {
throw new UsergridError("cannot fetch entity, no entity type specified", "no_type_specified");
- } else if (type === "users") {
+ } else if (type === "users" || type === "user") {
nameProperties.unshift("username");
}
var names = this.get(nameProperties).filter(function(x) {
[06/50] [abbrv] Test cases for Ajax,
Usergrid.Request and Usergrid.Response
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/650cfd5c/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index f5e01f2..2ea1a53 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-10 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){console.info("CALLED FROM",this.name||context?context.name:"UNKNOWN");var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prot
otype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name
,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console
[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promi
se},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},gl
obal[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(fn){var args=Array.prototype.slice.call(arguments,1);return function(){return fn.apply(this,args.concat(Array.prototype.slice(arguments,0)))}}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),self.logger.timeEnd(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&(xhr.setRequestHeader("Conten
t-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setSt
orage' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(to
ken){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","
DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeE
nd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Request.prototype.validate=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.prepare=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.fire=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),thi
s),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"
GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName");if(!mQuery&&!orgName&&!appName&&"function"==typeof this.logoutCallback)return this.logoutCallback(!0,"no_org_or_app_name_specified");uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error),doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.proto
type.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data]
)})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,funct
ion(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",tok
en)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Clie
nt.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),Usergrid.Entity=function(options){options&&(this._data=opt
ions.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),namePropertie
s=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"],options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA
#2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);i
f(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callb
ack){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._c
lient.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].c
reatedDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback)
{var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="n
o";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log(
"entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return d
ata=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;
-var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._typ
e;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),this.removeEntity(entity)},Usergrid.Collection.prototype.removeEntity=function(en
tity){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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._li
st.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collectio
n.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(er
r&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/us
ers/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callb
ack(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, de
crement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callb
ack,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new Usergrid.Error(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"str
ing":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new Usergrid.Error(data)],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(
callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergri
d.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new Usergrid.Error("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new Usergrid.Error("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new Usergrid.Error("The
File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new Usergrid.Error(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new Usergrid.Error(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=t
imestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void
0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=Usergri
dKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;if(isFunction(callback)){params||(params=[]),context||(context=this),params.push(context);try{returnValue=callback.apply(context,params)}catch(ex){console&&console.error&&console.error("Callback error:",ex)}}return returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventabl
e.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.ini
t(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&c
onsole[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new
Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)})
,p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-T
ype","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStora
ge' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token
){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DEL
ETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Request.prototype.validate=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.prepare=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.fire=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),
p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET
",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodePara
ms(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entit
y.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callba
ck){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){retu
rn 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=fun
ction(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applica
tions={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Us
ergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof thi
s.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrit
tenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[
field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===EN
TITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connect
ion,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):enti
ty.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"
/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client
.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"functio
n"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_p
art.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELE
TE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(da
ta.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++
+}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(
var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy ent
ity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;retu
rn hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNex
tPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback
&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(e
rror,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80
}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Coun
<TRUNCATED>
[28/50] [abbrv] git commit: Merge pull request #51 from r3b/JS_SDK_2.0
Posted by sn...@apache.org.
Merge pull request #51 from r3b/JS_SDK_2.0
Organizing and refactoring the Javascript SDK
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/7aa369ff
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/7aa369ff
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/7aa369ff
Branch: refs/heads/optimistic-tx-semantics
Commit: 7aa369ff259209a3908240a29b16bf34d5d73091
Parents: bc3dfba 52f0e02
Author: Rod Simpson <ro...@rodsimpson.com>
Authored: Tue Feb 11 15:47:26 2014 -0700
Committer: Rod Simpson <ro...@rodsimpson.com>
Committed: Tue Feb 11 15:47:26 2014 -0700
----------------------------------------------------------------------
.gitignore | 5 +-
sdks/html5-javascript/Gruntfile.js | 169 +-
sdks/html5-javascript/lib/Client.js | 865 ------
sdks/html5-javascript/lib/Collection.js | 446 ---
sdks/html5-javascript/lib/Counter.js | 186 --
sdks/html5-javascript/lib/Entity.js | 646 -----
sdks/html5-javascript/lib/Group.js | 233 --
sdks/html5-javascript/lib/Module.js | 34 +
sdks/html5-javascript/lib/Usergrid.js | 283 +-
sdks/html5-javascript/lib/modules/Asset.js | 149 +
sdks/html5-javascript/lib/modules/Client.js | 749 +++++
sdks/html5-javascript/lib/modules/Collection.js | 459 +++
sdks/html5-javascript/lib/modules/Counter.js | 186 ++
sdks/html5-javascript/lib/modules/Entity.js | 659 +++++
sdks/html5-javascript/lib/modules/Error.js | 125 +
sdks/html5-javascript/lib/modules/Folder.js | 167 ++
sdks/html5-javascript/lib/modules/Group.js | 233 ++
sdks/html5-javascript/lib/modules/util/Ajax.js | 74 +
sdks/html5-javascript/lib/modules/util/Event.js | 33 +
.../html5-javascript/lib/modules/util/Logger.js | 68 +
.../lib/modules/util/Promise.js | 83 +
sdks/html5-javascript/tests/mocha/test.js | 1036 +++++--
.../tests/resources/js/blanket_mocha.min.js | 2 +-
sdks/html5-javascript/usergrid.js | 2673 +++++++++++-------
sdks/html5-javascript/usergrid.min.js | 5 +-
25 files changed, 5953 insertions(+), 3615 deletions(-)
----------------------------------------------------------------------
[41/50] [abbrv] git commit: Fix compile problem in Query Validator.
Posted by sn...@apache.org.
Fix compile problem in Query Validator.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/c5b43cf1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/c5b43cf1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/c5b43cf1
Branch: refs/heads/optimistic-tx-semantics
Commit: c5b43cf125e24660812593c3546aa7eda87aad83
Parents: eb46ac7
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 08:47:31 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 08:47:31 2014 -0500
----------------------------------------------------------------------
stack/query-validator/pom.xml | 6 ++++++
.../apache/usergrid/query/validator/QueryValidatorRunner.java | 3 ++-
2 files changed, 8 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/c5b43cf1/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/pom.xml b/stack/query-validator/pom.xml
index 33c61f9..13f36d3 100644
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@ -120,6 +120,12 @@
<classifier>tests</classifier>
</dependency>
<dependency>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-launcher</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/c5b43cf1/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
index 4637ec5..7e8143b 100644
--- a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
@@ -32,7 +32,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import org.apache.cassandra.transport.Server;
+import org.apache.usergrid.launcher.Server;
+import org.apache.usergrid.management.ManagementService;
/**
* @author Sung-ju Jin(realbeast)
[25/50] [abbrv] git commit: removed Storable and references
Posted by sn...@apache.org.
removed Storable and references
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/6b03eed1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/6b03eed1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/6b03eed1
Branch: refs/heads/optimistic-tx-semantics
Commit: 6b03eed15e8a7176d0ccb5ebda31c42731cf1c0d
Parents: a0a585b
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 13:06:25 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 13:06:25 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/Gruntfile.js | 1 -
sdks/html5-javascript/lib/Usergrid.js | 1 -
.../lib/modules/util/Storable.js | 88 ------------------
sdks/html5-javascript/tests/mocha/test.js | 1 +
sdks/html5-javascript/usergrid.js | 97 --------------------
sdks/html5-javascript/usergrid.min.js | 4 +-
6 files changed, 3 insertions(+), 189 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/Gruntfile.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/Gruntfile.js b/sdks/html5-javascript/Gruntfile.js
index cfa39e3..82c2029 100644
--- a/sdks/html5-javascript/Gruntfile.js
+++ b/sdks/html5-javascript/Gruntfile.js
@@ -4,7 +4,6 @@ module.exports = function(grunt) {
"lib/modules/util/Logger.js",
"lib/modules/util/Promise.js",
"lib/modules/util/Ajax.js",
- "lib/modules/util/Storable.js",
"lib/Usergrid.js",
"lib/modules/Client.js",
"lib/modules/Entity.js",
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index 7b28d4f..9ef2583 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -204,7 +204,6 @@ function doCallback(callback, params, context) {
return p;
};
- Usergrid.Request.prototype= new UsergridStorable();
//TODO more granular handling of statusCodes
Usergrid.Response = function (err, response) {
var p = new Promise();
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/lib/modules/util/Storable.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Storable.js b/sdks/html5-javascript/lib/modules/util/Storable.js
deleted file mode 100644
index 5c4da2e..0000000
--- a/sdks/html5-javascript/lib/modules/util/Storable.js
+++ /dev/null
@@ -1,88 +0,0 @@
-function UsergridStorable(storage, keyPrefix){
- //throw Error("'UsergridStorable' is not intended to be invoked directly")
-}
-UsergridStorable.prototype.setStorage = function(storage) {
- if(!(storage instanceof Storage)){
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- storage=sessionStorage;
- }
- return this._storage=storage;
-};
-UsergridStorable.prototype.getStorage = function() {
- if(!(this._storage instanceof Storage)){
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- this._storage=sessionStorage;
- }
- return this._storage;
-};
-UsergridStorable.prototype.getStorageKey = function(key) {
- if(!this._keyPrefix)this._keyPrefix='usergrid_js_sdk_';
- return this._keyPrefix+key;
-};
-UsergridStorable.prototype.get=function(key){
- var value;
- if(arguments.length>1){
- key=[].slice.call(arguments).reduce(function(p,c,i,a){
- if(c instanceof Array){
- p= p.concat(c);
- }else{
- p.push(c);
- }
- return p;
- },[]);
- }
- if(this._storage instanceof Storage){
- if(key instanceof Array){
- var self=this;
- value=key.map(function(k){return self.get(k)});
- }else if("undefined" !== typeof key){
- this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
- value=this[key];
- }
- }
- return value;
-}
-UsergridStorable.prototype.set=function(key, value){
- if(this._storage instanceof Storage){
- if(value){
- this[key]=JSON.stringify(value);
- this.getStorage().setItem(this.getStorageKey(key),this[key]);
- }else{
- delete this[key];
- this.getStorage().removeItem(this.getStorageKey(key));
- }
- }
-}
-/*
- * A public method to store the OAuth token for later use - uses localstorage if available
- *
- * @method setToken
- * @public
- * @params {string} token
- * @return none
- */
-UsergridStorable.prototype.setToken = function (token) {
- return this.set('token', token);
-};
-
-/*
- * A public method to get the OAuth token
- *
- * @method getToken
- * @public
- * @return {string} token
- */
-UsergridStorable.prototype.getToken = function () {
- return this.get('token');
-};
-UsergridStorable.mixin = function(destObject){
- var props = ['getStorage', 'setStorage', 'getStorageKey', 'get', 'set', 'getToken', 'setToken'];
- for(var i = 0; i < props.length; i ++){
- if(props[i] in destObject.prototype){
- console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'.");
- console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'.");
- destObject.prototype['_'+props[i]]=destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index e430c02..216aa0a 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -163,6 +163,7 @@ describe('Usergrid Client', function() {
var client = getClient();
describe('Usergrid CRUD request', function() {
before(function(done) {
+ this.timeout(10000);
//Make sure our dog doesn't already exist
client.request({
method: 'DELETE',
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index ff83f6c..59e80ef 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -253,102 +253,6 @@ UsergridEventable.mixin = function(destObject) {
return global[name];
})();
-function UsergridStorable(storage, keyPrefix) {}
-
-UsergridStorable.prototype.setStorage = function(storage) {
- if (!(storage instanceof Storage)) {
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- storage = sessionStorage;
- }
- return this._storage = storage;
-};
-
-UsergridStorable.prototype.getStorage = function() {
- if (!(this._storage instanceof Storage)) {
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- this._storage = sessionStorage;
- }
- return this._storage;
-};
-
-UsergridStorable.prototype.getStorageKey = function(key) {
- if (!this._keyPrefix) this._keyPrefix = "usergrid_js_sdk_";
- return this._keyPrefix + key;
-};
-
-UsergridStorable.prototype.get = function(key) {
- var value;
- if (arguments.length > 1) {
- key = [].slice.call(arguments).reduce(function(p, c, i, a) {
- if (c instanceof Array) {
- p = p.concat(c);
- } else {
- p.push(c);
- }
- return p;
- }, []);
- }
- if (this._storage instanceof Storage) {
- if (key instanceof Array) {
- var self = this;
- value = key.map(function(k) {
- return self.get(k);
- });
- } else if ("undefined" !== typeof key) {
- this[key] = JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
- value = this[key];
- }
- }
- return value;
-};
-
-UsergridStorable.prototype.set = function(key, value) {
- if (this._storage instanceof Storage) {
- if (value) {
- this[key] = JSON.stringify(value);
- this.getStorage().setItem(this.getStorageKey(key), this[key]);
- } else {
- delete this[key];
- this.getStorage().removeItem(this.getStorageKey(key));
- }
- }
-};
-
-/*
- * A public method to store the OAuth token for later use - uses localstorage if available
- *
- * @method setToken
- * @public
- * @params {string} token
- * @return none
- */
-UsergridStorable.prototype.setToken = function(token) {
- return this.set("token", token);
-};
-
-/*
- * A public method to get the OAuth token
- *
- * @method getToken
- * @public
- * @return {string} token
- */
-UsergridStorable.prototype.getToken = function() {
- return this.get("token");
-};
-
-UsergridStorable.mixin = function(destObject) {
- var props = [ "getStorage", "setStorage", "getStorageKey", "get", "set", "getToken", "setToken" ];
- for (var i = 0; i < props.length; i++) {
- if (props[i] in destObject.prototype) {
- console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'.");
- console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'.");
- destObject.prototype["_" + props[i]] = destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
- }
-};
-
/*
* This module is a collection of classes designed to make working with
* the Appigee App Services API as easy as possible.
@@ -557,7 +461,6 @@ function doCallback(callback, params, context) {
Promise.chain([ request, response ]).then(oncomplete);
return p;
};
- Usergrid.Request.prototype = new UsergridStorable();
//TODO more granular handling of statusCodes
Usergrid.Response = function(err, response) {
var p = new Promise();
[42/50] [abbrv] git commit: Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
Merge branch 'master' into two-dot-o
Conflicts:
stack/query-validator/pom.xml
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/55293d10
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/55293d10
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/55293d10
Branch: refs/heads/optimistic-tx-semantics
Commit: 55293d10e14926796625362885dfa1d86b4d2c11
Parents: 3ed72f1
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 09:20:02 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 09:20:02 2014 -0500
----------------------------------------------------------------------
stack/query-validator/pom.xml | 152 ++++++++++++++++---------------------
1 file changed, 67 insertions(+), 85 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/55293d10/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/pom.xml b/stack/query-validator/pom.xml
index bace601..fda8466 100644
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@ -9,15 +9,19 @@
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <!-- This seems to be a safe figure -->
- <core.it.heapmax>1024m</core.it.heapmax>
- <core.it.heapmin>1024m</core.it.heapmin>
</properties>
<artifactId>usergrid-query-validator</artifactId>
<name>Usergrid Query Validator</name>
- <description>Query validator tools for Usergrid.</description>
+ <description>Query validator tools for Usergrid system.</description>
<packaging>jar</packaging>
-
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-report-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </reporting>
<build>
<resources>
<resource>
@@ -33,7 +37,9 @@
<directory>src/test/resources</directory>
<filtering>true</filtering>
<includes>
- <include>**/*</include>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ <include>**/*.json</include>
</includes>
</testResource>
</testResources>
@@ -42,17 +48,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
- <argLine>-Xmx${core.it.heapmax} -Xms${core.it.heapmin} -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
- </argLine>
-
- <includes>
- <include>**/*Suite.java</include>
- </includes>
- <excludes>
- <!-- Need to exclude Suite tests to prevent double execution -->
- <exclude>**/UserQueryIT.java</exclude>
- </excludes>
-
+ <testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>
@@ -81,6 +77,7 @@
<goal>test-jar</goal>
</goals>
<configuration>
+ <classifier>tests</classifier>
<includes>
<include>**/org/apache/usergrid/**</include>
</includes>
@@ -95,25 +92,26 @@
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-config</artifactId>
<version>${project.version}</version>
+ <scope>test</scope>
+ <classifier>tests</classifier>
</dependency>
-
<dependency>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-test-utils</artifactId>
<version>${project.version}</version>
- <classifier>compiled-jsp</classifier>
+ <scope>test</scope>
</dependency>
-
<dependency>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>commons-logging</artifactId>
+ <groupId>commons-logging</groupId>
+ </exclusion>
+ </exclusions>
</dependency>
-
- <!-- Apache Dependencies -->
-
<dependency>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-core</artifactId>
@@ -121,100 +119,85 @@
<scope>test</scope>
<classifier>tests</classifier>
</dependency>
-
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-test-utils</artifactId>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-launcher</artifactId>
<version>${project.version}</version>
- <scope>test</scope>
+ <scope>compile</scope>
</dependency>
-
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-core</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- <classifier>tests</classifier>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
</dependency>
-
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
<scope>test</scope>
</dependency>
-
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
<scope>test</scope>
</dependency>
-
<dependency>
- <groupId>org.jvnet.mock-javamail</groupId>
- <artifactId>mock-javamail</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
<scope>test</scope>
</dependency>
-
<dependency>
- <groupId>org.hectorclient</groupId>
- <artifactId>hector-test</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
<scope>test</scope>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-core</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ <exclusions>
+ <exclusion>
+ <artifactId>commons-logging</artifactId>
+ <groupId>commons-logging</groupId>
+ </exclusion>
+ </exclusions>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-logging-juli</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-jasper</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-beans</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat</groupId>
- <artifactId>tomcat-jasper-el</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat</groupId>
- <artifactId>tomcat-jsp-api</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
</dependency>
-
<dependency>
- <groupId>org.apache.tomcat</groupId>
- <artifactId>juli</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context-support</artifactId>
</dependency>
-
- <!-- use the external test client. Just depend on the maven jetty plugin to launch jetty -->
<dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-external</artifactId>
- <scope>test</scope>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-web</artifactId>
</dependency>
-
<dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-core</artifactId>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
-
<dependency>
- <groupId>org.usergrid</groupId>
- <artifactId>usergrid-java-client</artifactId>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-jdbc</artifactId>
+ <version>${org.springframework.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
-
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
@@ -226,7 +209,6 @@
<version>0.0.3</version>
<scope>compile</scope>
</dependency>
-
</dependencies>
-</project>
+</project>
\ No newline at end of file
[08/50] [abbrv] git commit: tests for UsergridError
Posted by sn...@apache.org.
tests for UsergridError
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/a976d1a7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/a976d1a7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/a976d1a7
Branch: refs/heads/optimistic-tx-semantics
Commit: a976d1a7781e46ab76ea9db2852fb45795dbb0c6
Parents: 650cfd5
Author: ryan bridges <rb...@apigee.com>
Authored: Mon Feb 10 16:46:43 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Mon Feb 10 16:46:43 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/tests/mocha/test.js | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a976d1a7/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index f3cb9e4..350706c 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -58,6 +58,24 @@ describe('Ajax', function() {
})
})
});
+describe('UsergridError', function() {
+ var errorResponse={
+ "error":"service_resource_not_found",
+ "timestamp":1392067967144,
+ "duration":0,
+ "exception":"org.usergrid.services.exceptions.ServiceResourceNotFoundException",
+ "error_description":"Service resource not found"
+ };
+ it('should unmarshal a response from Usergrid into a proper Javascript error',function(done){
+ var error = UsergridError.fromResponse(errorResponse);
+ console.log(error, errorResponse);
+ assert(error.name===errorResponse.error, "Error name not set correctly");
+ console.log(error.name,errorResponse.error);
+ assert(error.message===errorResponse.error_description, "Error message not set correctly");
+ console.log(error.message,errorResponse.error_description);
+ done();
+ });
+});
describe('Usergrid Request/Response', function() {
var dogName="dog"+Math.floor(Math.random()*10000);
var dogData=JSON.stringify({type:"dog",name:dogName});
[02/50] [abbrv] git commit: Update contribution blurb
Posted by sn...@apache.org.
Update contribution blurb
Linking to our approved contribution workflow on the wiki.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/f9da5bb8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/f9da5bb8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/f9da5bb8
Branch: refs/heads/optimistic-tx-semantics
Commit: f9da5bb8eca93133edbd017ada01d6e8f0f11037
Parents: ad8d78f
Author: Tim Anglade <ti...@gmail.com>
Authored: Sun Feb 9 21:42:15 2014 -0800
Committer: Tim Anglade <ti...@gmail.com>
Committed: Sun Feb 9 21:42:15 2014 -0800
----------------------------------------------------------------------
stack/README.md | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/f9da5bb8/stack/README.md
----------------------------------------------------------------------
diff --git a/stack/README.md b/stack/README.md
index 31f27ab..7f00962 100644
--- a/stack/README.md
+++ b/stack/README.md
@@ -84,9 +84,7 @@ Let’s use it to create a collection with some data in it:
## Contributing
-We welcome all contributions! If you want to submit code, please submit a pull request to [apigee/usergrid-stack](https://github.com/apigee/usergrid-stack/), using a [topic branch](http://git-scm.com/book/en/Git-Branching-Branching-Workflows).
-
-We’d prefer if your commit messages referenced the issue at hand (if applicable). We don’t have particular guidelines for commit messages but we appreciate branch names that observe the following format: `issue#-singleworddescription` (i.e. `325-twitter`) or just a single word if no issue exists on the topic. Thanks!
+We welcome all contributions, including via pull requests on GitHub! If you want to submit code, please read more about our [contribution workflow](https://cwiki.apache.org/confluence/display/usergrid/GitHub+Based+Contribution+Workflow)
## Licenses
[34/50] [abbrv] Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
----------------------------------------------------------------------
diff --cc stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
index 0000000,ec67483..16835dd
mode 000000,100644..100644
--- a/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
+++ b/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
@@@ -1,0 -1,2890 +1,2923 @@@
+ /*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+ package org.apache.usergrid.management.cassandra;
+
+
+ import java.nio.ByteBuffer;
+ import java.util.ArrayList;
+ import java.util.Collections;
+ import java.util.HashMap;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Map.Entry;
+ import java.util.Properties;
+ import java.util.Set;
+ import java.util.UUID;
+
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+ import org.springframework.beans.factory.annotation.Autowired;
+ import org.apache.usergrid.locking.Lock;
+ import org.apache.usergrid.locking.LockManager;
+ import org.apache.usergrid.management.AccountCreationProps;
+ import org.apache.usergrid.management.ActivationState;
+ import org.apache.usergrid.management.ApplicationInfo;
+ import org.apache.usergrid.management.ManagementService;
+ import org.apache.usergrid.management.OrganizationInfo;
+ import org.apache.usergrid.management.OrganizationOwnerInfo;
+ import org.apache.usergrid.management.UserInfo;
+ import org.apache.usergrid.management.exceptions.DisabledAdminUserException;
+ import org.apache.usergrid.management.exceptions.DisabledAppUserException;
+ import org.apache.usergrid.management.exceptions.IncorrectPasswordException;
+ import org.apache.usergrid.management.exceptions.ManagementException;
+ import org.apache.usergrid.management.exceptions.RecentlyUsedPasswordException;
+ import org.apache.usergrid.management.exceptions.UnableToLeaveOrganizationException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAdminUserException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAppUserException;
+ import org.apache.usergrid.management.exceptions.UnconfirmedAdminUserException;
+ import org.apache.usergrid.persistence.CredentialsInfo;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.EntityManager;
+ import org.apache.usergrid.persistence.EntityManagerFactory;
+ import org.apache.usergrid.persistence.EntityRef;
+ import org.apache.usergrid.persistence.Identifier;
+ import org.apache.usergrid.persistence.Results;
+ import org.apache.usergrid.persistence.Results.Level;
+ import org.apache.usergrid.persistence.SimpleEntityRef;
+ import org.apache.usergrid.persistence.entities.Application;
+ import org.apache.usergrid.persistence.entities.Group;
+ import org.apache.usergrid.persistence.entities.User;
+ import org.apache.usergrid.persistence.exceptions.DuplicateUniquePropertyExistsException;
+ import org.apache.usergrid.persistence.exceptions.EntityNotFoundException;
+ import org.apache.usergrid.security.AuthPrincipalInfo;
+ import org.apache.usergrid.security.AuthPrincipalType;
+ import org.apache.usergrid.security.crypto.EncryptionService;
+ import org.apache.usergrid.security.oauth.AccessInfo;
+ import org.apache.usergrid.security.oauth.ClientCredentialsInfo;
+ import org.apache.usergrid.security.salt.SaltProvider;
+ import org.apache.usergrid.security.shiro.PrincipalCredentialsToken;
+ import org.apache.usergrid.security.shiro.credentials.ApplicationClientCredentials;
+ import org.apache.usergrid.security.shiro.credentials.OrganizationClientCredentials;
+ import org.apache.usergrid.security.shiro.principals.ApplicationPrincipal;
+ import org.apache.usergrid.security.shiro.principals.OrganizationPrincipal;
+ import org.apache.usergrid.security.shiro.utils.SubjectUtils;
+ import org.apache.usergrid.security.tokens.TokenCategory;
+ import org.apache.usergrid.security.tokens.TokenInfo;
+ import org.apache.usergrid.security.tokens.TokenService;
+ import org.apache.usergrid.security.tokens.exceptions.TokenException;
+ import org.apache.usergrid.services.ServiceAction;
+ import org.apache.usergrid.services.ServiceManager;
+ import org.apache.usergrid.services.ServiceManagerFactory;
+ import org.apache.usergrid.services.ServiceRequest;
+ import org.apache.usergrid.services.ServiceResults;
+ import org.apache.usergrid.utils.ConversionUtils;
+ import org.apache.usergrid.utils.JsonUtils;
+ import org.apache.usergrid.utils.MailUtils;
+ import org.apache.usergrid.utils.StringUtils;
+ import org.apache.usergrid.utils.UUIDUtils;
+
+ import org.apache.commons.codec.digest.DigestUtils;
+ import org.apache.commons.lang.text.StrSubstitutor;
+ import org.apache.shiro.UnavailableSecurityManagerException;
+
+ import com.google.common.collect.BiMap;
+ import com.google.common.collect.HashBiMap;
+
+ import static java.lang.Boolean.parseBoolean;
+
+ import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString;
+ import static org.apache.commons.codec.digest.DigestUtils.sha;
+ import static org.apache.commons.lang.StringUtils.isBlank;
+ import static org.apache.usergrid.locking.LockHelper.getUniqueUpdateLock;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_ADMIN_ACTIVATION_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_ADMIN_CONFIRMATION_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_ADMIN_RESETPW_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_ACTIVATED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_CONFIRMATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_CONFIRMED_AWAITING_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_INVITED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_PASSWORD_RESET;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ADMIN_USER_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_FOOTER;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ORGANIZATION_ACTIVATED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ORGANIZATION_CONFIRMATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_ORGANIZATION_CONFIRMED_AWAITING_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_SYSADMIN_ADMIN_ACTIVATED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_SYSADMIN_ADMIN_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_SYSADMIN_ORGANIZATION_ACTIVATED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_SYSADMIN_ORGANIZATION_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_USER_ACTIVATED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_USER_CONFIRMATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_USER_CONFIRMED_AWAITING_ACTIVATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_USER_PASSWORD_RESET;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_EMAIL_USER_PIN_REQUEST;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_MAILER_EMAIL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_ORGANIZATION_ACTIVATION_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SETUP_TEST_ACCOUNT;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SYSADMIN_EMAIL;
++import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SYSADMIN_LOGIN_ALLOWED;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SYSADMIN_LOGIN_EMAIL;
++import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SYSADMIN_LOGIN_NAME;
++import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_SYSADMIN_LOGIN_PASSWORD;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_ADMIN_USER_EMAIL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_ADMIN_USER_NAME;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_ADMIN_USER_PASSWORD;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_ADMIN_USER_USERNAME;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_APP;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_TEST_ACCOUNT_ORGANIZATION;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_USER_ACTIVATION_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_USER_CONFIRMATION_URL;
+ import static org.apache.usergrid.management.AccountCreationProps.PROPERTIES_USER_RESETPW_URL;
+ import static org.apache.usergrid.persistence.CredentialsInfo.getCredentialsSecret;
+ import static org.apache.usergrid.persistence.Schema.DICTIONARY_CREDENTIALS;
+ import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
+ import static org.apache.usergrid.persistence.Schema.PROPERTY_PATH;
+ import static org.apache.usergrid.persistence.Schema.PROPERTY_SECRET;
+ import static org.apache.usergrid.persistence.Schema.PROPERTY_UUID;
+ import static org.apache.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION_ID;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_ACTOR;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_ACTOR_NAME;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_CATEGORY;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_CONTENT;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_DISPLAY_NAME;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_ENTITY_TYPE;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_OBJECT;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_OBJECT_ENTITY_TYPE;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_OBJECT_NAME;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_OBJECT_TYPE;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_TITLE;
+ import static org.apache.usergrid.persistence.entities.Activity.PROPERTY_VERB;
+ import static org.apache.usergrid.security.AuthPrincipalType.ADMIN_USER;
+ import static org.apache.usergrid.security.AuthPrincipalType.APPLICATION;
+ import static org.apache.usergrid.security.AuthPrincipalType.APPLICATION_USER;
+ import static org.apache.usergrid.security.AuthPrincipalType.ORGANIZATION;
+ import static org.apache.usergrid.security.oauth.ClientCredentialsInfo.getTypeFromClientId;
+ import static org.apache.usergrid.security.oauth.ClientCredentialsInfo.getUUIDFromClientId;
+ import static org.apache.usergrid.security.tokens.TokenCategory.ACCESS;
+ import static org.apache.usergrid.security.tokens.TokenCategory.EMAIL;
+ import static org.apache.usergrid.services.ServiceParameter.parameters;
+ import static org.apache.usergrid.services.ServicePayload.payload;
+ import static org.apache.usergrid.services.ServiceResults.genericServiceResults;
+ import static org.apache.usergrid.utils.ClassUtils.cast;
+ import static org.apache.usergrid.utils.ConversionUtils.bytes;
+ import static org.apache.usergrid.utils.ConversionUtils.uuid;
+ import static org.apache.usergrid.utils.ListUtils.anyNull;
+ import static org.apache.usergrid.utils.MapUtils.hashMap;
+ import static org.apache.usergrid.utils.PasswordUtils.mongoPassword;
+
+
+ public class ManagementServiceImpl implements ManagementService {
+ private static final Logger logger = LoggerFactory.getLogger( ManagementServiceImpl.class );
+
+ /** Key for the user's pin */
+ protected static final String USER_PIN = "pin";
+
+ /** Key for the user's oauth secret */
+ protected static final String USER_TOKEN = "secret";
+
+ /** Key for the user's mongo password */
+ protected static final String USER_MONGO_PASSWORD = "mongo_pwd";
+
+ /** Key for the user's password */
+ protected static final String USER_PASSWORD = "password";
+
+ protected static final String USER_PASSWORD_HISTORY = "password_history";
+
+ private static final String TOKEN_TYPE_ACTIVATION = "activate";
+
+ private static final String TOKEN_TYPE_PASSWORD_RESET = "resetpw";
+
+ private static final String TOKEN_TYPE_CONFIRM = "confirm";
+
+ public static final String MANAGEMENT_APPLICATION = "management";
+
+ public static final String APPLICATION_INFO = "application_info";
+
+
+ public static final String OAUTH_SECRET_SALT = "super secret oauth value";
+
+ private static final String ORGANIZATION_PROPERTIES_DICTIONARY = "orgProperties";
+ public static final String REGISTRATION_REQUIRES_ADMIN_APPROVAL = "registration_requires_admin_approval";
+ public static final String REGISTRATION_REQUIRES_EMAIL_CONFIRMATION = "registration_requires_email_confirmation";
+ public static final String NOTIFY_ADMIN_OF_NEW_USERS = "notify_admin_of_new_users";
+
+ protected ServiceManagerFactory smf;
+
+ protected EntityManagerFactory emf;
+
+ protected AccountCreationPropsImpl properties;
+
+ protected LockManager lockManager;
+
+ protected TokenService tokens;
+
+ protected SaltProvider saltProvider;
+
+ @Autowired
+ protected MailUtils mailUtils;
+
+ protected EncryptionService encryptionService;
+
+
+ /** Must be constructed with a CassandraClientPool. */
+ public ManagementServiceImpl() {
+ }
+
+
+ @Autowired
+ public void setEntityManagerFactory( EntityManagerFactory emf ) {
+ logger.info( "ManagementServiceImpl.setEntityManagerFactory" );
+ this.emf = emf;
+ }
+
+
+ @Autowired
+ public void setProperties( Properties properties ) {
+ this.properties = new AccountCreationPropsImpl( properties );
+ }
+
+
+ /** For testing purposes only */
+ public Properties getProperties() {
+ return properties.properties;
+ }
+
+
+ @Autowired
+ public void setTokenService( TokenService tokens ) {
+ this.tokens = tokens;
+ }
+
+
+ @Autowired
+ public void setServiceManagerFactory( ServiceManagerFactory smf ) {
+ this.smf = smf;
+ }
+
+
+ public LockManager getLockManager() {
+ return lockManager;
+ }
+
+
+ @Autowired
+ public void setLockManager( LockManager lockManager ) {
+ this.lockManager = lockManager;
+ }
+
+
+ /** @param encryptionService the encryptionService to set */
+ @Autowired
+ public void setEncryptionService( EncryptionService encryptionService ) {
+ this.encryptionService = encryptionService;
+ }
+
+
+ @Override
+ public void setup() throws Exception {
+
- if ( parseBoolean( properties.getProperty( PROPERTIES_SETUP_TEST_ACCOUNT ) ) ) {
++ if ( getBooleanProperty( PROPERTIES_SETUP_TEST_ACCOUNT ) ) {
+ String test_app_name = properties.getProperty( PROPERTIES_TEST_ACCOUNT_APP );
+ String test_organization_name = properties.getProperty( PROPERTIES_TEST_ACCOUNT_ORGANIZATION );
+ String test_admin_username = properties.getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_USERNAME );
+ String test_admin_name = properties.getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_NAME );
+ String test_admin_email = properties.getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_EMAIL );
+ String test_admin_password = properties.getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_PASSWORD );
+
+ if ( anyNull( test_app_name, test_organization_name, test_admin_username, test_admin_name, test_admin_email,
+ test_admin_password ) ) {
+ logger.warn( "Missing values for test app, check properties. Skipping test app setup..." );
+ return;
+ }
+
+ OrganizationInfo organization = getOrganizationByName( test_organization_name );
+
+ if ( organization == null ) {
+ OrganizationOwnerInfo created =
+ createOwnerAndOrganization( test_organization_name, test_admin_username, test_admin_name,
+ test_admin_email, test_admin_password, true, false );
+ organization = created.getOrganization();
+ }
+
+ if ( !getApplicationsForOrganization( organization.getUuid() ).containsValue( test_app_name ) ) {
+ createApplication( organization.getUuid(), test_app_name );
+ }
+ }
+ else {
+ logger.warn( "Test app creation disabled" );
+ }
+
- if ( properties.getSuperUser().isEnabled() ) {
++ if ( superuserEnabled() ) {
+ provisionSuperuser();
+ }
+ }
+
+
++ public boolean superuserEnabled() {
++ boolean superuser_enabled = getBooleanProperty( PROPERTIES_SYSADMIN_LOGIN_ALLOWED );
++ String superuser_username = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_NAME );
++ String superuser_email = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL );
++ String superuser_password = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_PASSWORD );
++
++ return superuser_enabled && !anyNull( superuser_username, superuser_email, superuser_password );
++ }
++
++
+ @Override
+ public void provisionSuperuser() throws Exception {
- final AccountCreationProps.SuperUser superUser = properties.getSuperUser();
- if ( superUser.isEnabled() ) {
- UserInfo user = this.getAdminUserByUsername( superUser.getUsername() );
++ boolean superuser_enabled = getBooleanProperty( PROPERTIES_SYSADMIN_LOGIN_ALLOWED );
++ String superuser_username = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_NAME );
++ String superuser_email = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL );
++ String superuser_password = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_PASSWORD );
++
++ if ( !anyNull( superuser_username, superuser_email, superuser_password ) ) {
++ UserInfo user = this.getAdminUserByUsername( superuser_username );
+ if ( user == null ) {
- createAdminUser( superUser.getUsername(), "Super User", superUser.getEmail(), superUser.getPassword(),
- superUser.isEnabled(), !superUser.isEnabled() );
++ createAdminUser( superuser_username, "Super User", superuser_email, superuser_password,
++ superuser_enabled, !superuser_enabled );
+ }
+ else {
- this.setAdminUserPassword( user.getUuid(), superUser.getPassword() );
++ this.setAdminUserPassword( user.getUuid(), superuser_password );
+ }
+ }
+ else {
+ logger.warn(
+ "Missing values for superuser account, check properties. Skipping superuser account setup..." );
+ }
+ }
+
+
+ public String generateOAuthSecretKey( AuthPrincipalType type ) {
+ long timestamp = System.currentTimeMillis();
+ ByteBuffer bytes = ByteBuffer.allocate( 20 );
+ bytes.put( sha( timestamp + OAUTH_SECRET_SALT + UUID.randomUUID() ) );
+ String secret = type.getBase64Prefix() + encodeBase64URLSafeString( bytes.array() );
+ return secret;
+ }
+
+
+ @SuppressWarnings( "serial" )
+ @Override
+ public void postOrganizationActivity( UUID organizationId, final UserInfo user, String verb, final EntityRef object,
+ final String objectType, final String objectName, String title,
+ String content ) throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+
+ Map<String, Object> properties = new HashMap<String, Object>();
+ properties.put( PROPERTY_VERB, verb );
+ properties.put( PROPERTY_CATEGORY, "admin" );
+ if ( content != null ) {
+ properties.put( PROPERTY_CONTENT, content );
+ }
+ if ( title != null ) {
+ properties.put( PROPERTY_TITLE, title );
+ }
+ properties.put( PROPERTY_ACTOR, new HashMap<String, Object>() {
+ {
+ put( PROPERTY_DISPLAY_NAME, user.getName() );
+ put( PROPERTY_OBJECT_TYPE, "person" );
+ put( PROPERTY_ENTITY_TYPE, "user" );
+ put( PROPERTY_UUID, user.getUuid() );
+ }
+ } );
+ properties.put( PROPERTY_OBJECT, new HashMap<String, Object>() {
+ {
+ put( PROPERTY_DISPLAY_NAME, objectName );
+ put( PROPERTY_OBJECT_TYPE, objectType );
+ put( PROPERTY_ENTITY_TYPE, object.getType() );
+ put( PROPERTY_UUID, object.getUuid() );
+ }
+ } );
+
+ sm.newRequest( ServiceAction.POST, parameters( "groups", organizationId, "activities" ), payload( properties ) )
+ .execute().getEntity();
+ }
+
+
+ @Override
+ public ServiceResults getOrganizationActivity( OrganizationInfo organization ) throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+ return sm.newRequest( ServiceAction.GET, parameters( "groups", organization.getUuid(), "feed" ) ).execute();
+ }
+
+
+ @Override
+ public ServiceResults getOrganizationActivityForAdminUser( OrganizationInfo organization, UserInfo user )
+ throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+ return sm.newRequest( ServiceAction.GET,
+ parameters( "groups", organization.getUuid(), "users", user.getUuid(), "feed" ) ).execute();
+ }
+
+
+ @Override
+ public ServiceResults getAdminUserActivity( UserInfo user ) throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+ return sm.newRequest( ServiceAction.GET, parameters( "users", user.getUuid(), "feed" ) ).execute();
+ }
+
+
+ @Override
+ public OrganizationOwnerInfo createOwnerAndOrganization( String organizationName, String username, String name,
+ String email, String password ) throws Exception {
+
+ boolean activated = !newAdminUsersNeedSysAdminApproval() && !newOrganizationsNeedSysAdminApproval();
+ boolean disabled = newAdminUsersRequireConfirmation();
+ // if we are active and enabled, skip the send email step
+
+ return createOwnerAndOrganization( organizationName, username, name, email, password, activated, disabled, null,
+ null );
+ }
+
+
+ @Override
+ public OrganizationOwnerInfo createOwnerAndOrganization( String organizationName, String username, String name,
+ String email, String password, boolean activated,
+ boolean disabled ) throws Exception {
+ return createOwnerAndOrganization( organizationName, username, name, email, password, activated, disabled, null,
+ null );
+ }
+
+
+ @Override
+ public OrganizationOwnerInfo createOwnerAndOrganization( String organizationName, String username, String name,
+ String email, String password, boolean activated,
+ boolean disabled, Map<String, Object> userProperties,
+ Map<String, Object> organizationProperties )
+ throws Exception {
+
+ /**
+ * Only lock on the target values. We don't want lock contention if another
+ * node is trying to set the property do a different value
+ */
+ Lock groupLock =
+ getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, organizationName, "groups", "path" );
+
+ Lock userLock = getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, username, "users", "username" );
+
+ Lock emailLock = getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, email, "users", "email" );
+
+ UserInfo user = null;
+ OrganizationInfo organization = null;
+
+ try {
+
+ groupLock.lock();
+ userLock.lock();
+ emailLock.lock();
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ if ( !em.isPropertyValueUniqueForEntity( "group", "path", organizationName ) ) {
+ throw new DuplicateUniquePropertyExistsException( "group", "path", organizationName );
+ }
+ if ( !validateAdminInfo( username, name, email, password ) ) {
+ return null;
+ }
+ if ( areActivationChecksDisabled() ) {
+ user = createAdminUserInternal( username, name, email, password, true, false, userProperties );
+ }
+ else {
+ user = createAdminUserInternal( username, name, email, password, activated, disabled, userProperties );
+ }
+
+ organization = createOrganizationInternal( organizationName, user, true, organizationProperties );
+ }
+ finally {
+ emailLock.unlock();
+ userLock.unlock();
+ groupLock.unlock();
+ }
+
+ return new OrganizationOwnerInfo( user, organization );
+ }
+
+
+ private OrganizationInfo createOrganizationInternal( String organizationName, UserInfo user, boolean activated )
+ throws Exception {
+ return createOrganizationInternal( organizationName, user, activated, null );
+ }
+
+
+ private OrganizationInfo createOrganizationInternal( String organizationName, UserInfo user, boolean activated,
+ Map<String, Object> properties ) throws Exception {
+ if ( ( organizationName == null ) || ( user == null ) ) {
+ return null;
+ }
+ logger.info( "createOrganizationInternal: {}", organizationName );
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+
+ Group organizationEntity = new Group();
+ organizationEntity.setPath( organizationName );
+ organizationEntity = em.create( organizationEntity );
+
+ em.addToCollection( organizationEntity, "users", new SimpleEntityRef( User.ENTITY_TYPE, user.getUuid() ) );
+
+ writeUserToken( MANAGEMENT_APPLICATION_ID, organizationEntity, encryptionService
+ .plainTextCredentials( generateOAuthSecretKey( AuthPrincipalType.ORGANIZATION ), user.getUuid(),
+ MANAGEMENT_APPLICATION_ID ) );
+
+ OrganizationInfo organization =
+ new OrganizationInfo( organizationEntity.getUuid(), organizationName, properties );
+ updateOrganization( organization );
+
+ logger.info( "createOrganizationInternal: {}", organizationName );
+ postOrganizationActivity( organization.getUuid(), user, "create", organizationEntity, "Organization",
+ organization.getName(),
+ "<a href=\"mailto:" + user.getEmail() + "\">" + user.getName() + " (" + user.getEmail()
+ + ")</a> created a new organization account named " + organizationName, null );
+
+ startOrganizationActivationFlow( organization );
+
+ return organization;
+ }
+
+
+ @Override
+ public OrganizationInfo createOrganization( String organizationName, UserInfo user, boolean activated )
+ throws Exception {
+
+ if ( ( organizationName == null ) || ( user == null ) ) {
+ return null;
+ }
+ Lock groupLock =
+ getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, organizationName, "groups", "path" );
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ if ( !em.isPropertyValueUniqueForEntity( "group", "path", organizationName ) ) {
+ throw new DuplicateUniquePropertyExistsException( "group", "path", organizationName );
+ }
+ try {
+ groupLock.lock();
+ return createOrganizationInternal( organizationName, user, activated );
+ }
+ finally {
+ groupLock.unlock();
+ }
+ }
+
+
+ /** currently only affects properties */
+ public void updateOrganization( OrganizationInfo organizationInfo ) throws Exception {
+ Map<String, Object> properties = organizationInfo.getProperties();
+ if ( properties != null ) {
+ EntityRef organizationEntity = new SimpleEntityRef( organizationInfo.getUuid() );
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ for ( Map.Entry<String, Object> entry : properties.entrySet() ) {
+ if ( "".equals( entry.getValue() ) ) {
+ properties.remove( entry.getKey() );
+ em.removeFromDictionary( organizationEntity, ORGANIZATION_PROPERTIES_DICTIONARY, entry.getKey() );
+ }
+ else {
+ em.addToDictionary( organizationEntity, ORGANIZATION_PROPERTIES_DICTIONARY, entry.getKey(),
+ entry.getValue() );
+ }
+ }
+ }
+ }
+
+
+ @Override
+ public OrganizationInfo importOrganization( UUID organizationId, OrganizationInfo organizationInfo,
+ Map<String, Object> properties ) throws Exception {
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ if ( !em.isPropertyValueUniqueForEntity( "group", "path", organizationInfo.getName() ) ) {
+ throw new DuplicateUniquePropertyExistsException( "group", "path", organizationInfo.getName() );
+ }
+ if ( properties == null ) {
+ properties = new HashMap<String, Object>();
+ }
+
+ String organizationName = null;
+ if ( organizationInfo != null ) {
+ organizationName = organizationInfo.getName();
+ }
+ if ( organizationName == null ) {
+ organizationName = ( String ) properties.get( PROPERTY_PATH );
+ }
+ if ( organizationName == null ) {
+ organizationName = ( String ) properties.get( PROPERTY_NAME );
+ }
+ if ( organizationName == null ) {
+ return null;
+ }
+
+ if ( organizationId == null ) {
+ if ( organizationInfo != null ) {
+ organizationId = organizationInfo.getUuid();
+ }
+ }
+ if ( organizationId == null ) {
+ organizationId = uuid( properties.get( PROPERTY_UUID ) );
+ }
+ if ( organizationId == null ) {
+ return null;
+ }
+
+ properties.put( PROPERTY_PATH, organizationName );
+ properties.put( PROPERTY_SECRET, generateOAuthSecretKey( AuthPrincipalType.ORGANIZATION ) );
+ Entity organization = em.create( organizationId, Group.ENTITY_TYPE, properties );
+ // em.addToCollection(organization, "users", new SimpleEntityRef(
+ // User.ENTITY_TYPE, userId));
+ return new OrganizationInfo( organization.getUuid(), organizationName );
+ }
+
+
+ @Override
+ public UUID importApplication( UUID organizationId, Application application ) throws Exception {
+ // TODO organizationName
+ OrganizationInfo organization = getOrganizationByUuid( organizationId );
+ UUID applicationId =
+ emf.importApplication( organization.getName(), application.getUuid(), application.getName(),
+ application.getProperties() );
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ properties.setProperty( "name", buildAppName( application.getName(), organization ) );
+ Entity app = em.create( applicationId, APPLICATION_INFO, application.getProperties() );
+
+ writeUserToken( MANAGEMENT_APPLICATION_ID, app, encryptionService
+ .plainTextCredentials( generateOAuthSecretKey( AuthPrincipalType.APPLICATION ), null, applicationId ) );
+
+ addApplicationToOrganization( organizationId, applicationId );
+ return applicationId;
+ }
+
+
+ /**
+ * Test if the applicationName contains a '/' character, prepend with orgName if it does not, assume it is complete
+ * (and that organization is needed) if so.
+ */
+ private String buildAppName( String applicationName, OrganizationInfo organization ) {
+ return applicationName.contains( "/" ) ? applicationName : organization.getName() + "/" + applicationName;
+ }
+
+
+ @Override
+ public List<OrganizationInfo> getOrganizations( UUID startResult, int count ) throws Exception {
+ // still need the bimap to search for existing
+ BiMap<UUID, String> organizations = HashBiMap.create();
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Results results =
+ em.getCollection( em.getApplicationRef(), "groups", startResult, count, Level.ALL_PROPERTIES, false );
+ List<OrganizationInfo> orgs = new ArrayList<OrganizationInfo>( results.size() );
+ OrganizationInfo orgInfo;
+ for ( Entity entity : results.getEntities() ) {
+ // TODO T.N. temporary hack to deal with duplicate orgs. Revert this
+ // commit after migration
+ String path = ( String ) entity.getProperty( "path" );
+
+ if ( organizations.containsValue( path ) ) {
+ path += "DUPLICATE";
+ }
+ orgInfo = new OrganizationInfo( entity.getUuid(), path );
+ orgs.add( orgInfo );
+ organizations.put( entity.getUuid(), path );
+ }
+ return orgs;
+ }
+
+
+ @Override
+ public BiMap<UUID, String> getOrganizations() throws Exception {
+ List<OrganizationInfo> orgs = getOrganizations( null, 10000 );
+ return buildOrgBiMap( orgs );
+ }
+
+
+ private BiMap<UUID, String> buildOrgBiMap( List<OrganizationInfo> orgs ) {
+ BiMap<UUID, String> organizations = HashBiMap.create();
+ for ( OrganizationInfo orgInfo : orgs ) {
+ organizations.put( orgInfo.getUuid(), orgInfo.getName() );
+ }
+ return organizations;
+ }
+
+
+ @Override
+ public OrganizationInfo getOrganizationInfoFromAccessToken( String token ) throws Exception {
+ Entity entity = getEntityFromAccessToken( token, null, ORGANIZATION );
+ if ( entity == null ) {
+ return null;
+ }
+ return new OrganizationInfo( entity.getProperties() );
+ }
+
+
+ @Override
+ public OrganizationInfo getOrganizationByName( String organizationName ) throws Exception {
+
+ if ( organizationName == null ) {
+ return null;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ EntityRef ref = em.getAlias( "group", organizationName );
+ if ( ref == null ) {
+ return null;
+ }
+ return getOrganizationByUuid( ref.getUuid() );
+ }
+
+
+ @Override
+ public OrganizationInfo getOrganizationByUuid( UUID id ) throws Exception {
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Entity entity = em.get( new SimpleEntityRef( Group.ENTITY_TYPE, id ) );
+ if ( entity == null ) {
+ return null;
+ }
+ Map properties = em.getDictionaryAsMap( entity, ORGANIZATION_PROPERTIES_DICTIONARY );
+ OrganizationInfo orgInfo = new OrganizationInfo( entity.getProperties() );
+ orgInfo.setProperties( properties );
+ return orgInfo;
+ }
+
+
+ @Override
+ public OrganizationInfo getOrganizationByIdentifier( Identifier id ) throws Exception {
+ if ( id.isUUID() ) {
+ return getOrganizationByUuid( id.getUUID() );
+ }
+ if ( id.isName() ) {
+ return getOrganizationByName( id.getName() );
+ }
+ return null;
+ }
+
+
+ public void postUserActivity( UserInfo user, String verb, EntityRef object, String objectType, String objectName,
+ String title, String content ) throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+
+ Map<String, Object> properties = new HashMap<String, Object>();
+ properties.put( PROPERTY_VERB, verb );
+ properties.put( PROPERTY_CATEGORY, "admin" );
+ if ( content != null ) {
+ properties.put( PROPERTY_CONTENT, content );
+ }
+ if ( title != null ) {
+ properties.put( PROPERTY_TITLE, title );
+ }
+ properties.put( PROPERTY_ACTOR, user.getUuid() );
+ properties.put( PROPERTY_ACTOR_NAME, user.getName() );
+ properties.put( PROPERTY_OBJECT, object.getUuid() );
+ properties.put( PROPERTY_OBJECT_ENTITY_TYPE, object.getType() );
+ properties.put( PROPERTY_OBJECT_TYPE, objectType );
+ properties.put( PROPERTY_OBJECT_NAME, objectName );
+
+ sm.newRequest( ServiceAction.POST, parameters( "users", user.getUuid(), "activities" ), payload( properties ) )
+ .execute().getEntity();
+ }
+
+
+ @Override
+ public ServiceResults getAdminUserActivities( UserInfo user ) throws Exception {
+ ServiceManager sm = smf.getServiceManager( MANAGEMENT_APPLICATION_ID );
+ ServiceRequest request = sm.newRequest( ServiceAction.GET, parameters( "users", user.getUuid(), "feed" ) );
+ ServiceResults results = request.execute();
+ return results;
+ }
+
+
+ private UserInfo doCreateAdmin( User user, CredentialsInfo userPassword, CredentialsInfo mongoPassword )
+ throws Exception {
+
+ writeUserToken( MANAGEMENT_APPLICATION_ID, user, encryptionService
+ .plainTextCredentials( generateOAuthSecretKey( AuthPrincipalType.ADMIN_USER ), user.getUuid(),
+ MANAGEMENT_APPLICATION_ID ) );
+
+ writeUserPassword( MANAGEMENT_APPLICATION_ID, user, userPassword );
+
+ writeUserMongoPassword( MANAGEMENT_APPLICATION_ID, user, mongoPassword );
+
+ UserInfo userInfo = new UserInfo( MANAGEMENT_APPLICATION_ID, user.getUuid(), user.getUsername(), user.getName(),
+ user.getEmail(), user.getConfirmed(), user.getActivated(), user.getDisabled(),
+ user.getDynamicProperties() );
+
+ // special case for sysadmin and test account only
+ if ( !user.getEmail().equals( properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL ) ) && !user.getEmail()
+ .equals(
+ properties
+ .getProperty(
+ PROPERTIES_TEST_ACCOUNT_ADMIN_USER_EMAIL ) ) ) {
+ this.startAdminUserActivationFlow( userInfo );
+ }
+
+ return userInfo;
+ }
+
+
+ @Override
+ public UserInfo createAdminFromPrexistingPassword( User user, CredentialsInfo ci ) throws Exception {
+
+ return doCreateAdmin( user, ci,
+ // we can't actually set the mongo password. We never have the plain text in
+ // this path
+ encryptionService.plainTextCredentials( mongoPassword( user.getUsername(), "" ), user.getUuid(),
+ MANAGEMENT_APPLICATION_ID ) );
+ }
+
+
+ @Override
+ public UserInfo createAdminFrom( User user, String password ) throws Exception {
+ return doCreateAdmin( user,
+ encryptionService.defaultEncryptedCredentials( password, user.getUuid(), MANAGEMENT_APPLICATION_ID ),
+ encryptionService.plainTextCredentials( mongoPassword( user.getUsername(), password ), user.getUuid(),
+ MANAGEMENT_APPLICATION_ID ) );
+ }
+
+
+ @Override
+ public UserInfo createAdminUser( String username, String name, String email, String password, boolean activated,
+ boolean disabled ) throws Exception {
+ return createAdminUser( username, name, email, password, activated, disabled, null );
+ }
+
+
+ @Override
+ public UserInfo createAdminUser( String username, String name, String email, String password, boolean activated,
+ boolean disabled, Map<String, Object> userProperties ) throws Exception {
+ if ( !validateAdminInfo( username, name, email, password ) ) {
+ return null;
+ }
+ return createAdminUserInternal( username, name, email, password, activated, disabled, userProperties );
+ }
+
+
+ private boolean validateAdminInfo( String username, String name, String email, String password ) throws Exception {
+ if ( email == null ) {
+ return false;
+ }
+ if ( username == null ) {
+ username = email;
+ }
+ if ( name == null ) {
+ name = email;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+
+ if ( !em.isPropertyValueUniqueForEntity( "user", "username", username ) ) {
+ throw new DuplicateUniquePropertyExistsException( "user", "username", username );
+ }
+
+ if ( !em.isPropertyValueUniqueForEntity( "user", "email", email ) ) {
+ throw new DuplicateUniquePropertyExistsException( "user", "email", email );
+ }
+ return true;
+ }
+
+
+ private UserInfo createAdminUserInternal( String username, String name, String email, String password,
+ boolean activated, boolean disabled, Map<String, Object> userProperties )
+ throws Exception {
+ logger.info( "createAdminUserInternal: {}", username );
+
+ if ( isBlank( password ) ) {
+ password = encodeBase64URLSafeString( bytes( UUID.randomUUID() ) );
+ }
+ if ( username == null ) {
+ username = email;
+ }
+ if ( name == null ) {
+ name = email;
+ }
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ User user = new User();
+ user.setUsername( username );
+ user.setName( name );
+ user.setEmail( email );
+ user.setActivated( activated );
+ user.setConfirmed( !newAdminUsersRequireConfirmation() ); // only
+ user.setDisabled( disabled );
+ if ( userProperties != null ) {
+ // double check no 'password' property just to be safe
+ userProperties.remove( "password" );
+ user.setProperties( userProperties );
+ }
+ user = em.create( user );
+
+ return createAdminFrom( user, password );
+ }
+
+
+ public UserInfo getUserInfo( UUID applicationId, Entity entity ) {
+
+ if ( entity == null ) {
+ return null;
+ }
+ return new UserInfo( applicationId, entity.getUuid(), ( String ) entity.getProperty( "username" ),
+ entity.getName(), ( String ) entity.getProperty( "email" ),
+ ConversionUtils.getBoolean( entity.getProperty( "confirmed" ) ),
+ ConversionUtils.getBoolean( entity.getProperty( "activated" ) ),
+ ConversionUtils.getBoolean( entity.getProperty( "disabled" ) ), entity.getDynamicProperties() );
+ }
+
+
+ public UserInfo getUserInfo( UUID applicationId, Map<String, Object> properties ) {
+
+ if ( properties == null ) {
+ return null;
+ }
+ return new UserInfo( applicationId, properties );
+ }
+
+
+ @Override
+ public List<UserInfo> getAdminUsersForOrganization( UUID organizationId ) throws Exception {
+
+ if ( organizationId == null ) {
+ return null;
+ }
+
+ List<UserInfo> users = new ArrayList<UserInfo>();
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Results results =
+ em.getCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organizationId ), "users", null, 10000,
+ Level.ALL_PROPERTIES, false );
+ for ( Entity entity : results.getEntities() ) {
+ users.add( getUserInfo( MANAGEMENT_APPLICATION_ID, entity ) );
+ }
+
+ return users;
+ }
+
+
+ @Override
+ public UserInfo updateAdminUser( UserInfo user, String username, String name, String email,
+ Map<String, Object> json ) throws Exception {
+
+ /**
+ * Only lock on the target values. We don't want lock contention if another
+ * node is trying to set the property do a different value
+ */
+ Lock usernameLock =
+ getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, username, "users", "username" );
+
+ Lock emailLock = getUniqueUpdateLock( lockManager, MANAGEMENT_APPLICATION_ID, email, "users", "email" );
+
+ try {
+
+ usernameLock.lock();
+ emailLock.lock();
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+
+ SimpleEntityRef entityRef = new SimpleEntityRef( User.ENTITY_TYPE, user.getUuid() );
+ if ( !isBlank( username ) ) {
+ em.setProperty( entityRef, "username", username );
+ }
+ if ( !isBlank( name ) ) {
+ em.setProperty( entityRef, "name", name );
+ }
+ if ( !isBlank( email ) ) {
+ em.setProperty( entityRef, "email", email );
+ }
+ if ( json != null ) {
+ json.remove( "password" );
+ json.remove( "oldpassword" );
+ json.remove( "newpassword" );
+ Map<String, Object> userProperties = user.getProperties();
+ userProperties.putAll( json );
+ em.updateProperties( entityRef, userProperties );
+ }
+
+ user = getAdminUserByUuid( user.getUuid() );
+ }
+ finally {
+ emailLock.unlock();
+ usernameLock.unlock();
+ }
+
+ return user;
+ }
+
+
+ public User getAdminUserEntityByEmail( String email ) throws Exception {
+
+ if ( email == null ) {
+ return null;
+ }
+
+ return getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, Identifier.fromEmail( email ) );
+ }
+
+
+ @Override
+ public UserInfo getAdminUserByEmail( String email ) throws Exception {
+ if ( email == null ) {
+ return null;
+ }
+ return getUserInfo( MANAGEMENT_APPLICATION_ID,
+ getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, Identifier.fromEmail( email ) ) );
+ }
+
+
+ public User getUserEntityByIdentifier( UUID applicationId, Identifier indentifier ) throws Exception {
+ EntityManager em = emf.getEntityManager( applicationId );
+ return em.get( em.getUserByIdentifier( indentifier ), User.class );
+ }
+
+
+ @Override
+ public UserInfo getAdminUserByUsername( String username ) throws Exception {
+ if ( username == null ) {
+ return null;
+ }
+ return getUserInfo( MANAGEMENT_APPLICATION_ID,
+ getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, Identifier.fromName( username ) ) );
+ }
+
+
+ @Override
+ public User getAdminUserEntityByUuid( UUID id ) throws Exception {
+ if ( id == null ) {
+ return null;
+ }
+ return getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, Identifier.fromUUID( id ) );
+ }
+
+
+ @Override
+ public UserInfo getAdminUserByUuid( UUID id ) throws Exception {
+ return getUserInfo( MANAGEMENT_APPLICATION_ID,
+ getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, Identifier.fromUUID( id ) ) );
+ }
+
+
+ @Override
+ public User getAdminUserEntityByIdentifier( Identifier id ) throws Exception {
+ return getUserEntityByIdentifier( MANAGEMENT_APPLICATION_ID, id );
+ }
+
+
+ @Override
+ public UserInfo getAdminUserByIdentifier( Identifier id ) throws Exception {
+ if ( id.isUUID() ) {
+ return getAdminUserByUuid( id.getUUID() );
+ }
+ if ( id.isName() ) {
+ return getAdminUserByUsername( id.getName() );
+ }
+ if ( id.isEmail() ) {
+ return getAdminUserByEmail( id.getEmail() );
+ }
+ return null;
+ }
+
+
+ public User findUserEntity( UUID applicationId, String identifier ) {
+
+ User user = null;
+ if ( UUIDUtils.isUUID( identifier ) ) {
+ try {
+ Entity entity = getUserEntityByIdentifier( applicationId,
+ Identifier.fromUUID( UUID.fromString( identifier ) ) );
+ if ( entity != null ) {
+ user = ( User ) entity.toTypedEntity();
+ logger.info( "Found user {} as a UUID", identifier );
+ }
+ }
+ catch ( Exception e ) {
+ logger.warn( "Unable to get user " + identifier + " as a UUID, trying username..." );
+ }
+ return user;
+ }
+ // now we are either an email or a username. Let Indentifier handle the parsing of such.
+ Identifier id = Identifier.from( identifier );
+
+ try {
+ Entity entity = getUserEntityByIdentifier( applicationId, id );
+ if ( entity != null ) {
+ user = ( User ) entity.toTypedEntity();
+ logger.info( "Found user {} as an {}", identifier, id.getType() );
+ }
+ }
+ catch ( Exception e ) {
+ logger.warn( "Unable to get user {} as a {}", identifier, id.getType() );
+ }
+ if ( user != null ) {
+ return user;
+ }
+
+ return null;
+ }
+
+
+ @Override
+ public UserInfo findAdminUser( String identifier ) {
+ return getUserInfo( MANAGEMENT_APPLICATION_ID, findUserEntity( MANAGEMENT_APPLICATION_ID, identifier ) );
+ }
+
+
+ @Override
+ public void setAdminUserPassword( UUID userId, String oldPassword, String newPassword ) throws Exception {
+
+ if ( ( userId == null ) || ( oldPassword == null ) || ( newPassword == null ) ) {
+ return;
+ }
+ User user = emf.getEntityManager( MANAGEMENT_APPLICATION_ID ).get( userId, User.class );
+
+ if ( !verify( MANAGEMENT_APPLICATION_ID, user.getUuid(), oldPassword ) ) {
+ logger.info( "Old password doesn't match" );
+ throw new IncorrectPasswordException( "Old password does not match" );
+ }
+
+ setAdminUserPassword( userId, newPassword );
+ }
+
+
+ private static final String CREDENTIALS_HISTORY = "credentialsHistory";
+
+
+ @Override
+ public void setAdminUserPassword( UUID userId, String newPassword ) throws Exception {
+
+ if ( ( userId == null ) || ( newPassword == null ) ) {
+ return;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ User user = em.get( userId, User.class );
+
+ CredentialsInfo newCredentials =
+ encryptionService.defaultEncryptedCredentials( newPassword, user.getUuid(), MANAGEMENT_APPLICATION_ID );
+
+ int passwordHistorySize = calculatePasswordHistorySizeForUser( user.getUuid() );
+ Map<String, CredentialsInfo> credsMap = cast( em.getDictionaryAsMap( user, CREDENTIALS_HISTORY ) );
+
+ CredentialsInfo currentCredentials = null;
+ if ( passwordHistorySize > 0 ) {
+ ArrayList<CredentialsInfo> oldCreds = new ArrayList<CredentialsInfo>( credsMap.values() );
+ Collections.sort( oldCreds );
+
+ currentCredentials = readUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, user.getUuid() );
+
+ // check credential history
+ if ( encryptionService.verify( newPassword, currentCredentials, userId, MANAGEMENT_APPLICATION_ID ) ) {
+ throw new RecentlyUsedPasswordException();
+ }
+ for ( int i = 0; i < oldCreds.size() && i < passwordHistorySize; i++ ) {
+ CredentialsInfo ci = oldCreds.get( i );
+ if ( encryptionService.verify( newPassword, ci, userId, MANAGEMENT_APPLICATION_ID ) ) {
+ throw new RecentlyUsedPasswordException();
+ }
+ }
+ }
+
+ // remove excess history
+ if ( credsMap.size() > passwordHistorySize ) {
+ ArrayList<UUID> oldUUIDs = new ArrayList<UUID>( credsMap.size() );
+ for ( String uuid : credsMap.keySet() ) {
+ oldUUIDs.add( UUID.fromString( uuid ) );
+ }
+ UUIDUtils.sort( oldUUIDs );
+ for ( int i = 0; i < oldUUIDs.size() - passwordHistorySize; i++ ) {
+ em.removeFromDictionary( user, CREDENTIALS_HISTORY, oldUUIDs.get( i ).toString() );
+ }
+ }
+
+ if ( passwordHistorySize > 0 ) {
+ UUID uuid = UUIDUtils.newTimeUUID();
+ em.addToDictionary( user, CREDENTIALS_HISTORY, uuid.toString(), currentCredentials );
+ }
+
+ writeUserPassword( MANAGEMENT_APPLICATION_ID, user, newCredentials );
+ writeUserMongoPassword( MANAGEMENT_APPLICATION_ID, user, encryptionService
+ .plainTextCredentials( mongoPassword( ( String ) user.getProperty( "username" ), newPassword ),
+ user.getUuid(), MANAGEMENT_APPLICATION_ID ) );
+ }
+
+
+ public int calculatePasswordHistorySizeForUser( UUID userId ) throws Exception {
+
+ int size = 0;
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+
+ Results orgResults =
+ em.getCollection( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "groups", null, 10000, Level.REFS,
+ false );
+
+ for ( EntityRef orgRef : orgResults.getRefs() ) {
+ Map properties = em.getDictionaryAsMap( orgRef, ORGANIZATION_PROPERTIES_DICTIONARY );
+ if ( properties != null ) {
+ size = Math.max( new OrganizationInfo( null, null, properties ).getPasswordHistorySize(), size );
+ }
+ }
+
+ return size;
+ }
+
+
+ @Override
+ public boolean verifyAdminUserPassword( UUID userId, String password ) throws Exception {
+ if ( ( userId == null ) || ( password == null ) ) {
+ return false;
+ }
+ User user = emf.getEntityManager( MANAGEMENT_APPLICATION_ID ).get( userId, User.class );
+
+ return verify( MANAGEMENT_APPLICATION_ID, user.getUuid(), password );
+ }
+
+
+ @Override
+ public UserInfo verifyAdminUserPasswordCredentials( String name, String password ) throws Exception {
+ UserInfo userInfo = null;
+
+ User user = findUserEntity( MANAGEMENT_APPLICATION_ID, name );
+ if ( user == null ) {
+ return null;
+ }
+
+ if ( verify( MANAGEMENT_APPLICATION_ID, user.getUuid(), password ) ) {
+ userInfo = getUserInfo( MANAGEMENT_APPLICATION_ID, user );
+
- boolean userIsSuperAdmin = properties.getSuperUser().isEnabled() && properties.getSuperUser().getEmail().equals(userInfo.getEmail());
-
- boolean testUserEnabled = parseBoolean( properties.getProperty( PROPERTIES_SETUP_TEST_ACCOUNT ) );
++ boolean userIsSuperAdmin =
++ StringUtils.equals( getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL ), userInfo.getEmail() );
++ boolean testUserEnabled = getBooleanProperty( PROPERTIES_SETUP_TEST_ACCOUNT );
+
+ boolean userIsTestUser = !testUserEnabled ? false :
- properties.getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_EMAIL )
- .equals( userInfo.getEmail() );
++ StringUtils.equals(getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL ), userInfo.getEmail());
+
+ if ( !userIsSuperAdmin && !userIsTestUser ) {
+
+ if ( !userInfo.isConfirmed() && newAdminUsersRequireConfirmation() ) {
+ throw new UnconfirmedAdminUserException();
+ }
+ if ( !userInfo.isActivated() ) {
+ throw new UnactivatedAdminUserException();
+ }
+ if ( userInfo.isDisabled() ) {
+ throw new DisabledAdminUserException();
+ }
+ }
+ return userInfo;
+ }
+ logger.info( "password compare fail for {}", name );
+ return null;
+ }
+
+
+ @Override
+ public UserInfo verifyMongoCredentials( String name, String nonce, String key ) throws Exception {
+
+ Entity user = findUserEntity( MANAGEMENT_APPLICATION_ID, name );
+
+ if ( user == null ) {
+ return null;
+ }
+
+ String mongo_pwd = readUserMongoPassword( MANAGEMENT_APPLICATION_ID, user.getUuid() ).getSecret();
+
+ if ( mongo_pwd == null ) {
+ throw new IncorrectPasswordException( "Your mongo password has not be set" );
+ }
+
+ String expected_key = DigestUtils.md5Hex( nonce + user.getProperty( "username" ) + mongo_pwd );
+
+ if ( !expected_key.equalsIgnoreCase( key ) ) {
+ throw new IncorrectPasswordException();
+ }
+
+ UserInfo userInfo = new UserInfo( MANAGEMENT_APPLICATION_ID, user.getProperties() );
+
+ if ( !userInfo.isActivated() ) {
+ throw new UnactivatedAdminUserException();
+ }
+ if ( userInfo.isDisabled() ) {
+ throw new DisabledAdminUserException();
+ }
+
+ return userInfo;
+ }
+
+
+ // TokenType tokenType, String type, AuthPrincipalInfo principal,
+ // Map<String, Object> state
+ public String getTokenForPrincipal( TokenCategory token_category, String token_type, UUID applicationId,
+ AuthPrincipalType principal_type, UUID id, long duration ) throws Exception {
+
+ if ( anyNull( token_category, applicationId, principal_type, id ) ) {
+ return null;
+ }
+
+ return tokens
+ .createToken( token_category, token_type, new AuthPrincipalInfo( principal_type, id, applicationId ),
+ null, duration );
+ }
+
+
+ public void revokeTokensForPrincipal( AuthPrincipalType principalType, UUID applicationId, UUID id )
+ throws Exception {
+
+ if ( anyNull( applicationId, principalType, id ) ) {
+ throw new IllegalArgumentException( "applicationId, principal_type and id are required" );
+ }
+
+ AuthPrincipalInfo principal = new AuthPrincipalInfo( principalType, id, applicationId );
+
+ tokens.removeTokens( principal );
+ }
+
+
+ public AuthPrincipalInfo getPrincipalFromAccessToken( String token, String expected_token_type,
+ AuthPrincipalType expected_principal_type ) throws Exception {
+
+ TokenInfo tokenInfo = tokens.getTokenInfo( token );
+
+ if ( tokenInfo == null ) {
+ return null;
+ }
+
+ if ( ( expected_token_type != null ) && !expected_token_type.equals( tokenInfo.getType() ) ) {
+ return null;
+ }
+
+ AuthPrincipalInfo principal = tokenInfo.getPrincipal();
+ if ( principal == null ) {
+ return null;
+ }
+
+ if ( ( expected_principal_type != null ) && !expected_principal_type.equals( principal.getType() ) ) {
+ return null;
+ }
+
+ return principal;
+ }
+
+
+ public Entity getEntityFromAccessToken( String token, String expected_token_type,
+ AuthPrincipalType expected_principal_type ) throws Exception {
+
+ AuthPrincipalInfo principal =
+ getPrincipalFromAccessToken( token, expected_token_type, expected_principal_type );
+ if ( principal == null ) {
+ return null;
+ }
+
+ return getEntityFromPrincipal( principal );
+ }
+
+
+ public Entity getEntityFromPrincipal( AuthPrincipalInfo principal ) throws Exception {
+
+ EntityManager em = emf.getEntityManager(
+ principal.getApplicationId() != null ? principal.getApplicationId() : MANAGEMENT_APPLICATION_ID );
+ Entity entity = em.get( principal.getUuid() );
+ return entity;
+ }
+
+
+ @Override
+ public String getAccessTokenForAdminUser( UUID userId, long duration ) throws Exception {
+
+ return getTokenForPrincipal( ACCESS, null, MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, duration );
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.apache.usergrid.management.ManagementService#revokeAccessTokensForAdminUser
+ * (java.util.UUID)
+ */
+ @Override
+ public void revokeAccessTokensForAdminUser( UUID userId ) throws Exception {
+ revokeTokensForPrincipal( ADMIN_USER, MANAGEMENT_APPLICATION_ID, userId );
+ }
+
+
+ @Override
+ public void revokeAccessTokenForAdminUser( UUID userId, String token ) throws Exception {
+ if ( anyNull( userId, token ) ) {
+ throw new IllegalArgumentException( "token is required" );
+ }
+
+ Entity user = getAdminUserEntityFromAccessToken( token );
+ if ( !user.getUuid().equals( userId ) ) {
+ throw new TokenException( "Could not match token : " + token );
+ }
+
+ tokens.revokeToken( token );
+ }
+
+
+ @Override
+ public Entity getAdminUserEntityFromAccessToken( String token ) throws Exception {
+
+ Entity user = getEntityFromAccessToken( token, null, ADMIN_USER );
+ return user;
+ }
+
+
+ @Override
+ public UserInfo getAdminUserInfoFromAccessToken( String token ) throws Exception {
+ Entity user = getAdminUserEntityFromAccessToken( token );
+ return new UserInfo( MANAGEMENT_APPLICATION_ID, user.getProperties() );
+ }
+
+
+ @Override
+ public BiMap<UUID, String> getOrganizationsForAdminUser( UUID userId ) throws Exception {
+
+ if ( userId == null ) {
+ return null;
+ }
+
+ BiMap<UUID, String> organizations = HashBiMap.create();
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Results results = em.getCollection( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "groups", null, 10000,
+ Level.ALL_PROPERTIES, false );
+
+ String path = null;
+
+ for ( Entity entity : results.getEntities() ) {
+
+ path = ( String ) entity.getProperty( "path" );
+
+ if ( path != null ) {
+ path = path.toLowerCase();
+ }
+
+ organizations.put( entity.getUuid(), path );
+ }
+
+ return organizations;
+ }
+
+
+ @Override
+ public Map<String, Object> getAdminUserOrganizationData( UUID userId ) throws Exception {
+ UserInfo user = getAdminUserByUuid( userId );
+ return getAdminUserOrganizationData( user, true );
+ }
+
+
+ @Override
+ public Long getLastAdminPasswordChange( UUID userId ) throws Exception {
+ CredentialsInfo ci = readUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, userId );
+ return ci.getCreated();
+ }
+
+
+ @Override
+ public Map<String, Object> getAdminUserOrganizationData( UserInfo user, boolean deep ) throws Exception {
+
+ Map<String, Object> json = new HashMap<String, Object>();
+
+ json.putAll( JsonUtils.toJsonMap( user ) );
+
+ Map<String, Map<String, Object>> jsonOrganizations = new HashMap<String, Map<String, Object>>();
+ json.put( "organizations", jsonOrganizations );
+
+ Map<UUID, String> organizations;
+
- AccountCreationProps.SuperUser superUser = properties.getSuperUser();
- if ( superUser.isEnabled() && superUser.getUsername().equals( user.getUsername() ) ) {
++ boolean superuser_enabled = getBooleanProperty( PROPERTIES_SYSADMIN_LOGIN_ALLOWED );
++ String superuser_username = properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_NAME );
++ if ( superuser_enabled && ( superuser_username != null ) && superuser_username.equals( user.getUsername() ) ) {
+ organizations = buildOrgBiMap( getOrganizations( null, 10 ) );
+ }
+ else {
+ organizations = getOrganizationsForAdminUser( user.getUuid() );
+ }
+
+ for ( Entry<UUID, String> organization : organizations.entrySet() ) {
+ Map<String, Object> jsonOrganization = new HashMap<String, Object>();
+
+ jsonOrganizations.put( organization.getValue(), jsonOrganization );
+
+ jsonOrganization.put( PROPERTY_NAME, organization.getValue() );
+ jsonOrganization.put( PROPERTY_UUID, organization.getKey() );
+ jsonOrganization.put( "properties", getOrganizationByUuid( organization.getKey() ).getProperties() );
+
+ if ( deep ) {
+ BiMap<UUID, String> applications = getApplicationsForOrganization( organization.getKey() );
+ jsonOrganization.put( "applications", applications.inverse() );
+
+ List<UserInfo> users = getAdminUsersForOrganization( organization.getKey() );
+ Map<String, Object> jsonUsers = new HashMap<String, Object>();
+ for ( UserInfo u : users ) {
+ jsonUsers.put( u.getUsername(), u );
+ }
+ jsonOrganization.put( "users", jsonUsers );
+ }
+ }
+
+ return json;
+ }
+
+
+ @Override
+ public Map<String, Object> getOrganizationData( OrganizationInfo organization ) throws Exception {
+
+ Map<String, Object> jsonOrganization = new HashMap<String, Object>();
+ jsonOrganization.putAll( JsonUtils.toJsonMap( organization ) );
+
+ BiMap<UUID, String> applications = getApplicationsForOrganization( organization.getUuid() );
+ jsonOrganization.put( "applications", applications.inverse() );
+
+ List<UserInfo> users = getAdminUsersForOrganization( organization.getUuid() );
+ Map<String, Object> jsonUsers = new HashMap<String, Object>();
+ for ( UserInfo u : users ) {
+ jsonUsers.put( u.getUsername(), u );
+ }
+ jsonOrganization.put( "users", jsonUsers );
+
+ return jsonOrganization;
+ }
+
+
+ @Override
+ public void addAdminUserToOrganization( UserInfo user, OrganizationInfo organization, boolean email )
+ throws Exception {
+
+ if ( ( user == null ) || ( organization == null ) ) {
+ return;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.addToCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organization.getUuid() ), "users",
+ new SimpleEntityRef( User.ENTITY_TYPE, user.getUuid() ) );
+
+ if ( email ) {
+ sendAdminUserInvitedEmail( user, organization );
+ }
+ }
+
+
+ @Override
+ public void removeAdminUserFromOrganization( UUID userId, UUID organizationId ) throws Exception {
+
+ if ( ( userId == null ) || ( organizationId == null ) ) {
+ return;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+
+ try {
+ if ( em.getCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organizationId ), "users", null, 2,
+ Level.IDS, false ).size() <= 1 ) {
+ throw new Exception();
+ }
+ }
+ catch ( Exception e ) {
+ throw new UnableToLeaveOrganizationException( "Organizations must have at least one member." );
+ }
+
+ em.removeFromCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organizationId ), "users",
+ new SimpleEntityRef( User.ENTITY_TYPE, userId ) );
+ }
+
+
+ @Override
+ public ApplicationInfo createApplication( UUID organizationId, String applicationName ) throws Exception {
+
+ return createApplication( organizationId, applicationName, null );
+ }
+
+
+ @Override
+ public ApplicationInfo createApplication( UUID organizationId, String applicationName,
+ Map<String, Object> properties ) throws Exception {
+
+ if ( ( organizationId == null ) || ( applicationName == null ) ) {
+ return null;
+ }
+
+ if ( properties == null ) {
+ properties = new HashMap<String, Object>();
+ }
+
+ OrganizationInfo organizationInfo = getOrganizationByUuid( organizationId );
+
+ UUID applicationId = emf.createApplication( organizationInfo.getName(), applicationName, properties );
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ properties.put( "name", buildAppName( applicationName, organizationInfo ) );
+ Entity applicationEntity = em.create( applicationId, APPLICATION_INFO, properties );
+
+ writeUserToken( MANAGEMENT_APPLICATION_ID, applicationEntity, encryptionService
+ .plainTextCredentials( generateOAuthSecretKey( AuthPrincipalType.APPLICATION ), null,
+ MANAGEMENT_APPLICATION_ID ) );
+ addApplicationToOrganization( organizationId, applicationId );
+
+ UserInfo user = null;
+ // if we call this method before the full stack is initialized
+ // we'll get an exception
+ try {
+ user = SubjectUtils.getUser();
+ }
+ catch ( UnavailableSecurityManagerException e ) {
+ }
+ if ( ( user != null ) && user.isAdminUser() ) {
+ postOrganizationActivity( organizationId, user, "create", applicationEntity, "Application", applicationName,
+ "<a href=\"mailto:" + user.getEmail() + "\">" + user.getName() + " (" + user.getEmail()
+ + ")</a> created a new application named " + applicationName, null );
+ }
+ return new ApplicationInfo( applicationId, applicationEntity.getName() );
+ }
+
+
+ @Override
+ public OrganizationInfo getOrganizationForApplication( UUID applicationId ) throws Exception {
+
+ if ( applicationId == null ) {
+ return null;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Results r = em.getConnectingEntities( applicationId, "owns", "group", Level.ALL_PROPERTIES );
+ Entity entity = r.getEntity();
+ if ( entity != null ) {
+ return new OrganizationInfo( entity.getUuid(), ( String ) entity.getProperty( "path" ) );
+ }
+
+ return null;
+ }
+
+
+ @Override
+ public BiMap<UUID, String> getApplicationsForOrganization( UUID organizationId ) throws Exception {
+
+ if ( organizationId == null ) {
+ return null;
+ }
+ BiMap<UUID, String> applications = HashBiMap.create();
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Results results = em.getConnectedEntities( organizationId, "owns", APPLICATION_INFO, Level.ALL_PROPERTIES );
+ if ( !results.isEmpty() ) {
+
+ String entityName = null;
+
+ for ( Entity entity : results.getEntities() ) {
+ entityName = entity.getName();
+
+ if ( entityName != null ) {
+ entityName = entityName.toLowerCase();
+ }
+
+ applications.put( entity.getUuid(), entityName );
+ }
+ }
+
+ return applications;
+ }
+
+
+ @Override
+ public BiMap<UUID, String> getApplicationsForOrganizations( Set<UUID> organizationIds ) throws Exception {
+ if ( organizationIds == null ) {
+ return null;
+ }
+ BiMap<UUID, String> applications = HashBiMap.create();
+ for ( UUID organizationId : organizationIds ) {
+ BiMap<UUID, String> organizationApplications = getApplicationsForOrganization( organizationId );
+ applications.putAll( organizationApplications );
+ }
+ return applications;
+ }
+
+
+ @Override
+ public UUID addApplicationToOrganization( UUID organizationId, UUID applicationId ) throws Exception {
+
+ if ( ( organizationId == null ) || ( applicationId == null ) ) {
+ return null;
+ }
+
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.createConnection( new SimpleEntityRef( "group", organizationId ), "owns",
+ new SimpleEntityRef( APPLICATION_INFO, applicationId ) );
+
+ return applicationId;
+ }
+
+
+ @Override
+ public void deleteOrganizationApplication( UUID organizationId, UUID applicationId ) throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+
+ @Override
+ public void removeOrganizationApplication( UUID organizationId, UUID applicationId ) throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+
+ @Override
+ public ApplicationInfo getApplicationInfo( String applicationName ) throws Exception {
+ if ( applicationName == null ) {
+ return null;
+ }
+ UUID applicationId = emf.lookupApplication( applicationName );
+ if ( applicationId == null ) {
+ return null;
+ }
+ return new ApplicationInfo( applicationId, applicationName.toLowerCase() );
+ }
+
+
+ @Override
+ public ApplicationInfo getApplicationInfo( UUID applicationId ) throws Exception {
+ if ( applicationId == null ) {
+ return null;
+ }
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ Entity entity = em.get( applicationId );
+
+ if ( entity != null ) {
+ return new ApplicationInfo( applicationId, entity.getName() );
+ }
+ return null;
+ }
+
+
+ @Override
+ public ApplicationInfo getApplicationInfo( Identifier id ) throws Exception {
+ if ( id == null ) {
+ return null;
+ }
+ if ( id.isUUID() ) {
+ return getApplicationInfo( id.getUUID() );
+ }
+ if ( id.isName() ) {
+ return getApplicationInfo( id.getName() );
+ }
+ return null;
+ }
+
+
+ @Override
+ public ApplicationInfo getApplicationInfoFromAccessToken( String token ) throws Exception {
+ Entity entity = getEntityFromAccessToken( token, null, APPLICATION );
+ if ( entity == null ) {
+ throw new TokenException( "Could not find an entity for that access token: " + token );
+ }
+ return new ApplicationInfo( entity.getProperties() );
+ }
+
+
+ @Override
+ public ServiceResults getApplicationMetadata( UUID applicationId ) throws Exception {
+
+ if ( applicationId == null ) {
+ return ServiceResults.genericServiceResults();
+ }
+
+ EntityManager em = emf.getEntityManager( applicationId );
+ Entity entity = em.get( em.getApplicationRef() );
+
+ Results r = Results.fromEntity( entity );
+
+ Map<String, Object> collections = em.getApplicationCollectionMetadata();
+ if ( collections.size() > 0 ) {
+ r.setMetadata( em.getApplicationRef().getUuid(), "collections", collections );
+ }
+ return genericServiceResults( r );
+ }
+
+
+ public String getSecret( UUID applicationId, AuthPrincipalType type, UUID id ) throws Exception {
+ if ( AuthPrincipalType.ORGANIZATION.equals( type ) || AuthPrincipalType.APPLICATION.equals( type ) ) {
+ UUID ownerId =
+ AuthPrincipalType.APPLICATION_USER.equals( type ) ? applicationId : MANAGEMENT_APPLICATION_ID;
+
+ return getCredentialsSecret( readUserToken( ownerId, id ) );
+ }
+ else if ( AuthPrincipalType.ADMIN_USER.equals( type ) || AuthPrincipalType.APPLICATION_USER.equals( type ) ) {
+ return getCredentialsSecret( readUserPasswordCredentials( applicationId, id ) );
+ }
+ throw new IllegalArgumentException( "Must specify an admin user, organization or application principal" );
+ }
+
+
+ @Override
+ public String getClientIdForOrganization( UUID organizationId ) {
+ return ClientCredentialsInfo.getClientIdForTypeAndUuid( AuthPrincipalType.ORGANIZATION, organizationId );
+ }
+
+
+ @Override
+ public String getClientSecretForOrganization( UUID organizationId ) throws Exception {
+ return getSecret( MANAGEMENT_APPLICATION_ID, AuthPrincipalType.ORGANIZATION, organizationId );
+ }
+
+
+ @Override
+ public String getClientIdForApplication( UUID applicationId ) {
+ return ClientCredentialsInfo.getClientIdForTypeAndUuid( AuthPrincipalType.APPLICATION, applicationId );
+ }
+
+
+ @Override
+ public String getClientSecretForApplication( UUID applicationId ) throws Exception {
+ return getSecret( MANAGEMENT_APPLICATION_ID, AuthPrincipalType.APPLICATION, applicationId );
+ }
+
+
+ public String newSecretKey( AuthPrincipalType type, UUID id ) throws Exception {
+ String secret = generateOAuthSecretKey( type );
+
+ writeUserToken( MANAGEMENT_APPLICATION_ID, new SimpleEntityRef( type.getEntityType(), id ),
+ encryptionService.plainTextCredentials( secret, id, MANAGEMENT_APPLICATION_ID ) );
+
+ return secret;
+ }
+
+
+ @Override
+ public String newClientSecretForOrganization( UUID organizationId ) throws Exception {
+ return newSecretKey( AuthPrincipalType.ORGANIZATION, organizationId );
+ }
+
+
+ @Override
+ public String newClientSecretForApplication( UUID applicationId ) throws Exception {
+ return newSecretKey( AuthPrincipalType.APPLICATION, applicationId );
+ }
+
+
+ @Override
+ public AccessInfo authorizeClient( String clientId, String clientSecret, long ttl ) throws Exception {
+ if ( ( clientId == null ) || ( clientSecret == null ) ) {
+ return null;
+ }
+ UUID uuid = getUUIDFromClientId( clientId );
+ if ( uuid == null ) {
+ return null;
+ }
+ AuthPrincipalType type = getTypeFromClientId( clientId );
+ if ( type == null ) {
+ return null;
+ }
+ AccessInfo access_info = null;
+ if ( clientSecret.equals( getSecret( MANAGEMENT_APPLICATION_ID, type, uuid ) ) ) {
+
+ String token = getTokenForPrincipal( ACCESS, null, MANAGEMENT_APPLICATION_ID, type, uuid, ttl );
+
+ long duration = tokens.getMaxTokenAgeInSeconds( token );
+
+ access_info = new AccessInfo().withExpiresIn( duration ).withAccessToken( token );
+
+ if ( type.equals( AuthPrincipalType.APPLICATION ) ) {
+ ApplicationInfo app = getApplicationInfo( uuid );
+ access_info = access_info.withProperty( "application", app.getId() );
+ }
+ else if ( type.equals( AuthPrincipalType.ORGANIZATION ) ) {
+ OrganizationInfo organization = getOrganizationByUuid( uuid );
+ access_info = access_info.withProperty( "organization", getOrganizationData( organization ) );
+ }
+ }
+ return access_info;
+ }
+
+
+ @Override
+ public PrincipalCredentialsToken getPrincipalCredentialsTokenForClientCredentials( String clientId,
+ String clientSecret )
+ throws Exception {
+ if ( ( clientId == null ) || ( clientSecret == null ) ) {
+ return null;
+ }
+ UUID uuid = getUUIDFromClientId( clientId );
+ if ( uuid == null ) {
+ return null;
+ }
+ AuthPrincipalType type = getTypeFromClientId( clientId );
+ if ( type == null ) {
+ return null;
+ }
+ PrincipalCredentialsToken token = null;
+ if ( clientSecret.equals( getSecret( MANAGEMENT_APPLICATION_ID, type, uuid ) ) ) {
+ if ( type.equals( AuthPrincipalType.APPLICATION ) ) {
+ ApplicationInfo app = getApplicationInfo( uuid );
+ token = new PrincipalCredentialsToken( new ApplicationPrincipal( app ),
+ new ApplicationClientCredentials( clientId, clientSecret ) );
+ }
+ else if ( type.equals( AuthPrincipalType.ORGANIZATION ) ) {
+ OrganizationInfo organization = getOrganizationByUuid( uuid );
+ token = new PrincipalCredentialsToken( new OrganizationPrincipal( organization ),
+ new OrganizationClientCredentials( clientId, clientSecret ) );
+ }
+ }
+ return token;
+ }
+
+
+ public AccessInfo authorizeAppUser( String clientType, String clientId, String clientSecret ) throws Exception {
+
+ return null;
+ }
+
+
+ @Override
+ public String getPasswordResetTokenForAdminUser( UUID userId, long ttl ) throws Exception {
+ return getTokenForPrincipal( EMAIL, TOKEN_TYPE_PASSWORD_RESET, MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId,
+ ttl );
+ }
+
+
+ @Override
+ public boolean checkPasswordResetTokenForAdminUser( UUID userId, String token ) throws Exception {
+ AuthPrincipalInfo principal = null;
+ try {
+ principal = getPrincipalFromAccessToken( token, TOKEN_TYPE_PASSWORD_RESET, ADMIN_USER );
+ }
+ catch ( Exception e ) {
+ logger.error( "Unable to verify token", e );
+ }
+ return ( principal != null ) && userId.equals( principal.getUuid() );
+ }
+
+
+ @Override
+ public String getActivationTokenForAdminUser( UUID userId, long ttl ) throws Exception {
+ return getTokenForPrincipal( EMAIL, TOKEN_TYPE_ACTIVATION, MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, ttl );
+ }
+
+
+ @Override
+ public String getConfirmationTokenForAdminUser( UUID userId, long ttl ) throws Exception {
+ return getTokenForPrincipal( EMAIL, TOKEN_TYPE_CONFIRM, MANAGEMENT_APPLICATION_ID, ADMIN_USER, userId, ttl );
+ }
+
+
+ @Override
+ public void activateAdminUser( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.setProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "activated", true );
+ }
+
+
+ @Override
+ public User deactivateUser( UUID applicationId, UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( applicationId );
+
+ User user = em.get( userId, User.class );
+
+ if ( user == null ) {
+ throw new ManagementException(
+ String.format( "User with id %s does not exist in app %s", userId, applicationId ) );
+ }
+
+ user.setActivated( false );
+ user.setDeactivated( System.currentTimeMillis() );
+
+ em.update( user );
+
+ // revoke all access tokens for the app
+ revokeAccessTokensForAppUser( applicationId, userId );
+
+ return user;
+ }
+
+
+ @Override
+ public boolean isAdminUserActivated( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ return Boolean.TRUE.equals( em.getProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "activated" ) );
+ }
+
+
+ @Override
+ public void confirmAdminUser( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.setProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "confirmed", true );
+ }
+
+
+ @Override
+ public void unconfirmAdminUser( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.setProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "confirmed", false );
+ }
+
+
+ @Override
+ public boolean isAdminUserConfirmed( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ return Boolean.TRUE.equals( em.getProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "confirmed" ) );
+ }
+
+
+ @Override
+ public void enableAdminUser( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.setProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "disabled", false );
+ }
+
+
+ @Override
+ public void disableAdminUser( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ em.setProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "disabled", true );
+
+ revokeAccessTokensForAdminUser( userId );
+ }
+
+
+ @Override
+ public boolean isAdminUserEnabled( UUID userId ) throws Exception {
+ EntityManager em = emf.getEntityManager( MANAGEMENT_APPLICATION_ID );
+ return !Boolean.TRUE.equals( em.getProperty( new SimpleEntityRef( User.ENTITY_TYPE, userId ), "disabled" ) );
+ }
+
+
+ privat
<TRUNCATED>
[13/50] [abbrv] git commit: Fixed issues with
Usergrid.Client.prototype.createGroup. Added more tests
Posted by sn...@apache.org.
Fixed issues with Usergrid.Client.prototype.createGroup. Added more tests
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/49783334
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/49783334
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/49783334
Branch: refs/heads/optimistic-tx-semantics
Commit: 49783334d2886fa4f42eccf0bc126986b5ddab99
Parents: e104c3e
Author: ryan bridges <rb...@apigee.com>
Authored: Mon Feb 10 19:16:21 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Mon Feb 10 19:16:21 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/Gruntfile.js | 6 +-
sdks/html5-javascript/lib/Usergrid.js | 6 +-
sdks/html5-javascript/lib/modules/Client.js | 10 +---
sdks/html5-javascript/tests/mocha/test.js | 71 ++++++++++++++++++++++--
sdks/html5-javascript/usergrid.js | 19 ++-----
sdks/html5-javascript/usergrid.min.js | 2 +-
6 files changed, 82 insertions(+), 32 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/sdks/html5-javascript/Gruntfile.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/Gruntfile.js b/sdks/html5-javascript/Gruntfile.js
index 527633d..cfa39e3 100644
--- a/sdks/html5-javascript/Gruntfile.js
+++ b/sdks/html5-javascript/Gruntfile.js
@@ -68,8 +68,8 @@ module.exports = function(grunt) {
"tasks": ["default"]
},
"blanket_mocha": {
- "all": tests,
- //urls: [ 'http://localhost:8000/tests/mocha/index.html' ],
+ //"all": tests,
+ urls: [ 'http://localhost:8000/tests/mocha/index.html' ],
"options": {
"dest": "report/coverage.html",
"reporter": "Spec",
@@ -92,6 +92,6 @@ module.exports = function(grunt) {
]);
grunt.registerTask("test", [
"connect:test",
- "blanket_mocha",
+ "blanket_mocha"
]);
};
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index ec10de1..3fca37a 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -138,13 +138,13 @@ function doCallback(callback, params, context) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- try {
+ //try {
returnValue = callback.apply(context, params);
- } catch (ex) {
+ /*} catch (ex) {
if (console && console.error) {
console.error("Callback error:", ex);
}
- }
+ }*/
}
return returnValue;
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/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
index 88ff623..4efae5a 100644
--- a/sdks/html5-javascript/lib/modules/Client.js
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -132,17 +132,13 @@
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);
+ var okToSave = (err && ['service_resource_not_found','no_name_specified','null_pointer'].indexOf(err.name)!==-1) || (!err && getOnExist);
if (okToSave) {
group.save(function(err, data){
- if (typeof(callback) === 'function') {
- callback(err, group);
- }
+ doCallback(callback, [err, group, data]);
});
} else {
- if(typeof(callback) === 'function') {
- callback(err, group);
- }
+ doCallback(callback, [null, group, data]);
}
});
};
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index 2ecf944..8bcd19a 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -267,24 +267,81 @@ describe('Usergrid Client', function() {
});
describe('Usergrid convenience methods', function(){
it('createEntity',function(done){
- done();
+ client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, dog){
+ assert(!err, "createEntity returned an error")
+ assert(dog, "createEntity did not return a dog")
+ assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'")
+ done();
+ })
})
- it('createCollection',function(done){
- done();
+ it('createEntity - existing entity',function(done){
+ client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, dog){
+ assert(!err, "createEntity returned an error")
+ assert(dog, "createEntity did not return a dog")
+ assert(dog.get("name")==='createEntityTestDog', "The dog's name is not 'createEntityTestDog'")
+ done();
+ })
})
+ it('createEntity - get on Exist',function(done){
+ client.createEntity({type:'dog',name:'createEntityTestDog', getOnExist:true}, function(err, dog){
+ assert(!err, "createEntity returned an error")
+ assert(dog, "createEntity did not return a dog")
+ assert(dog.get("uuid")!==null, "The dog's UUID was not returned")
+ done();
+ })
+ })
+ var testGroup;
it('createGroup',function(done){
+ client.createGroup({path:'dogLovers'},function(err, group){
+ assert(!err, "createGroup returned an error: "+err);
+ assert(group, "createGroup did not return a group");
+ assert(group instanceof Usergrid.Group, "createGroup did not return a Usergrid.Group");
+ testGroup=group;
+ done();
+ })
done();
})
it('buildAssetURL',function(done){
+ var assetURL='https://api.usergrid.com/yourorgname/sandbox/assets/00000000-0000-0000-000000000000/data';
+ assert(assetURL===client.buildAssetURL('00000000-0000-0000-000000000000'), "buildAssetURL doesn't work")
done();
})
+ var dogEntity;
it('getEntity',function(done){
- done();
+ client.getEntity({type:'dog',name:'createEntityTestDog'}, function(err, dog){
+ assert(!err, "createEntity returned an error")
+ assert(dog, "createEntity returned a dog")
+ assert(dog.get("uuid")!==null, "The dog's UUID was not returned")
+ dogEntity=dog;
+ done();
+ })
})
it('restoreEntity',function(done){
+ var serializedDog=dogEntity.serialize();
+ var dog=client.restoreEntity(serializedDog);
+ assert(dog, "restoreEntity did not return a dog")
+ assert(dog.get("uuid")===dogEntity.get("uuid"), "The dog's UUID was not the same as the serialized dog")
+ assert(dog.get("type")===dogEntity.get("type"), "The dog's type was not the same as the serialized dog")
+ assert(dog.get("name")===dogEntity.get("name"), "The dog's name was not the same as the serialized dog")
+
done();
})
+ var dogCollection;
+ it('createCollection',function(done){
+ client.createCollection({type:'dogs'},function(err, dogs){
+ assert(!err, "createCollection returned an error");
+ assert(dogs, "createCollection did not return a dogs collection");
+ dogCollection=dogs;
+ done();
+ })
+ })
it('restoreCollection',function(done){
+ var serializedDogs=dogCollection.serialize();
+ var dogs=client.restoreCollection(serializedDogs);
+ console.warn('restoreCollection',dogs, dogCollection);
+ assert(dogs._type===dogCollection._type, "The dog collection type was not the same as the serialized dog collection")
+ assert(dogs._qs==dogCollection._qs, "The query strings do not match")
+ assert(dogs._list.length===dogCollection._list.length, "The collections have a different number of entities")
done();
})
it('getFeedForUser',function(done){
@@ -344,6 +401,12 @@ describe('Usergrid Client', function() {
it('getDisplayImage',function(done){
done();
})
+ after(function(done){
+ dogEntity.destroy();
+ //dogCollection.destroy();
+ //testGroup.destroy();
+ done();
+ })
});
describe('Usergrid Entity', function() {
var dog;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 38a8011..093e847 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -497,13 +497,8 @@ function doCallback(callback, params, context) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- try {
- returnValue = callback.apply(context, params);
- } catch (ex) {
- if (console && console.error) {
- console.error("Callback error:", ex);
- }
- }
+ //try {
+ returnValue = callback.apply(context, params);
}
return returnValue;
}
@@ -738,17 +733,13 @@ function doCallback(callback, params, context) {
};
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;
+ var okToSave = err && [ "service_resource_not_found", "no_name_specified", "null_pointer" ].indexOf(err.name) !== -1 || !err && getOnExist;
if (okToSave) {
group.save(function(err, data) {
- if (typeof callback === "function") {
- callback(err, group);
- }
+ doCallback(callback, [ err, group, data ]);
});
} else {
- if (typeof callback === "function") {
- callback(err, group);
- }
+ doCallback(callback, [ null, group, data ]);
}
});
};
[10/50] [abbrv] removed unused functions from Usergrid.Request.
stubbed out the remaining test cases for Usergrid.Client
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/e104c3e9/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index 2ea1a53..eb8fafa 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-10 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;if(isFunction(callback)){params||(params=[]),context||(context=this),params.push(context);try{returnValue=callback.apply(context,params)}catch(ex){console&&console.error&&console.error("Callback error:",ex)}}return returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventabl
e.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.ini
t(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&c
onsole[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new
Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)})
,p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-T
ype","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStora
ge' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token
){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DEL
ETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Request.prototype.validate=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.prepare=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Request.prototype.fire=function(){var p=new Promise;return p.done(null,this),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),
p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET
",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodePara
ms(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entit
y.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callba
ck){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){retu
rn 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=fun
ction(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applica
tions={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Us
ergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof thi
s.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrit
tenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[
field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===EN
TITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connect
ion,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):enti
ty.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"
/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client
.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"functio
n"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_p
art.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELE
TE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(da
ta.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++
-}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(
var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy ent
ity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;retu
rn hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNex
tPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback
&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(e
rror,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80
}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof c
allback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start)switch(typeof start){case"undefined":start_time=0;break;case"number":start_time=start;break;case"string":start_time=isNa
N(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,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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._
data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if
("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&
&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){
err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._clien
t.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new U
sergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timesta
mp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.U
sergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;if(isFunction(callback)){params||(params=[]),context||(context=this),params.push(context);try{returnValue=callback.apply(context,params)}catch(ex){console&&console.error&&console.error("Callback error:",ex)}}return returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventabl
e.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.ini
t(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&c
onsole[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new
Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)})
,p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-T
ype","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStora
ge' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token
){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DEL
ETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logge
r.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]
=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_
specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.En
tity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callba
ck){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),th
is.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),loc
alStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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 tryi
ng to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.pu
sh(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergri
d.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridEr
ror("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();enti
ty&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error)
,callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"
/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Use
rgrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].
picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,
data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==
typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._c
lient=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var
collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
+user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=func
tion(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._p
ath=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.t
ype,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed"
,options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.counter
s=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self
<TRUNCATED>
[20/50] [abbrv] removing 2 more as-yet unused files
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2ab8ec4d/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index c93af87..1c742ce 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-11 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();
uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","
no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.rest
oreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options
);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof St
orage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={cl
ient:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"func
tion"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"=
=typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid
.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===
type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.En
tity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=
this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(op
tions,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=th
is,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.follow
ing=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user ro
les"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entit
y.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{}
,this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("functi
on"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
-user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key]
;if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.get
PrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(o
ptions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={ty
pe:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+thi
s._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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",thi
s._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function
(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].j
oin("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&sel
f.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);
else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sDa
ta){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):doCallback(callback,[null,self],self)};var fr=new FileReader;fr.onload=functio
n(){var binary=fr.result;xhr.overrideMimeType("application/octet-stream"),setTimeout(function(){xhr.sendAsBinary(binary)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.excep
tion=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.time
stamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){ret
urn a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}!function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml"
,"exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0}
,Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.call
backs.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function part
ial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(
encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Reques
t"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=
new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var expor
ts,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endp
oint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okT
oSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject)
,options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.
Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.
reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=d
ata.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototy
pe.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(meth
od)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.g
et("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===type||"user"===type)&&nameProperties.unshift("username");var names=this.ge
t(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=th
is.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callba
ck&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity co
uld not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={m
ethod:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.enti
ties)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,d
ata,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self
=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._pre
vious=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNe
xtEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringi
fy(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key];if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous
=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1
+},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(ca
llback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=dat
a.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){v
ar self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.timest
amp||0,this._data.type="events",this._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergr
id.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encod
eURIComponent(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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.
entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function
<TRUNCATED>
[45/50] [abbrv] git commit: Fixing merge issues in query validator,
still fighting a compile error in the tests.
Posted by sn...@apache.org.
Fixing merge issues in query validator, still fighting a compile error in the tests.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/3dc1e9fe
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/3dc1e9fe
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/3dc1e9fe
Branch: refs/heads/optimistic-tx-semantics
Commit: 3dc1e9fe8e3cd0c7a25576cacd8be567391588f9
Parents: 0f1a38b
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 09:48:51 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 09:48:51 2014 -0500
----------------------------------------------------------------------
stack/pom.xml | 1 -
stack/query-validator/pom.xml | 2 +-
.../query/validator/ApiServerRunner.java | 4 +-
.../validator/DefaultQueryResultsMatcher.java | 32 +
.../query/validator/QueryResultsMatcher.java | 29 +
.../usergrid/query/validator/QueryRunner.java | 2 +-
.../usergrid/query/validator/SqliteRunner.java | 5 +-
.../validator/DefaultQueryResultsMatcher.java | 32 -
.../query/validator/QueryResultsMatcher.java | 29 -
.../query/validator/AbstractQueryIT.java | 133 +++
.../usergrid/query/validator/QueryITSuite.java | 39 +
.../query/validator/users/UserQueryIT.java | 877 +++++++++++++++++++
.../query/validator/AbstractQueryIT.java | 133 ---
.../usergrid/query/validator/QueryITSuite.java | 39 -
.../query/validator/users/UserQueryIT.java | 877 -------------------
15 files changed, 1116 insertions(+), 1118 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/pom.xml
----------------------------------------------------------------------
diff --git a/stack/pom.xml b/stack/pom.xml
index 6c695e9..52dbaa8 100644
--- a/stack/pom.xml
+++ b/stack/pom.xml
@@ -176,7 +176,6 @@
<module>websocket</module>
<module>rest</module>
<module>launcher</module>
- <module>query-validator</module>
<module>test-utils</module>
<module>build-tools</module>
</modules>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/pom.xml b/stack/query-validator/pom.xml
index 13f36d3..fda8466 100644
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@ -211,4 +211,4 @@
</dependency>
</dependencies>
-</project>
+</project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
index 4eba257..57434b2 100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
@@ -23,13 +23,13 @@ import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.cassandra.config.Schema;
import org.apache.commons.lang.StringUtils;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.persistence.Schema;
import org.codehaus.jackson.JsonNode;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.usergrid.java.client.Client;
-import org.usergrid.java.client.entities.Entity;
import org.usergrid.java.client.response.ApiResponse;
import static org.usergrid.java.client.utils.ObjectUtils.isEmpty;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/DefaultQueryResultsMatcher.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/DefaultQueryResultsMatcher.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/DefaultQueryResultsMatcher.java
new file mode 100644
index 0000000..7690cce
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/DefaultQueryResultsMatcher.java
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.query.validator;
+
+import org.apache.usergrid.persistence.Entity;
+
+import java.util.List;
+
+/**
+ * @author Sungju Jin
+ */
+public class DefaultQueryResultsMatcher implements QueryResultsMatcher {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ return expectedEntities.equals(actuallyEntities);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResultsMatcher.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResultsMatcher.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResultsMatcher.java
new file mode 100644
index 0000000..c85fa54
--- /dev/null
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResultsMatcher.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.query.validator;
+
+import org.apache.usergrid.persistence.Entity;
+
+import java.util.List;
+
+/**
+ * @author Sungju Jin
+ */
+public interface QueryResultsMatcher {
+ boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities);
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
index b99038d..84b2b51 100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
@@ -17,9 +17,9 @@
*/
package org.apache.usergrid.query.validator;
-import org.apache.usergrid.persistence.Entity;
import java.util.List;
+import org.apache.usergrid.persistence.Entity;
/**
* @author Sungju Jin
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
index 7c7aa55..a0ffbd6 100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
@@ -29,9 +29,8 @@ import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
-import javax.swing.tree.RowMapper;
-import org.usergrid.query.validator.QueryEntity;
-import org.usergrid.query.validator.QueryRunner;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.RowMapper;
/**
* @author Sungju Jin
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/usergrid/query/validator/DefaultQueryResultsMatcher.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/DefaultQueryResultsMatcher.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/DefaultQueryResultsMatcher.java
deleted file mode 100644
index 614b9fc..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/DefaultQueryResultsMatcher.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.usergrid.query.validator;
-
-import org.usergrid.persistence.Entity;
-
-import java.util.List;
-
-/**
- * @author Sungju Jin
- */
-public class DefaultQueryResultsMatcher implements QueryResultsMatcher {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- return expectedEntities.equals(actuallyEntities);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResultsMatcher.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResultsMatcher.java b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResultsMatcher.java
deleted file mode 100644
index e720ec5..0000000
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResultsMatcher.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.usergrid.query.validator;
-
-import org.usergrid.persistence.Entity;
-
-import java.util.List;
-
-/**
- * @author Sungju Jin
- */
-public interface QueryResultsMatcher {
- boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities);
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/AbstractQueryIT.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/AbstractQueryIT.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/AbstractQueryIT.java
new file mode 100644
index 0000000..f41a1f0
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/AbstractQueryIT.java
@@ -0,0 +1,133 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
+import org.junit.BeforeClass;
+import org.apache.usergrid.management.ApplicationInfo;
+import org.apache.usergrid.management.ManagementService;
+import org.apache.usergrid.management.OrganizationInfo;
+import org.apache.usergrid.management.UserInfo;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.utils.JsonUtils;
+
+import java.io.IOException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.*;
+
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * @author Sungju Jin
+ */
+public class AbstractQueryIT {
+
+ protected static QueryValidator validator;
+ private static Properties properties;
+ private static String fullEndpoint;
+ private static String orgName;
+ private static String appName;
+ private static String email;
+ private static String password;
+ private static int port;
+
+ @BeforeClass
+ public static void tearsup() throws Exception {
+ validator = QueryITSuite.cassandraResource.getBean(QueryValidator.class);
+ properties = QueryITSuite.cassandraResource.getBean("properties",Properties.class);
+ if( isDisableLocalServer()) {
+ return;
+ }
+ setProperties();
+ createOrganizationWithApplication();
+ }
+
+ private static void createOrganizationWithApplication() throws Exception {
+ String uuid = UUID.randomUUID().toString().replaceAll("-", "");
+ orgName = orgName + uuid;
+ appName = appName + uuid;
+ email = orgName + "@usergrid.com";
+ ManagementService managementService = QueryITSuite.serverResource.getMgmtSvc();
+ UserInfo user = managementService.createAdminUser(orgName, "Query Test", email, password, false, false);
+ OrganizationInfo org = managementService.createOrganization(orgName, user, false );
+ assertNotNull( org );
+ ApplicationInfo app = managementService.createApplication( org.getUuid(), appName);
+ assertNotNull( app );
+ }
+
+ private static void setProperties() {
+ port = QueryITSuite.serverResource.getTomcatPort();
+ fullEndpoint = (String)properties.get("usergrid.query.validator.api.endpoint") + ":" + port;
+ orgName = (String)properties.get("usergrid.query.validator.api.organization");
+ appName = (String)properties.get("usergrid.query.validator.api.app");
+ email = (String)properties.get("usergrid.query.validator.api.authorize.email");
+ password = (String)properties.get("usergrid.query.validator.api.authorize.password");
+ }
+
+ protected static void createInitializationDatas(String collection) {
+ List<Entity> entities = loadEntitiesFromResource(collection);
+ QueryValidationConfiguration configuration = new QueryValidationConfiguration();
+ configuration.setEndpointUri(fullEndpoint);
+ configuration.setOrg(orgName);
+ configuration.setEmail(email);
+ configuration.setPassword(password);
+ configuration.setApp(appName);
+ configuration.setCollection(collection);
+ configuration.setEntities(entities);
+ validator.setConfiguration(configuration);
+ validator.setup();
+ }
+
+ private static List<Entity> loadEntitiesFromResource(String collection) {
+ String json = null;
+ try {
+ URL url = Thread.currentThread().getContextClassLoader().getResource(collection + ".json");
+ json = FileUtils.readFileToString(FileUtils.toFile(url), Charset.forName("UTF-8"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ List<Entity> entities = new ArrayList<Entity>();
+ List<Map<String, Object>> datas = (List<Map<String, Object>>) JsonUtils.parse(json);
+ int index = 0;
+ for(Map<String, Object> data : datas) {
+ long created = System.currentTimeMillis() + (index*1000);
+
+ QueryEntity entity = new QueryEntity();
+ entity.setType(collection);
+ for ( Map.Entry<String, Object> property : data.entrySet() ) {
+ if(StringUtils.equals("name", property.getKey()))
+ entity.setName((String)property.getValue());
+ else
+ entity.setProperty( property.getKey(), property.getValue() );
+ }
+ entity.setProperties(data);
+ entity.setCreated(created);
+ entity.setModified(created);
+ entities.add(entity);
+ index++;
+ }
+ return entities;
+ }
+
+ private static boolean isDisableLocalServer() {
+ return !StringUtils.equalsIgnoreCase("true", (String) properties.get("usergrid.query.validator.api.enablelocal"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
new file mode 100644
index 0000000..8f92fc3
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
@@ -0,0 +1,39 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.query.validator;
+
+import org.junit.ClassRule;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.apache.usergrid.cassandra.CassandraResource;
+import org.apache.usergrid.query.validator.users.UserQueryIT;
+import org.apache.usergrid.rest.ITSetup;
+
+@RunWith(Suite.class)
+@Suite.SuiteClasses(
+ {
+ UserQueryIT.class
+ })
+public class QueryITSuite {
+ @ClassRule
+ public static CassandraResource cassandraResource = CassandraResource.newWithAvailablePorts();
+
+ //TODO Detecting current path
+ @ClassRule
+ public static ITSetup serverResource = new ITSetup( cassandraResource, "../rest/src/main/webapp" );
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/users/UserQueryIT.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/users/UserQueryIT.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/users/UserQueryIT.java
new file mode 100644
index 0000000..bf76c8a
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/users/UserQueryIT.java
@@ -0,0 +1,877 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.query.validator.users;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.query.validator.AbstractQueryIT;
+import org.apache.usergrid.query.validator.QueryRequest;
+import org.apache.usergrid.query.validator.QueryResponse;
+import org.apache.usergrid.query.validator.QueryResultsMatcher;
+import org.apache.usergrid.utils.StringUtils;
+
+import java.util.List;
+
+/**
+ * @author Sungju Jin
+ */
+public class UserQueryIT extends AbstractQueryIT {
+
+ @BeforeClass
+ public static void setDatas() {
+ createInitializationDatas("user");
+ }
+
+ @Test
+ public void sexEqualAndNameEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and name = 'judekim' LIMIT 10";
+ String api = "SELECT * WHERE sex = 'male' AND name = 'judekim'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameEqualAndSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 10";
+ String api = "select * where name = 'judekim' and sex = 'male'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameEqualAndSexEqual_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 20";
+ String api = "select * where name = 'judekim' and sex = 'male'";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndNameEqualExtra1() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'female' and name = 'curioe' LIMIT 10";
+ String api = "select * where sex = 'female' and name = 'curioe'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualOrNameEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'female' or name = 'curioe' LIMIT 10";
+ String api = "select * where sex = 'female' or name = 'curioe'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(4);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc_limitL4() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(4);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqual_sortAgeDescExtra1() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String sex = (String)entity.getProperty("sex");
+
+ if((StringUtils.equals("male",sex)) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqual_sortAgeDescExtra2() {
+ String sqlite = " SELECT * FROM users WHERE sex = 'female' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'female' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal() {
+ String sqlite = " SELECT * FROM users WHERE sex = 'male' and age >= 35 LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAgeDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAgeDesc_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 20";
+ String api = "select * where sex = 'male' and age >= 35 order by age desc";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlSexEqualAndAgeGreaterthanequal_sortNameDesc_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 20";
+ String api = "select * where sex = 'male' and age >= 35 order by name desc";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ String sex = (String)entity.getProperty("sex");
+
+ if(((StringUtils.equals("male",sex) && age >= 35) || StringUtils.equals("female",sex)) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortAgeDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY age desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void limitL12() {
+ String sqlite = "SELECT * FROM users LIMIT 12";
+ String api = null;
+ int limit = 12;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 20";
+ String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void limitL11() {
+ String sqlite = "SELECT * FROM users LIMIT 11";
+ String api = null;
+ int limit = 11;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 10";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 20";
+ String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sexEqualAndAgeGreaterthanequal_sortAddressDesc_limitL100() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY address desc LIMIT 100";
+ String api = "select * where sex = 'male' and age >= 35 order by address desc";
+ int limit = 100;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlNameEqual() {
+ String sqlite = "SELECT * FROM users WHERE name = 'judekim' LIMIT 10";
+ String api = "select * where name = 'judekim'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeEqual() {
+ String sqlite = "SELECT * FROM users WHERE age = 16 LIMIT 10";
+ String api = "select * where age = 16";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlNameEqualAndAgeEqual() {
+ String sqlite = "SELECT * FROM users WHERE name = 'askagirl' and age = 16 LIMIT 10";
+ String api = "select * where name = 'askagirl' and age = 16";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String name = entity.getName();
+ int age = (Integer)entity.getProperty("age");
+ if ((StringUtils.equals("askagirl", name) && age == 16) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeLessthan() {
+ String sqlite = "SELECT * FROM users WHERE age < 16 LIMIT 10";
+ String api = "select * where age < 16";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ if((age < 16) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeLessthanequal() {
+ String sqlite = "SELECT * FROM users WHERE age <= 16 LIMIT 20";
+ String api = "select * where age <= 16";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ if((age <= 16) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeGreaterthan() {
+ String sqlite = "SELECT * FROM users WHERE age > 16 LIMIT 10";
+ String api = "select * where age > 16";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ if((age > 16) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeGreaterthanequal() {
+ String sqlite = "SELECT * FROM users WHERE age >= 16 LIMIT 10";
+ String api = "select * where age >= 16";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ if((age >= 16) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeGreaterthanequalAndAgeLessthan() {
+ String sqlite = "SELECT * FROM users WHERE age >= 32 and age < 40 LIMIT 10";
+ String api = "select * where age >= 32 and age < 40";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ if((age >= 32 && age < 40) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAgeGreaterthanequalAndAgeLessthanAndSexEqual() {
+ String sqlite = "SELECT * FROM users WHERE age >= 32 and age < 40 and sex = 'female' LIMIT 10";
+ String api = "select * where age >= 32 and age < 40 and sex = 'female'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ String sex = (String)entity.getProperty("sex");
+
+ if((age >= 32 && age < 40 && StringUtils.equals("female",sex)) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAddressFulltext() {
+ String sqlite = "SELECT * FROM users WHERE address LIKE '%서울시%' LIMIT 10";
+ String api = "select * where address contains '서울시'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String address = (String)entity.getProperty("address");
+
+ if((StringUtils.contains(address,"서울시")) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAddressFulltextstartswith() {
+ String sqlite = " SELECT * FROM users WHERE address LIKE 'A%' LIMIT 10";
+ String api = "select * where address contains 'A*'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String address = (String)entity.getProperty("address");
+
+ if((StringUtils.startsWith(address,"A")) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAddressBeginswith() {
+ String sqlite = "SELECT * FROM users WHERE address LIKE 'B%' LIMIT 10";
+ String api = "select * where address = 'B*'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String address = (String)entity.getProperty("address");
+
+ if((StringUtils.startsWith(address,"B")) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAddressBeginswithAndSexFulltextstartswith() {
+ String sqlite = "SELECT * FROM users WHERE address LIKE 'C%' and sex LIKE 'ma%' LIMIT 10";
+ String api = "select * where address = 'C*' and sex contains 'ma*'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String address = (String)entity.getProperty("address");
+
+ if((StringUtils.startsWith(address,"C")) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlAddressBeginswithAndSexFulltext() {
+ String sqlite = "SELECT * FROM users WHERE (address LIKE 'D%' and sex LIKE '%male%') LIMIT 10";
+ String api = "select * where address = 'D*' and sex contains 'male'";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ String address = (String)entity.getProperty("address");
+
+ if((StringUtils.startsWith(address,"D")) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void qlSexEqualOrAgeGreaterthanequalAndAgeLessthan_limitL20() {
+ String sqlite = "SELECT * FROM users WHERE sex = 'female' or age >= 12 and age < 20 LIMIT 20";
+ String api = "select * where sex = 'female' or age >= 12 and age < 20";
+ int limit = 20;
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ request.getApiQuery().setLimit(limit);
+ QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
+ @Override
+ public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
+ boolean equals = expectedEntities.size() == expectedEntities.size();
+ if( !equals )
+ return false;
+
+ for(Entity entity : actuallyEntities) {
+ int age = (Integer)entity.getProperty("age");
+ String sex = (String)entity.getProperty("sex");
+
+ if(((StringUtils.equals("female",sex) || age >= 12) && age < 20) == false) {
+ return false;
+ }
+ }
+ return equals;
+ }
+ });
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortNameAsc() {
+ String sqlite = "SELECT * FROM users ORDER BY name asc LIMIT 10";
+ String api = "select * order by name asc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortNameDesc() {
+ String sqlite = "SELECT * FROM users ORDER BY name desc LIMIT 10";
+ String api = "select * order by name desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortNameAscAgeDesc() {
+ String sqlite = "SELECT * FROM users ORDER BY name asc, age desc LIMIT 10";
+ String api = "select * order by name asc, age desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortNameAscAddressAsc() {
+ String sqlite = "SELECT * FROM users ORDER BY name asc, address asc LIMIT 10";
+ String api = "select * order by name asc, address asc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortCreatedAsc() {
+ String sqlite = "SELECT * FROM users ORDER BY created asc LIMIT 10";
+ String api = "select * order by created asc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortCreatedDesc() {
+ String sqlite = "SELECT * FROM users ORDER BY created desc LIMIT 10";
+ String api = "select * order by created desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortModifiedAsc() {
+ String sqlite = "SELECT * FROM users ORDER BY modified asc LIMIT 10";
+ String api = "select * order by modified asc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortCreatedDescNameAsc() {
+ String sqlite = "SELECT * FROM users ORDER BY created desc, name asc LIMIT 10";
+ String api = "select * order by created desc, name asc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+
+ @Test
+ public void sortNameAscCreatedDesc() {
+ String sqlite = "SELECT * FROM users ORDER BY name asc, created desc LIMIT 10";
+ String api = "select * order by name asc, created desc";
+
+ QueryRequest request = new QueryRequest();
+ request.setDbQuery(sqlite);
+ request.getApiQuery().setQuery(api);
+ QueryResponse response = validator.execute(request);
+ Assert.assertTrue(response.toString(), response.result());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/usergrid/query/validator/AbstractQueryIT.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/usergrid/query/validator/AbstractQueryIT.java b/stack/query-validator/src/test/java/org/usergrid/query/validator/AbstractQueryIT.java
deleted file mode 100644
index b48e094..0000000
--- a/stack/query-validator/src/test/java/org/usergrid/query/validator/AbstractQueryIT.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.usergrid.query.validator;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.junit.BeforeClass;
-import org.usergrid.management.ApplicationInfo;
-import org.usergrid.management.ManagementService;
-import org.usergrid.management.OrganizationInfo;
-import org.usergrid.management.UserInfo;
-import org.usergrid.persistence.Entity;
-import org.usergrid.utils.JsonUtils;
-
-import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.*;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * @author Sungju Jin
- */
-public class AbstractQueryIT {
-
- protected static QueryValidator validator;
- private static Properties properties;
- private static String fullEndpoint;
- private static String orgName;
- private static String appName;
- private static String email;
- private static String password;
- private static int port;
-
- @BeforeClass
- public static void tearsup() throws Exception {
- validator = QueryITSuite.cassandraResource.getBean(QueryValidator.class);
- properties = QueryITSuite.cassandraResource.getBean("properties",Properties.class);
- if( isDisableLocalServer()) {
- return;
- }
- setProperties();
- createOrganizationWithApplication();
- }
-
- private static void createOrganizationWithApplication() throws Exception {
- String uuid = UUID.randomUUID().toString().replaceAll("-", "");
- orgName = orgName + uuid;
- appName = appName + uuid;
- email = orgName + "@usergrid.com";
- ManagementService managementService = QueryITSuite.serverResource.getMgmtSvc();
- UserInfo user = managementService.createAdminUser(orgName, "Query Test", email, password, false, false);
- OrganizationInfo org = managementService.createOrganization(orgName, user, false );
- assertNotNull( org );
- ApplicationInfo app = managementService.createApplication( org.getUuid(), appName);
- assertNotNull( app );
- }
-
- private static void setProperties() {
- port = QueryITSuite.serverResource.getTomcatPort();
- fullEndpoint = (String)properties.get("usergrid.query.validator.api.endpoint") + ":" + port;
- orgName = (String)properties.get("usergrid.query.validator.api.organization");
- appName = (String)properties.get("usergrid.query.validator.api.app");
- email = (String)properties.get("usergrid.query.validator.api.authorize.email");
- password = (String)properties.get("usergrid.query.validator.api.authorize.password");
- }
-
- protected static void createInitializationDatas(String collection) {
- List<Entity> entities = loadEntitiesFromResource(collection);
- QueryValidationConfiguration configuration = new QueryValidationConfiguration();
- configuration.setEndpointUri(fullEndpoint);
- configuration.setOrg(orgName);
- configuration.setEmail(email);
- configuration.setPassword(password);
- configuration.setApp(appName);
- configuration.setCollection(collection);
- configuration.setEntities(entities);
- validator.setConfiguration(configuration);
- validator.setup();
- }
-
- private static List<Entity> loadEntitiesFromResource(String collection) {
- String json = null;
- try {
- URL url = Thread.currentThread().getContextClassLoader().getResource(collection + ".json");
- json = FileUtils.readFileToString(FileUtils.toFile(url), Charset.forName("UTF-8"));
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- List<Entity> entities = new ArrayList<Entity>();
- List<Map<String, Object>> datas = (List<Map<String, Object>>) JsonUtils.parse(json);
- int index = 0;
- for(Map<String, Object> data : datas) {
- long created = System.currentTimeMillis() + (index*1000);
-
- QueryEntity entity = new QueryEntity();
- entity.setType(collection);
- for ( Map.Entry<String, Object> property : data.entrySet() ) {
- if(StringUtils.equals("name", property.getKey()))
- entity.setName((String)property.getValue());
- else
- entity.setProperty( property.getKey(), property.getValue() );
- }
- entity.setProperties(data);
- entity.setCreated(created);
- entity.setModified(created);
- entities.add(entity);
- index++;
- }
- return entities;
- }
-
- private static boolean isDisableLocalServer() {
- return !StringUtils.equalsIgnoreCase("true", (String) properties.get("usergrid.query.validator.api.enablelocal"));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryITSuite.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryITSuite.java b/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryITSuite.java
deleted file mode 100644
index 327776f..0000000
--- a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryITSuite.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.usergrid.query.validator;
-
-import org.junit.ClassRule;
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-import org.usergrid.cassandra.CassandraResource;
-import org.usergrid.query.validator.users.UserQueryIT;
-import org.usergrid.rest.ITSetup;
-
-@RunWith(Suite.class)
-@Suite.SuiteClasses(
- {
- UserQueryIT.class
- })
-public class QueryITSuite {
- @ClassRule
- public static CassandraResource cassandraResource = CassandraResource.newWithAvailablePorts();
-
- //TODO Detecting current path
- @ClassRule
- public static ITSetup serverResource = new ITSetup( cassandraResource, "../rest/src/main/webapp" );
-}
\ No newline at end of file
[21/50] [abbrv] git commit: removing 2 more as-yet unused files
Posted by sn...@apache.org.
removing 2 more as-yet unused files
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/2ab8ec4d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/2ab8ec4d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/2ab8ec4d
Branch: refs/heads/optimistic-tx-semantics
Commit: 2ab8ec4d2f69bf4b35ddf5087c47009078b404c5
Parents: 0dc6c70
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 11:15:32 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 11:15:32 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/Gruntfile.js | 2 -
sdks/html5-javascript/lib/modules/util/Event.js | 33 -----
.../lib/modules/util/Storable.js | 88 -------------
sdks/html5-javascript/usergrid.js | 132 -------------------
sdks/html5-javascript/usergrid.min.js | 4 +-
5 files changed, 2 insertions(+), 257 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2ab8ec4d/sdks/html5-javascript/Gruntfile.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/Gruntfile.js b/sdks/html5-javascript/Gruntfile.js
index cfa39e3..d48a950 100644
--- a/sdks/html5-javascript/Gruntfile.js
+++ b/sdks/html5-javascript/Gruntfile.js
@@ -1,10 +1,8 @@
module.exports = function(grunt) {
var files = [
- "lib/modules/util/Event.js",
"lib/modules/util/Logger.js",
"lib/modules/util/Promise.js",
"lib/modules/util/Ajax.js",
- "lib/modules/util/Storable.js",
"lib/Usergrid.js",
"lib/modules/Client.js",
"lib/modules/Entity.js",
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2ab8ec4d/sdks/html5-javascript/lib/modules/util/Event.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Event.js b/sdks/html5-javascript/lib/modules/util/Event.js
deleted file mode 100644
index 146d03e..0000000
--- a/sdks/html5-javascript/lib/modules/util/Event.js
+++ /dev/null
@@ -1,33 +0,0 @@
-var UsergridEventable = function(){
- throw Error("'UsergridEventable' is not intended to be invoked directly")
-}
-UsergridEventable.prototype = {
- bind : function(event, fn){
- this._events = this._events || {};
- this._events[event] = this._events[event] || [];
- this._events[event].push(fn);
- },
- unbind : function(event, fn){
- this._events = this._events || {};
- if( event in this._events === false ) return;
- this._events[event].splice(this._events[event].indexOf(fn), 1);
- },
- trigger : function(event /* , args... */){
- this._events = this._events || {};
- if( event in this._events === false ) return;
- for(var i = 0; i < this._events[event].length; i++){
- this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1))
- }
- }
-};
-UsergridEventable.mixin = function(destObject){
- var props = ['bind', 'unbind', 'trigger'];
- for(var i = 0; i < props.length; i ++){
- if(props[i] in destObject.prototype){
- console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'.");
- console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'.");
- destObject.prototype['_'+props[i]]=destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]];
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2ab8ec4d/sdks/html5-javascript/lib/modules/util/Storable.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Storable.js b/sdks/html5-javascript/lib/modules/util/Storable.js
deleted file mode 100644
index 5c4da2e..0000000
--- a/sdks/html5-javascript/lib/modules/util/Storable.js
+++ /dev/null
@@ -1,88 +0,0 @@
-function UsergridStorable(storage, keyPrefix){
- //throw Error("'UsergridStorable' is not intended to be invoked directly")
-}
-UsergridStorable.prototype.setStorage = function(storage) {
- if(!(storage instanceof Storage)){
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- storage=sessionStorage;
- }
- return this._storage=storage;
-};
-UsergridStorable.prototype.getStorage = function() {
- if(!(this._storage instanceof Storage)){
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- this._storage=sessionStorage;
- }
- return this._storage;
-};
-UsergridStorable.prototype.getStorageKey = function(key) {
- if(!this._keyPrefix)this._keyPrefix='usergrid_js_sdk_';
- return this._keyPrefix+key;
-};
-UsergridStorable.prototype.get=function(key){
- var value;
- if(arguments.length>1){
- key=[].slice.call(arguments).reduce(function(p,c,i,a){
- if(c instanceof Array){
- p= p.concat(c);
- }else{
- p.push(c);
- }
- return p;
- },[]);
- }
- if(this._storage instanceof Storage){
- if(key instanceof Array){
- var self=this;
- value=key.map(function(k){return self.get(k)});
- }else if("undefined" !== typeof key){
- this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
- value=this[key];
- }
- }
- return value;
-}
-UsergridStorable.prototype.set=function(key, value){
- if(this._storage instanceof Storage){
- if(value){
- this[key]=JSON.stringify(value);
- this.getStorage().setItem(this.getStorageKey(key),this[key]);
- }else{
- delete this[key];
- this.getStorage().removeItem(this.getStorageKey(key));
- }
- }
-}
-/*
- * A public method to store the OAuth token for later use - uses localstorage if available
- *
- * @method setToken
- * @public
- * @params {string} token
- * @return none
- */
-UsergridStorable.prototype.setToken = function (token) {
- return this.set('token', token);
-};
-
-/*
- * A public method to get the OAuth token
- *
- * @method getToken
- * @public
- * @return {string} token
- */
-UsergridStorable.prototype.getToken = function () {
- return this.get('token');
-};
-UsergridStorable.mixin = function(destObject){
- var props = ['getStorage', 'setStorage', 'getStorageKey', 'get', 'set', 'getToken', 'setToken'];
- for(var i = 0; i < props.length; i ++){
- if(props[i] in destObject.prototype){
- console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'.");
- console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'.");
- destObject.prototype['_'+props[i]]=destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/2ab8ec4d/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index ff83f6c..b8debdf 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -1,40 +1,4 @@
/*! usergrid@0.0.0 2014-02-11 */
-var UsergridEventable = function() {
- throw Error("'UsergridEventable' is not intended to be invoked directly");
-};
-
-UsergridEventable.prototype = {
- bind: function(event, fn) {
- this._events = this._events || {};
- this._events[event] = this._events[event] || [];
- this._events[event].push(fn);
- },
- unbind: function(event, fn) {
- this._events = this._events || {};
- if (event in this._events === false) return;
- this._events[event].splice(this._events[event].indexOf(fn), 1);
- },
- trigger: function(event) {
- this._events = this._events || {};
- if (event in this._events === false) return;
- for (var i = 0; i < this._events[event].length; i++) {
- this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
- }
- }
-};
-
-UsergridEventable.mixin = function(destObject) {
- var props = [ "bind", "unbind", "trigger" ];
- for (var i = 0; i < props.length; i++) {
- if (props[i] in destObject.prototype) {
- console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'.");
- console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'.");
- destObject.prototype["_" + props[i]] = destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridEventable.prototype[props[i]];
- }
-};
-
//Logger
(function() {
var name = "Logger", global = this, overwrittenName = global[name], exports;
@@ -253,102 +217,6 @@ UsergridEventable.mixin = function(destObject) {
return global[name];
})();
-function UsergridStorable(storage, keyPrefix) {}
-
-UsergridStorable.prototype.setStorage = function(storage) {
- if (!(storage instanceof Storage)) {
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- storage = sessionStorage;
- }
- return this._storage = storage;
-};
-
-UsergridStorable.prototype.getStorage = function() {
- if (!(this._storage instanceof Storage)) {
- console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage");
- this._storage = sessionStorage;
- }
- return this._storage;
-};
-
-UsergridStorable.prototype.getStorageKey = function(key) {
- if (!this._keyPrefix) this._keyPrefix = "usergrid_js_sdk_";
- return this._keyPrefix + key;
-};
-
-UsergridStorable.prototype.get = function(key) {
- var value;
- if (arguments.length > 1) {
- key = [].slice.call(arguments).reduce(function(p, c, i, a) {
- if (c instanceof Array) {
- p = p.concat(c);
- } else {
- p.push(c);
- }
- return p;
- }, []);
- }
- if (this._storage instanceof Storage) {
- if (key instanceof Array) {
- var self = this;
- value = key.map(function(k) {
- return self.get(k);
- });
- } else if ("undefined" !== typeof key) {
- this[key] = JSON.parse(this.getStorage().getItem(this.getStorageKey(key)));
- value = this[key];
- }
- }
- return value;
-};
-
-UsergridStorable.prototype.set = function(key, value) {
- if (this._storage instanceof Storage) {
- if (value) {
- this[key] = JSON.stringify(value);
- this.getStorage().setItem(this.getStorageKey(key), this[key]);
- } else {
- delete this[key];
- this.getStorage().removeItem(this.getStorageKey(key));
- }
- }
-};
-
-/*
- * A public method to store the OAuth token for later use - uses localstorage if available
- *
- * @method setToken
- * @public
- * @params {string} token
- * @return none
- */
-UsergridStorable.prototype.setToken = function(token) {
- return this.set("token", token);
-};
-
-/*
- * A public method to get the OAuth token
- *
- * @method getToken
- * @public
- * @return {string} token
- */
-UsergridStorable.prototype.getToken = function() {
- return this.get("token");
-};
-
-UsergridStorable.mixin = function(destObject) {
- var props = [ "getStorage", "setStorage", "getStorageKey", "get", "set", "getToken", "setToken" ];
- for (var i = 0; i < props.length; i++) {
- if (props[i] in destObject.prototype) {
- console.warn("overwriting '" + props[i] + "' on '" + destObject.name + "'.");
- console.warn("the previous version can be found at '_" + props[i] + "' on '" + destObject.name + "'.");
- destObject.prototype["_" + props[i]] = destObject.prototype[props[i]];
- }
- destObject.prototype[props[i]] = UsergridStorable.prototype[props[i]];
- }
-};
-
/*
* This module is a collection of classes designed to make working with
* the Appigee App Services API as easy as possible.
[22/50] [abbrv] Revert "removing 2 more as-yet unused files"
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/a0a585ba/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index 1c742ce..c93af87 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-11 */
-function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){ret
urn a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}!function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml"
,"exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0}
,Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.call
backs.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function part
ial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(
encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Reques
t"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=
new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var expor
ts,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endp
oint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okT
oSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject)
,options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.
Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.
reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=d
ata.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototy
pe.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(meth
od)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.g
et("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===type||"user"===type)&&nameProperties.unshift("username");var names=this.ge
t(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=th
is.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callba
ck&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity co
uld not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={m
ethod:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.enti
ties)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,d
ata,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self
=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._pre
vious=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNe
xtEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringi
fy(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key];if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous
=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1
-},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(ca
llback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=dat
a.entities[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){v
ar self=this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.timest
amp||0,this._data.type="events",this._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergr
id.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encod
eURIComponent(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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.
entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[
err,new UsergridError(data)],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.
prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folde
r){if(err)return callback.call(self,err,folder);var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),t
his.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_descr
iption,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),Usergr
idError},global[name]}(this);
\ No newline at end of file
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();
uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","
no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.rest
oreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options
);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof St
orage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={cl
ient:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"func
tion"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"=
=typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid
.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===
type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.En
tity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=
this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(op
tions,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=th
is,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.follow
ing=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user ro
les"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entit
y.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{}
,this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("functi
on"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
+user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key]
;if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.get
PrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(o
ptions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={ty
pe:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+thi
s._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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",thi
s._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function
(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].j
oin("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&sel
f.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function
<TRUNCATED>
[43/50] [abbrv] git commit: Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
Merge branch 'master' into two-dot-o
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/0f1a38b3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/0f1a38b3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/0f1a38b3
Branch: refs/heads/optimistic-tx-semantics
Commit: 0f1a38b310b73fe9bf62b2cd44517d2eea327786
Parents: 55293d1 c5b43cf
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 09:20:30 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 09:20:30 2014 -0500
----------------------------------------------------------------------
stack/query-validator/pom.xml | 2 +-
.../org/apache/usergrid/query/validator/QueryValidatorRunner.java | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
[40/50] [abbrv] git commit: Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
Merge branch 'master' into two-dot-o
Conflicts:
.gitignore
stack/query-validator/pom.xml
stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/3ed72f1e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/3ed72f1e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/3ed72f1e
Branch: refs/heads/optimistic-tx-semantics
Commit: 3ed72f1e132ca92b4a929136f118cd194db0f104
Parents: fb5f8d6 eb46ac7
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 08:39:20 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 08:39:20 2014 -0500
----------------------------------------------------------------------
.gitignore | 4 +-
README.md | 29 +
sdks/html5-javascript/Gruntfile.js | 169 +-
sdks/html5-javascript/lib/Client.js | 865 ------
sdks/html5-javascript/lib/Collection.js | 446 ---
sdks/html5-javascript/lib/Counter.js | 186 --
sdks/html5-javascript/lib/Entity.js | 646 -----
sdks/html5-javascript/lib/Group.js | 233 --
sdks/html5-javascript/lib/Module.js | 34 +
sdks/html5-javascript/lib/Usergrid.js | 283 +-
sdks/html5-javascript/lib/modules/Asset.js | 149 +
sdks/html5-javascript/lib/modules/Client.js | 749 +++++
sdks/html5-javascript/lib/modules/Collection.js | 459 +++
sdks/html5-javascript/lib/modules/Counter.js | 186 ++
sdks/html5-javascript/lib/modules/Entity.js | 659 +++++
sdks/html5-javascript/lib/modules/Error.js | 125 +
sdks/html5-javascript/lib/modules/Folder.js | 167 ++
sdks/html5-javascript/lib/modules/Group.js | 233 ++
sdks/html5-javascript/lib/modules/util/Ajax.js | 74 +
sdks/html5-javascript/lib/modules/util/Event.js | 33 +
.../html5-javascript/lib/modules/util/Logger.js | 68 +
.../lib/modules/util/Promise.js | 83 +
sdks/html5-javascript/tests/mocha/test.js | 1036 +++++--
.../tests/resources/js/blanket_mocha.min.js | 2 +-
sdks/html5-javascript/usergrid.js | 2673 +++++++++++-------
sdks/html5-javascript/usergrid.min.js | 5 +-
stack/README.md | 4 +-
stack/query-validator/pom.xml | 87 +-
.../query/validator/ApiServerRunner.java | 212 ++
.../usergrid/query/validator/QueryEntity.java | 63 +
.../usergrid/query/validator/QueryRequest.java | 67 +
.../usergrid/query/validator/QueryResponse.java | 105 +
.../usergrid/query/validator/QueryRunner.java | 31 +
.../validator/QueryValidationConfiguration.java | 94 +
.../query/validator/QueryValidator.java | 78 +
.../usergrid/query/validator/SqliteRunner.java | 193 ++
.../query/validator/ApiServerRunner.java | 214 --
.../usergrid/query/validator/QueryEntity.java | 63 -
.../usergrid/query/validator/QueryRequest.java | 67 -
.../usergrid/query/validator/QueryResponse.java | 105 -
.../usergrid/query/validator/QueryRunner.java | 31 -
.../validator/QueryValidationConfiguration.java | 94 -
.../query/validator/QueryValidator.java | 78 -
.../usergrid/query/validator/SqliteRunner.java | 193 --
.../query/validator/CassandraRunner.java | 199 ++
.../query/validator/QueryValidationTest.java | 339 +++
.../query/validator/QueryValidatorRunner.java | 207 ++
.../query/validator/QueryValidationTest.java | 339 ---
.../query/validator/QueryValidatorRunner.java | 209 --
stack/rest/pom.xml | 4 +-
50 files changed, 7576 insertions(+), 5096 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/pom.xml
index 22158b5,33c61f9..bace601
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@@ -95,191 -92,106 +95,126 @@@
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-config</artifactId>
<version>${project.version}</version>
- <scope>test</scope>
- <classifier>tests</classifier>
</dependency>
+
<dependency>
<groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-count-batcher</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-count-common</artifactId>
- <version>${project.version}</version>
- <classifier>classes</classifier>
- <exclusions>
- <exclusion>
- <artifactId>servlet-api</artifactId>
- <groupId>javax.servlet</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-test-utils</artifactId>
<version>${project.version}</version>
- <scope>test</scope>
+ <classifier>compiled-jsp</classifier>
</dependency>
+
<dependency>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
+ <classifier>tests</classifier>
+ <scope>test</scope>
</dependency>
+
+ <!-- Apache Dependencies -->
+
<dependency>
- <groupId>commons-collections</groupId>
- <artifactId>commons-collections</artifactId>
- </dependency>
-
- <!-- SUN, Javax Package, and Other Com Dependencies -->
-
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- </dependency>
-
- <!--<dependency>-->
- <!--<!– TODO - should not scope be 'test' ? –>-->
- <!--<groupId>org.slf4j</groupId>-->
- <!--<artifactId>jcl-over-slf4j</artifactId>-->
- <!--</dependency>-->
-
- <!--<dependency>-->
- <!--<!– TODO - should not scope be 'test' ? –>-->
- <!--<groupId>org.slf4j</groupId>-->
- <!--<artifactId>jul-to-slf4j</artifactId>-->
- <!--</dependency>-->
-
- <!-- Testing and Logging Dependencies -->
-
- <dependency>
<groupId>org.apache.usergrid</groupId>
<artifactId>usergrid-core</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<classifier>tests</classifier>
</dependency>
+
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
+ <groupId>org.usergrid</groupId>
+ <artifactId>usergrid-test-utils</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.usergrid</groupId>
+ <artifactId>usergrid-core</artifactId>
+ <version>${project.version}</version>
<scope>test</scope>
+ <classifier>tests</classifier>
</dependency>
+
<dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jcl-over-slf4j</artifactId>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jul-to-slf4j</artifactId>
+ <groupId>org.jvnet.mock-javamail</groupId>
+ <artifactId>mock-javamail</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
+ <groupId>org.hectorclient</groupId>
+ <artifactId>hector-test</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-core</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-logging-juli</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-aop</artifactId>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-jasper</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-jasper-el</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-jsp-api</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>juli</artifactId>
+ <scope>test</scope>
</dependency>
+
+ <!-- use the external test client. Just depend on the maven jetty plugin to launch jetty -->
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
+ <groupId>com.sun.jersey.jersey-test-framework</groupId>
+ <artifactId>jersey-test-framework-external</artifactId>
<scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${org.springframework.version}</version>
+ <groupId>com.sun.jersey.jersey-test-framework</groupId>
+ <artifactId>jersey-test-framework-core</artifactId>
+ <scope>test</scope>
</dependency>
+
-
-
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>org.usergrid</groupId>
+ <artifactId>usergrid-java-client</artifactId>
</dependency>
+
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
@@@ -297,17 -203,6 +226,7 @@@
<version>0.0.3</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>org.apache.usergrid</groupId>
- <artifactId>usergrid-standalone</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <artifactId>commons-logging</artifactId>
- <groupId>commons-logging</groupId>
- </exclusion>
- </exclusions>
- </dependency>
+
</dependencies>
+
</project>
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
index 0000000,c5f28e6..4eba257
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/ApiServerRunner.java
@@@ -1,0 -1,212 +1,212 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
-import org.apache.commons.lang.StringUtils;
-import org.codehaus.jackson.JsonNode;
-import org.springframework.http.HttpMethod;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.persistence.Entity;
-
+ import java.util.ArrayList;
+ import java.util.HashMap;
+ import java.util.List;
-import org.apache.usergrid.persistence.Schema;
-
+ import java.util.Map;
+ import java.util.logging.Level;
+ import java.util.logging.Logger;
++import org.apache.cassandra.config.Schema;
++import org.apache.commons.lang.StringUtils;
++import org.codehaus.jackson.JsonNode;
++import org.springframework.http.HttpMethod;
++import org.springframework.stereotype.Component;
+ import org.usergrid.java.client.Client;
++import org.usergrid.java.client.entities.Entity;
+ import org.usergrid.java.client.response.ApiResponse;
-
+ import static org.usergrid.java.client.utils.ObjectUtils.isEmpty;
+
++
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ @Component
+ public class ApiServerRunner implements QueryRunner {
+
+ private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
+ private Client client;
+
+ private String org;
+ private String app;
+ private String baseUri;
+ private String email;
+ private String password;
+ private String collection;
+ private List<Entity> entities;
+
+ @Override
+ public boolean setup() {
+ client = new Client(getOrg(), getApp()).withApiUrl(getBaseUri());
+ String accessToken = authorize(email, password);
+ if(!StringUtils.isEmpty(accessToken))
+ client.setAccessToken(accessToken);
+ return insertDatas();
+ }
+
+ public String authorize(String email, String password) {
+ String accessToken = null;
+ Map<String, Object> formData = new HashMap<String, Object>();
+ formData.put("grant_type", "password");
+ formData.put("username", email);
+ formData.put("password", password);
+ ApiResponse response = client.apiRequest(HttpMethod.POST, null, formData,
+ "management", "token");
+ if (!isEmpty(response.getAccessToken())) {
+ accessToken = response.getAccessToken();
+ logger.info("Access token: " + accessToken);
+ } else {
+ logger.info("Response: " + response);
+ }
+ return accessToken;
+ }
+
+ public boolean insertDatas() {
+ List<org.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
+ for(org.usergrid.java.client.entities.Entity entity : clientEntities) {
+ ApiResponse response = client.createEntity(entity);
+ if( response == null || !StringUtils.isEmpty(response.getError()) ) {
+ logger.log(Level.SEVERE, response.getErrorDescription());
+ //throw new RuntimeException(response.getErrorDescription());
+ } else {
+ logger.log(Level.INFO, response.toString());
+ }
+ }
+ return true;
+ }
+
+ private List<org.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
+ List<org.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.usergrid.java.client.entities.Entity>();
+ for(Entity entity : entities) {
+ org.usergrid.java.client.entities.Entity clientEntity = new org.usergrid.java.client.entities.Entity();
+ clientEntity.setType(entity.getType());
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ Object value = entity.getProperty(key);
+ if( value instanceof String )
+ clientEntity.setProperty(key,(String)value );
+ else if( value instanceof Long )
+ clientEntity.setProperty(key,(Long)value );
+ else if( value instanceof Integer )
+ clientEntity.setProperty(key,(Integer)value );
+ else if( value instanceof Float )
+ clientEntity.setProperty(key,(Float)value );
+ else if( value instanceof Boolean )
+ clientEntity.setProperty(key,(Boolean)value );
+ }
+ clientEntities.add(clientEntity);
+ }
+ return clientEntities;
+ }
+
+ @Override
+ public List<Entity> execute(String query) {
+ return execute(query, 10);
+ }
+
+ @Override
+ public List<Entity> execute(String query, int limit) {
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put("ql", query);
+ params.put("limit", limit);
+ ApiResponse response = client.apiRequest(HttpMethod.GET, params, null, getOrg(), getApp(), getCollection());
+ List<Entity> entities = new ArrayList<Entity>();
+ if( response.getEntities() == null )
+ return entities;
+
+ for(org.usergrid.java.client.entities.Entity clientEntitity : response.getEntities()) {
+ Entity entity = new QueryEntity();
+ entity.setUuid(clientEntitity.getUuid());
+ entity.setType(clientEntitity.getType());
+ Map<String, JsonNode> values = clientEntitity.getProperties();
+ for( String key : values.keySet() ) {
+ JsonNode node = values.get(key);
+ if( node.isBoolean() ) {
+ entity.setProperty(key, node.asBoolean());
+ } else if( node.isInt() ) {
+ entity.setProperty(key, node.asInt());
+ } else if( node.isLong() ) {
+ entity.setProperty(key, node.asLong());
+ } else if( node.isDouble() ) {
+ entity.setProperty(key, node.asDouble());
+ } else {
+ entity.setProperty(key, node.asText());
+ }
+ }
+ entities.add(entity);
+ }
+ return entities;
+ }
+
+ public String getOrg() {
+ return org;
+ }
+
+ public void setOrg(String org) {
+ this.org = org;
+ }
+
+ public String getApp() {
+ return app;
+ }
+
+ public void setApp(String app) {
+ this.app = app;
+ }
+
+ public String getBaseUri() {
+ return baseUri;
+ }
+
+ public void setBaseUri(String baseUri) {
+ this.baseUri = baseUri;
+ }
+
+ public String getCollection() {
+ return collection;
+ }
+
+ public void setCollection(String collection) {
+ this.collection = collection;
+ }
+
+ public List<Entity> getEntities() {
+ return entities;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
index 0000000,77893bd..5790204
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryEntity.java
@@@ -1,0 -1,34 +1,63 @@@
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
++ *
++ * http://www.apache.org/licenses/LICENSE-2.0
++ *
++ * Unless required by applicable law or agreed to in writing, software
++ * distributed under the License is distributed on an "AS IS" BASIS,
++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++ * See the License for the specific language governing permissions and
++ * limitations under the License.
++ */
+ package org.apache.usergrid.query.validator;
+
+ import org.apache.usergrid.persistence.DynamicEntity;
+
+ import java.util.Map;
+
++/**
++ * @author Sungju Jin
++ */
+ public class QueryEntity extends DynamicEntity {
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ if(!(obj instanceof QueryEntity))
+ return false;
+
+ QueryEntity other = (QueryEntity)obj;
+ Map<String, Object> properties = this.getProperties();
+ Map<String, Object> otherProperties = other.getProperties();
+ for(String key : properties.keySet()) {
+ if( "created".equals(key) || "modified".equals(key) )
+ continue;
+
+ Object value = properties.get(key);
+ Object otherValue = otherProperties.get(key);
++
++ if(value.getClass() == Boolean.class) {
++ value = (Boolean)value ? 1 : 0;
++ }
++
++ if(otherValue.getClass() == Boolean.class) {
++ otherValue = (Boolean)otherValue ? 1 : 0;
++ }
++
+ if( otherValue == null || !value.equals(otherValue) )
+ return false;
+ }
+ return true;
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
index 0000000,d2989c7..eecc0d2
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRequest.java
@@@ -1,0 -1,74 +1,67 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ public class QueryRequest {
+ private String dbQuery;
+ private ApiQuery apiQuery;
- private boolean ignoreOrdering;
+
+ public QueryRequest() {
+ this.apiQuery = new ApiQuery();
+ }
+
+ public String getDbQuery() {
+ return dbQuery;
+ }
+
+ public void setDbQuery(String dbQuery) {
+ this.dbQuery = dbQuery;
+ }
+
+ public ApiQuery getApiQuery() {
+ return apiQuery;
+ }
+
+ static public class ApiQuery {
+ private String query;
+ private int limit;
+
+ public ApiQuery() {
+ limit = 10;
+ }
+
+ public String getQuery() {
+ return query;
+ }
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ public int getLimit() {
+ return limit;
+ }
+
+ public void setLimit(int limit) {
+ this.limit = limit;
+ }
+ }
-
- public boolean isIgnoreOrdering() {
- return ignoreOrdering;
- }
-
- public void setIgnoreOrdering(boolean ignoreOrdering) {
- this.ignoreOrdering = ignoreOrdering;
- }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
index 0000000,aa152d5..b3669ff
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryResponse.java
@@@ -1,0 -1,103 +1,105 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
+ import org.apache.commons.lang.StringUtils;
+ import org.apache.usergrid.persistence.Entity;
+
+ import java.util.List;
+
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ public class QueryResponse {
+
+ boolean result;
+ List<Entity> expacted;
+ List<Entity> actually;
+ String description;
+ QueryRequest request;
+
+ public boolean result() {
+ return result;
+ }
+
+ public void setResult(boolean result) {
+ this.result = result;
+ }
+
+ public List<Entity> getExpacted() {
+ return expacted;
+ }
+
+ public void setExpacted(List<Entity> expacted) {
+ this.expacted = expacted;
+ }
+
+ public List<Entity> getActually() {
+ return actually;
+ }
+
+ public void setActually(List<Entity> actually) {
+ this.actually = actually;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public QueryRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(QueryRequest request) {
+ this.request = request;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("", 20, "-"));
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("* Expected", 20, " "));
+ builder.append("\n");
+ builder.append("list size : " + expacted.size());
+ builder.append("\n");
+ for(Entity entity : expacted) {
+ builder.append(entity.toString());
+ builder.append("\n");
+ }
+
+ builder.append("\n");
+ builder.append(StringUtils.rightPad("* Actually", 20, " "));
+ builder.append("\n");
+ builder.append("list size : " + actually.size());
+ builder.append("\n");
+ for(Entity entity : actually) {
+ builder.append(entity.toString());
+ builder.append("\n");
+ }
+
+ builder.append(StringUtils.rightPad("", 20, "-"));
+ builder.append("\n");
+ return builder.toString();
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
index 0000000,06341d6..b99038d
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryRunner.java
@@@ -1,0 -1,28 +1,31 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
-import java.util.List;
+ import org.apache.usergrid.persistence.Entity;
+
++import java.util.List;
++
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ public interface QueryRunner {
+ public boolean setup();
+ public List<Entity> execute(String query);
+ public List<Entity> execute(String query, int limit);
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
index 0000000,8b14737..6f7b9e6
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidationConfiguration.java
@@@ -1,0 -1,74 +1,94 @@@
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
++ *
++ * http://www.apache.org/licenses/LICENSE-2.0
++ *
++ * Unless required by applicable law or agreed to in writing, software
++ * distributed under the License is distributed on an "AS IS" BASIS,
++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
++ * See the License for the specific language governing permissions and
++ * limitations under the License.
++ */
+ package org.apache.usergrid.query.validator;
+
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.utils.InflectionUtils;
+
+ import java.util.List;
+
++/**
++ * @author Sungju Jin
++ */
+ public class QueryValidationConfiguration {
+
+ String org;
+ String app;
+ String endpointUri;
+ String email;
+ String password;
+ String collection;
+ List<Entity> entities;
+
+ public String getCollection() {
+ return collection;
+ }
+
+ public void setCollection(String collection) {
+ String pluralizeName = InflectionUtils.pluralize(collection);
+ this.collection = pluralizeName;
+ }
+
+ public String getOrg() {
+ return org;
+ }
+
+ public void setOrg(String org) {
+ this.org = org;
+ }
+
+ public String getApp() {
+ return app;
+ }
+
+ public void setApp(String app) {
+ this.app = app;
+ }
+
+ public String getEndpointUri() {
+ return endpointUri;
+ }
+
+ public void setEndpointUri(String endpointUri) {
+ this.endpointUri = endpointUri;
+ }
+
+ public List<Entity> getEntities() {
+ return entities;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
index 0000000,180a8e5..4d46950
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/QueryValidator.java
@@@ -1,0 -1,77 +1,78 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
+ import org.springframework.beans.factory.annotation.Autowired;
+ import org.springframework.stereotype.Component;
+ import org.apache.usergrid.persistence.Entity;
+
+ import java.util.List;
+
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ @Component
+ public class QueryValidator {
+
+ QueryValidationConfiguration configuration;
+ @Autowired
+ ApiServerRunner api;
+ @Autowired
+ SqliteRunner sql;
+
+ public QueryValidator() {
+ }
+
+ public QueryValidator(QueryValidationConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public boolean setup() {
+ return api.setup() && sql.setup();
+ }
+
+ public QueryResponse execute(QueryRequest request) {
++ return execute(request, new DefaultQueryResultsMatcher());
++ }
++
++ public QueryResponse execute(QueryRequest request, QueryResultsMatcher matcher) {
+ List<Entity> sqlEntities = sql.execute(request.getDbQuery());
+ List<Entity> apiEntities = api.execute(request.getApiQuery().getQuery(), request.getApiQuery().getLimit());
- boolean equals = false;
- if( request.isIgnoreOrdering() ) {
- equals = sqlEntities.size() == apiEntities.size();
- } else {
- equals = sqlEntities.equals(apiEntities);
- }
++ boolean equals = matcher.equals(sqlEntities, apiEntities);
+
+ QueryResponse response = new QueryResponse();
+ response.setResult(equals);
+ response.setExpacted(sqlEntities);
+ response.setActually(apiEntities);
+ return response;
+ }
+
+ public void setConfiguration(QueryValidationConfiguration configuration) {
+ this.configuration = configuration;
+ sql.setCollection(configuration.getCollection());
+ sql.setEntities(configuration.getEntities());
+
+ api.setOrg(configuration.getOrg());
+ api.setApp(configuration.getApp());
+ api.setBaseUri(configuration.getEndpointUri());
+ api.setCollection(configuration.getCollection());
+ api.setEntities(configuration.getEntities());
+ api.setEmail(configuration.getEmail());
+ api.setPassword(configuration.getPassword());
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
index 0000000,a1932a0..7c7aa55
mode 000000,100644..100644
--- a/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
+++ b/stack/query-validator/src/main/java/org/apache/usergrid/query/validator/SqliteRunner.java
@@@ -1,0 -1,160 +1,193 @@@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
++/**
++ * Licensed to the Apache Software Foundation (ASF) under one
++ * or more contributor license agreements. See the NOTICE file
++ * distributed with this work for additional information
++ * regarding copyright ownership. The ASF licenses this file
++ * to you under the Apache License, Version 2.0 (the
++ * "License"); you may not use this file except in compliance
++ * with the License. You may obtain a copy of the License at
+ *
- * http://www.apache.org/licenses/LICENSE-2.0
++ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
- ******************************************************************************/
++ */
+ package org.apache.usergrid.query.validator;
+
+ import org.apache.commons.lang.StringUtils;
+ import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.core.RowMapper;
+ import org.springframework.stereotype.Component;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.Schema;
+
+ import java.sql.ResultSet;
+ import java.sql.ResultSetMetaData;
+ import java.sql.SQLException;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.logging.Logger;
++import javax.swing.tree.RowMapper;
++import org.usergrid.query.validator.QueryEntity;
++import org.usergrid.query.validator.QueryRunner;
+
+ /**
- * @author Sung-ju Jin(realbeast)
++ * @author Sungju Jin
+ */
+ @Component
+ public class SqliteRunner implements QueryRunner {
+
+ private Logger logger = Logger.getLogger(SqliteRunner.class.getName());
+
+ @Autowired
+ private JdbcTemplate jdbcTemplate;
+ private String collection;
+ private List<Entity> entities;
+
+ @Override
+ public boolean setup() {
+ createTable();
+ insertDatas();
+
+ return true;
+ }
+
+ private void insertDatas() {
+ for( Entity entity : entities ) {
+ insertData(entity);
+ }
+ }
+
+ private void insertData(Entity entity) {
+ StringBuilder feilds = new StringBuilder();
+ StringBuilder values = new StringBuilder();
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ feilds.append(key);
+ feilds.append(",");
+
- Object value = entity.getProperty(key);
- Class type = value.getClass();
++ Class type = null;
++ try
++ {
++ type = entity.getProperty(key).getClass();
++ } catch (NullPointerException ne) {
++ type = entity.getDynamicProperties().get(key).getClass();
++ }
++
++ Object value = null;
++ if(StringUtils.equals("name",key)) {
++ value = entity.getName();
++ } else {
++ value = entity.getProperty(key);
++ }
++ if( type == Boolean.class ) {
++ if((Boolean)value) {
++ value = 1;
++ } else {
++ value = 0;
++ }
++ }
++
+ String sqlType = getSqlDatatype(type);
+ if( StringUtils.equals("TEXT", sqlType) ) {
+ values.append("'");
+ values.append(value);
+ values.append("'");
+ } else {
+ values.append(value);
+ }
+ values.append(",");
+ }
+ feilds.deleteCharAt(feilds.length()-1);
+ values.deleteCharAt(values.length()-1);
+
+ StringBuilder builder = new StringBuilder();
+ builder.append("INSERT INTO ");
+ builder.append(collection);
+ builder.append("(");
+ builder.append(feilds);
+ builder.append(")");
+ builder.append(" VALUES(");
+ builder.append(values);
+ builder.append(")");
+ logger.info(builder.toString());
+ jdbcTemplate.execute(builder.toString());
+ }
+
+ private void createTable() {
+ Entity entity = entities.get(0);
+ StringBuilder builder = new StringBuilder();
+ builder.append("CREATE TABLE ");
+ builder.append(collection);
+ builder.append("(");
+ Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
+ for(String key : properties.keySet()) {
+ builder.append(key);
+ builder.append(" ");
+
- Class type = entity.getProperty(key).getClass();
++ Class type = null;
++ try
++ {
++ type = entity.getProperty(key).getClass();
++ } catch (NullPointerException ne) {
++ type = entity.getDynamicProperties().get(key).getClass();
++ }
++
+ String sqlType = getSqlDatatype(type);
+ builder.append(sqlType);
+ builder.append(",");
+ }
+ builder.deleteCharAt(builder.length()-1);
+ builder.append(")");
+
+ jdbcTemplate.execute("DROP TABLE IF EXISTS " + collection);
+ logger.info(builder.toString());
+ jdbcTemplate.execute(builder.toString());
+ }
+
+ @Override
+ public List<Entity> execute(String query) {
+ List<Entity> entities = jdbcTemplate.query(query, new RowMapper<Entity>() {
+ @Override
+ public Entity mapRow(ResultSet rs, int i) throws SQLException {
+ ResultSetMetaData rsmd = rs.getMetaData();
+ Entity entity = new QueryEntity();
+ for( int j = 1 ; j <= rsmd.getColumnCount() ; j++) {
+ entity.setProperty(rsmd.getColumnName(j), rs.getObject(j));
+ }
+ return entity;
+ }
+ });
+ return entities;
+ }
+
+ @Override
+ public List<Entity> execute(String query, int limit) {
+ return execute(query);
+ }
+
+ // based on sqlite (http://www.sqlite.org/datatype3.html)
+ private String getSqlDatatype(Class clz) {
++ if ( clz == null )
++ return "TEXT";
++
+ if( clz == Integer.class || clz == Long.class || clz == Boolean.class ) {
+ return "INTEGER";
+ } else if( clz == Double.class ) {
- return "REAL";
++ return "REAL";
+ } else if( clz == Byte.class ) {
+ return "BLOB";
+ }
+ return "TEXT";
+ }
+
+ public void setCollection(String collection) {
+ this.collection = collection;
+ }
+
+ public void setEntities(List<Entity> entities) {
+ this.entities = entities;
+ }
+ }
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3ed72f1e/stack/rest/pom.xml
----------------------------------------------------------------------
[14/50] [abbrv] finished fleshing out Client tests with a few
exceptions.
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/8dcc1de8/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index f7b4d36..4d2b953 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
-/*! usergrid@0.0.0 2014-02-10 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutC
allback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_no
t_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prot
otype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Enti
ty(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=va
lue,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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.acc
ess_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.na
me,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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.set
Token(data.access_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.key
s(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntit
y=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unsh
ift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){v
ar endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)retu
rn void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._clien
t.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get
("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof call
back&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"
==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connectio
n,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterat
or=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.rese
tEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
+/*! usergrid@0.0.0 2014-02-11 */
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();
uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","
no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.rest
oreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options
);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof St
orage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={cl
ient:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"func
tion"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"=
=typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid
.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===
type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.En
tity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=
this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(op
tions,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=th
is,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.follow
ing=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user ro
les"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entit
y.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{}
,this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("functi
on"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=func
tion(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._p
ath=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.t
ype,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed"
,options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.counter
s=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callba
ck){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});para
ms.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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.enti
ties[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);else{var endpoi
nt=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBy
tes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)return callback.call(self,err,folder);va
r endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}
function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.
duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
[16/50] [abbrv] git commit: Fleshed out tests for collections and
fixed a couple of bugs along the way.
Posted by sn...@apache.org.
Fleshed out tests for collections and fixed a couple of bugs along the way.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/421793ad
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/421793ad
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/421793ad
Branch: refs/heads/optimistic-tx-semantics
Commit: 421793ad3fdfd6e13c99ccb41af0b9a80dab4be5
Parents: 8dcc1de
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 02:39:16 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 02:39:16 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/lib/modules/Collection.js | 10 +-
sdks/html5-javascript/tests/mocha/test.js | 101 +++++++++++++------
sdks/html5-javascript/usergrid.js | 2 +-
sdks/html5-javascript/usergrid.min.js | 2 +-
4 files changed, 79 insertions(+), 36 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/421793ad/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
index 5173fc9..2fd1092 100644
--- a/sdks/html5-javascript/lib/modules/Collection.js
+++ b/sdks/html5-javascript/lib/modules/Collection.js
@@ -217,12 +217,12 @@ Usergrid.Collection.prototype.destroyEntity = function (entity, callback) {
callback(err, data);
}
} else {
- //destroy was good, so repopulate the collection
- self.fetch(callback);
+ //destroy was good, so repopulate the collection
+ self.fetch(callback);
}
});
- //remove entity from the local store
- this.removeEntity(entity);
+ //remove entity from the local store
+ this.removeEntity(entity);
};
@@ -250,7 +250,7 @@ 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;
+ return callback(null, listItem);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/421793ad/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index be4bdf6..e430c02 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -570,10 +570,9 @@ describe('Usergrid Client', function() {
type: 'dogs',
name: 'Rocky'
}
- client.createEntity(options, function(err, entity) {
+ dog=new Usergrid.Entity({client:client,data:options});
+ dog.save(function(err, entity) {
assert(!err, "dog not created");
- dog = entity;
- console.log("AFTER CREATE", dog.get());
done();
});
});
@@ -606,7 +605,6 @@ describe('Usergrid Client', function() {
}
//set is additive, so previously set properties are not overwritten
dog.set(data);
- console.log("BEFORE SAVE", dog.get());
//finally, call save on the object to save it back to the database
dog.save(function(err) {
assert(!err, "dog not saved");
@@ -630,14 +628,6 @@ describe('Usergrid Client', function() {
var client = getClient();
var dog, dogs = {};
- function loop(done) {
- while (dogs.hasNextEntity()) {
- //get a reference to the dog
- dog = dogs.getNextEntity();
- console.log(dog.get('name'));
- }
- if (done) done();
- }
before(function(done) {
console.log("remove existing dogs");
//Make sure our dog doesn't already exist
@@ -674,17 +664,15 @@ describe('Usergrid Client', function() {
});
it('should CREATE a new dogs collection', function(done) {
var options = {
+ client:client,
type: 'dogs',
qs: {
ql: 'order by index'
}
}
-
- client.createCollection(options, function(err, data) {
- assert(!err, "could not create dogs collection: " + data.error_description);
- dogs = data;
- done();
- });
+ dogs=new Usergrid.Collection(options);
+ assert(dogs, "could not create dogs collection");
+ done();
});
it('should CREATE dogs in the collection', function(done) {
this.timeout(10000);
@@ -696,7 +684,7 @@ describe('Usergrid Client', function() {
name: 'dog' + dogNum,
index: y
}
- client.createEntity(options, function(err, dog) {
+ dogs.addEntity(options, function(err, dog) {
console.log(err, dog);
assert(!err, "dog not created");
if (dogNum === totalDogs) {
@@ -706,7 +694,12 @@ describe('Usergrid Client', function() {
})
});
it('should RETRIEVE dogs from the collection', function(done) {
- loop(done);
+ while (dogs.hasNextEntity()) {
+ //get a reference to the dog
+ dog = dogs.getNextEntity();
+ console.log(dog.get('name'));
+ }
+ if (done) done();
});
it('should RETRIEVE the next page of dogs from the collection', function(done) {
if (dogs.hasNextPage()) {
@@ -717,15 +710,65 @@ describe('Usergrid Client', function() {
done();
}
});
- it('should RETRIEVE the previous page of dogs from the collection', function(done) {
- if (dogs.hasPreviousPage()) {
- dogs.getPreviousPage(function(err) {
- loop(done);
- });
- } else {
- done();
- }
- });
+ it('should RETRIEVE the previous page of dogs from the collection', function(done) {
+ if (dogs.hasPreviousPage()) {
+ dogs.getPreviousPage(function(err) {
+ loop(done);
+ });
+ } else {
+ done();
+ }
+ });
+ it('should RETRIEVE an entity by UUID.', function(done) {
+ var uuid=dogs.getFirstEntity().get("uuid")
+ dogs.getEntityByUUID(uuid,function(err, data){
+ assert(!err, "getEntityByUUID returned an error.");
+ assert(uuid==data.get("uuid"), "We didn't get the dog we asked for.");
+ done();
+ })
+ });
+ it('should RETRIEVE the first entity from the collection', function() {
+ assert(dogs.getFirstEntity(), "Could not retrieve the first dog");
+ });
+ it('should RETRIEVE the last entity from the collection', function() {
+ assert(dogs.getLastEntity(), "Could not retrieve the last dog");
+ });
+ it('should reset the paging', function() {
+ dogs.resetPaging();
+ assert(!dogs.hasPreviousPage(), "Could not resetPaging");
+ });
+ it('should reset the entity pointer', function() {
+ dogs.resetEntityPointer();
+ assert(!dogs.hasPrevEntity(), "Could not reset the pointer");
+ assert(dogs.hasNextEntity(), "Dog has no more entities");
+ assert(dogs.getNextEntity(), "Could not retrieve the next dog");
+ });
+ it('should RETRIEVE the next entity from the collection', function() {
+ assert(dogs.hasNextEntity(), "Dog has no more entities");
+ assert(dogs.getNextEntity(), "Could not retrieve the next dog");
+ });
+ it('should RETRIEVE the previous entity from the collection', function() {
+ assert(dogs.getNextEntity(), "Could not retrieve the next dog");
+ assert(dogs.hasPrevEntity(), "Dogs has no previous entities");
+ assert(dogs.getPrevEntity(), "Could not retrieve the previous dog");
+ });
+ it('should DELETE the entities from the collection', function(done) {
+ this.timeout(10000);
+ function remove(){
+ if(dogs.hasNextEntity()){
+ dogs.destroyEntity(dogs.getNextEntity(),function(err, data){
+ assert(!err, "Could not destroy dog.");
+ remove();
+ })
+ }else if(dogs.hasNextPage()){
+ dogs.getNextPage();
+ remove();
+ }else{
+ done();
+ }
+ }
+ remove();
+ });
});
describe('Usergrid Counters', function() {
var counter;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/421793ad/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index d8a888f..ff83f6c 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -2115,7 +2115,7 @@ 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;
+ return callback(null, listItem);
}
}
//get the entity from the database
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/421793ad/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index 4d2b953..c93af87 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-11 */
function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();
uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","
no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.rest
oreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options
);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof St
orage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={cl
ient:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"func
tion"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"=
=typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid
.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===
type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.En
tity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=
this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(op
tions,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=th
is,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.follow
ing=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user ro
les"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entit
y.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{}
,this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("functi
on"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
-user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=func
tion(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._p
ath=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.t
ype,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed"
,options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.counter
s=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callba
ck){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});para
ms.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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.enti
ties[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);else{var endpoi
nt=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBy
tes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)return callback.call(self,err,folder);va
r endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}
function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.
duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key]
;if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.get
PrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(o
ptions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={ty
pe:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+thi
s._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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",thi
s._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function
(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].j
oin("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&sel
f.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);
else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sDa
ta){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):doCallback(callback,[null,self],self)};var fr=new FileReader;fr.onload=functio
n(){var binary=fr.result;xhr.overrideMimeType("application/octet-stream"),setTimeout(function(){xhr.sendAsBinary(binary)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.excep
tion=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.time
stamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
[18/50] [abbrv] git commit: rebasing from usergrid master
Posted by sn...@apache.org.
rebasing from usergrid master
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/7b9048ca
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/7b9048ca
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/7b9048ca
Branch: refs/heads/optimistic-tx-semantics
Commit: 7b9048cac746b830df0c61ceab3637ef6ccb8b39
Parents: 421793a bc3dfba
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 10:59:36 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 10:59:36 2014 -0500
----------------------------------------------------------------------
.gitignore | 5 +-
README.md | 29 +
portal/Gruntfile.js | 40 +-
portal/config.js | 2 +-
portal/css/main.css | 244 +-
portal/js/app-overview/getting-started.html | 30 +-
portal/js/global/page-controller.js | 10 +-
portal/js/libs/usergrid.sdk.js | 4 +-
portal/tests/protractor/applications.spec.js | 6 +-
portal/tests/protractor/forgotPassword.spec.js | 5 +
portal/tests/protractor/profile.spec.js | 14 +-
portal/tests/protractor/users.spec.js | 5 +-
portal/tests/protractor/util.js | 34 +-
portal/tests/protractorConf.js | 11 +-
sdks/android/doc/allclasses-frame.html | 110 +-
sdks/android/doc/allclasses-noframe.html | 110 +-
sdks/android/doc/constant-values.html | 859 +-
sdks/android/doc/deprecated-list.html | 237 +-
sdks/android/doc/help-doc.html | 419 +-
sdks/android/doc/index-all.html | 371 +
sdks/android/doc/index-files/index-1.html | 209 -
sdks/android/doc/index-files/index-10.html | 151 -
sdks/android/doc/index-files/index-11.html | 154 -
sdks/android/doc/index-files/index-12.html | 151 -
sdks/android/doc/index-files/index-13.html | 217 -
sdks/android/doc/index-files/index-14.html | 268 -
sdks/android/doc/index-files/index-15.html | 204 -
sdks/android/doc/index-files/index-16.html | 151 -
sdks/android/doc/index-files/index-17.html | 466 -
sdks/android/doc/index-files/index-18.html | 184 -
sdks/android/doc/index-files/index-19.html | 157 -
sdks/android/doc/index-files/index-2.html | 193 -
sdks/android/doc/index-files/index-20.html | 239 -
sdks/android/doc/index-files/index-21.html | 154 -
sdks/android/doc/index-files/index-3.html | 161 -
sdks/android/doc/index-files/index-4.html | 166 -
sdks/android/doc/index-files/index-5.html | 151 -
sdks/android/doc/index-files/index-6.html | 547 -
sdks/android/doc/index-files/index-7.html | 145 -
sdks/android/doc/index-files/index-8.html | 160 -
sdks/android/doc/index-files/index-9.html | 145 -
sdks/android/doc/index.html | 89 +-
.../apache/usergrid/android/client/Client.html | 989 +
.../client/callbacks/ApiResponseCallback.html | 224 +
.../client/callbacks/ClientAsyncTask.html | 338 +
.../client/callbacks/ClientCallback.html | 227 +
.../callbacks/DeviceRegistrationCallback.html | 220 +
.../callbacks/GroupsRetrievedCallback.html | 220 +
.../client/callbacks/QueryResultsCallback.html | 220 +
.../class-use/ApiResponseCallback.html | 282 +
.../callbacks/class-use/ClientAsyncTask.html | 117 +
.../callbacks/class-use/ClientCallback.html | 180 +
.../class-use/DeviceRegistrationCallback.html | 171 +
.../class-use/GroupsRetrievedCallback.html | 160 +
.../class-use/QueryResultsCallback.html | 219 +
.../android/client/callbacks/package-frame.html | 28 +
.../client/callbacks/package-summary.html | 166 +
.../android/client/callbacks/package-tree.html | 145 +
.../android/client/callbacks/package-use.html | 178 +
.../android/client/class-use/Client.html | 117 +
.../usergrid/android/client/package-frame.html | 20 +
.../android/client/package-summary.html | 137 +
.../usergrid/android/client/package-tree.html | 134 +
.../usergrid/android/client/package-use.html | 117 +
.../android/client/utils/DeviceUuidFactory.html | 352 +
.../android/client/utils/ObjectUtils.html | 258 +
.../utils/class-use/DeviceUuidFactory.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../android/client/utils/package-frame.html | 21 +
.../android/client/utils/package-summary.html | 142 +
.../android/client/utils/package-tree.html | 131 +
.../android/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/android/doc/overview-frame.html | 71 +-
sdks/android/doc/overview-summary.html | 280 +-
sdks/android/doc/overview-tree.html | 301 +-
sdks/android/doc/package-list | 8 +-
sdks/android/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/android/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/android/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/android/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/android/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/android/doc/stylesheet.css | 501 +-
.../0.0.6/usergrid-java-client-0.0.6.jar | Bin 0 -> 46389 bytes
.../0.0.6/usergrid-java-client-0.0.6.jar.sha1 | 1 +
.../0.0.6/usergrid-java-client-0.0.6.pom | 95 +
.../0.0.6/usergrid-java-client-0.0.6.pom.sha1 | 1 +
.../maven-metadata-local.xml | 12 +
sdks/android/pom.xml | 31 +-
.../apache/usergrid/android/client/Client.java | 590 +
.../client/callbacks/ApiResponseCallback.java | 10 +
.../client/callbacks/ClientAsyncTask.java | 38 +
.../client/callbacks/ClientCallback.java | 9 +
.../callbacks/DeviceRegistrationCallback.java | 9 +
.../callbacks/GroupsRetrievedCallback.java | 13 +
.../client/callbacks/QueryResultsCallback.java | 9 +
.../android/client/utils/DeviceUuidFactory.java | 154 +
.../android/client/utils/ObjectUtils.java | 20 +
.../org/usergrid/android/client/Client.java | 590 -
.../client/callbacks/ApiResponseCallback.java | 10 -
.../client/callbacks/ClientAsyncTask.java | 38 -
.../client/callbacks/ClientCallback.java | 9 -
.../callbacks/DeviceRegistrationCallback.java | 9 -
.../callbacks/GroupsRetrievedCallback.java | 13 -
.../client/callbacks/QueryResultsCallback.java | 9 -
.../android/client/utils/DeviceUuidFactory.java | 154 -
.../android/client/utils/ObjectUtils.java | 20 -
sdks/java/doc/allclasses-frame.html | 123 +-
sdks/java/doc/allclasses-noframe.html | 123 +-
sdks/java/doc/constant-values.html | 1437 +-
sdks/java/doc/deprecated-list.html | 237 +-
sdks/java/doc/help-doc.html | 419 +-
sdks/java/doc/index-all.html | 1299 +
sdks/java/doc/index-files/index-1.html | 209 -
sdks/java/doc/index-files/index-10.html | 151 -
sdks/java/doc/index-files/index-11.html | 154 -
sdks/java/doc/index-files/index-12.html | 151 -
sdks/java/doc/index-files/index-13.html | 217 -
sdks/java/doc/index-files/index-14.html | 268 -
sdks/java/doc/index-files/index-15.html | 204 -
sdks/java/doc/index-files/index-16.html | 151 -
sdks/java/doc/index-files/index-17.html | 466 -
sdks/java/doc/index-files/index-18.html | 184 -
sdks/java/doc/index-files/index-19.html | 157 -
sdks/java/doc/index-files/index-2.html | 193 -
sdks/java/doc/index-files/index-20.html | 239 -
sdks/java/doc/index-files/index-21.html | 154 -
sdks/java/doc/index-files/index-3.html | 161 -
sdks/java/doc/index-files/index-4.html | 166 -
sdks/java/doc/index-files/index-5.html | 151 -
sdks/java/doc/index-files/index-6.html | 547 -
sdks/java/doc/index-files/index-7.html | 145 -
sdks/java/doc/index-files/index-8.html | 160 -
sdks/java/doc/index-files/index-9.html | 145 -
sdks/java/doc/index.html | 89 +-
.../usergrid/java/client/Client.Query.html | 238 +
.../java/client/Client.QueuePosition.html | 381 +
.../org/apache/usergrid/java/client/Client.html | 1652 +
.../java/client/class-use/Client.Query.html | 246 +
.../client/class-use/Client.QueuePosition.html | 192 +
.../usergrid/java/client/class-use/Client.html | 175 +
.../entities/Activity.ActivityCollection.html | 408 +
.../entities/Activity.ActivityObject.html | 720 +
.../client/entities/Activity.MediaLink.html | 434 +
.../usergrid/java/client/entities/Activity.html | 1449 +
.../usergrid/java/client/entities/Device.html | 387 +
.../usergrid/java/client/entities/Entity.html | 599 +
.../usergrid/java/client/entities/Group.html | 427 +
.../usergrid/java/client/entities/Message.html | 641 +
.../usergrid/java/client/entities/User.html | 707 +
.../class-use/Activity.ActivityCollection.html | 117 +
.../class-use/Activity.ActivityObject.html | 231 +
.../entities/class-use/Activity.MediaLink.html | 191 +
.../client/entities/class-use/Activity.html | 203 +
.../java/client/entities/class-use/Device.html | 169 +
.../java/client/entities/class-use/Entity.html | 415 +
.../java/client/entities/class-use/Group.html | 159 +
.../java/client/entities/class-use/Message.html | 183 +
.../java/client/entities/class-use/User.html | 248 +
.../java/client/entities/package-frame.html | 28 +
.../java/client/entities/package-summary.html | 169 +
.../java/client/entities/package-tree.html | 141 +
.../java/client/entities/package-use.html | 219 +
.../java/client/exception/ClientException.html | 263 +
.../exception/class-use/ClientException.html | 117 +
.../java/client/exception/package-frame.html | 20 +
.../java/client/exception/package-summary.html | 137 +
.../java/client/exception/package-tree.html | 142 +
.../java/client/exception/package-use.html | 117 +
.../usergrid/java/client/package-frame.html | 28 +
.../usergrid/java/client/package-summary.html | 167 +
.../usergrid/java/client/package-tree.html | 146 +
.../usergrid/java/client/package-use.html | 158 +
.../java/client/response/AggregateCounter.html | 316 +
.../client/response/AggregateCounterSet.html | 444 +
.../java/client/response/ApiResponse.html | 1148 +
.../client/response/ClientCredentialsInfo.html | 316 +
.../java/client/response/QueueInfo.html | 297 +
.../response/class-use/AggregateCounter.html | 191 +
.../response/class-use/AggregateCounterSet.html | 170 +
.../client/response/class-use/ApiResponse.html | 365 +
.../class-use/ClientCredentialsInfo.html | 170 +
.../client/response/class-use/QueueInfo.html | 187 +
.../java/client/response/package-frame.html | 24 +
.../java/client/response/package-summary.html | 151 +
.../java/client/response/package-tree.html | 134 +
.../java/client/response/package-use.html | 178 +
.../usergrid/java/client/utils/JsonUtils.html | 480 +
.../usergrid/java/client/utils/MapUtils.html | 260 +
.../usergrid/java/client/utils/ObjectUtils.html | 258 +
.../usergrid/java/client/utils/UrlUtils.html | 314 +
.../java/client/utils/class-use/JsonUtils.html | 117 +
.../java/client/utils/class-use/MapUtils.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../java/client/utils/class-use/UrlUtils.html | 117 +
.../java/client/utils/package-frame.html | 23 +
.../java/client/utils/package-summary.html | 147 +
.../java/client/utils/package-tree.html | 133 +
.../usergrid/java/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/java/doc/overview-frame.html | 73 +-
sdks/java/doc/overview-summary.html | 288 +-
sdks/java/doc/overview-tree.html | 331 +-
sdks/java/doc/package-list | 10 +-
sdks/java/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/java/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/java/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/java/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/java/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/java/doc/serialized-form.html | 134 +
sdks/java/doc/stylesheet.css | 501 +-
sdks/java/pom.xml | 182 +-
.../org/apache/usergrid/java/client/Client.java | 1276 +
.../usergrid/java/client/entities/Activity.java | 627 +
.../usergrid/java/client/entities/Device.java | 52 +
.../usergrid/java/client/entities/Entity.java | 175 +
.../usergrid/java/client/entities/Group.java | 63 +
.../usergrid/java/client/entities/Message.java | 132 +
.../usergrid/java/client/entities/User.java | 142 +
.../java/client/exception/ClientException.java | 40 +
.../java/client/response/AggregateCounter.java | 36 +
.../client/response/AggregateCounterSet.java | 95 +
.../java/client/response/ApiResponse.java | 405 +
.../client/response/ClientCredentialsInfo.java | 42 +
.../java/client/response/QueueInfo.java | 28 +
.../usergrid/java/client/utils/JsonUtils.java | 166 +
.../usergrid/java/client/utils/MapUtils.java | 23 +
.../usergrid/java/client/utils/ObjectUtils.java | 20 +
.../usergrid/java/client/utils/UrlUtils.java | 108 +
.../java/org/usergrid/java/client/Client.java | 1276 -
.../usergrid/java/client/entities/Activity.java | 627 -
.../usergrid/java/client/entities/Device.java | 52 -
.../usergrid/java/client/entities/Entity.java | 175 -
.../usergrid/java/client/entities/Group.java | 63 -
.../usergrid/java/client/entities/Message.java | 132 -
.../org/usergrid/java/client/entities/User.java | 142 -
.../java/client/exception/ClientException.java | 40 -
.../java/client/response/AggregateCounter.java | 36 -
.../client/response/AggregateCounterSet.java | 95 -
.../java/client/response/ApiResponse.java | 405 -
.../client/response/ClientCredentialsInfo.java | 42 -
.../java/client/response/QueueInfo.java | 28 -
.../usergrid/java/client/utils/JsonUtils.java | 166 -
.../usergrid/java/client/utils/MapUtils.java | 23 -
.../usergrid/java/client/utils/ObjectUtils.java | 20 -
.../usergrid/java/client/utils/UrlUtils.java | 108 -
sdks/nodejs/lib/usergrid.js | 187 +
sdks/nodejs/test.js | 94 +-
.../lib/vendor/Apigee/Usergrid/Collection.php | 18 +-
sdks/php/lib/vendor/Apigee/Usergrid/Entity.php | 90 +-
stack/README.md | 4 +-
stack/build-tools/pom.xml | 4 +-
.../src/main/resources/usergrid/checkstyle.xml | 2 +-
stack/config/pom.xml | 4 +-
stack/config/src/main/resources/log4j.xml | 14 +-
.../main/resources/usergrid-default.properties | 2 +-
.../config/src/test/resources/log4j.properties | 14 +-
stack/config/src/test/resources/log4j.xml | 4 +-
stack/core/pom.xml | 14 +-
.../persistence/query/tree/QueryFilter.g | 311 +
.../persistence/query/tree/QueryFilter.g | 311 -
.../java/org/apache/usergrid/batch/AppArgs.java | 57 +
.../java/org/apache/usergrid/batch/Job.java | 20 +
.../org/apache/usergrid/batch/JobExecution.java | 91 +
.../apache/usergrid/batch/JobExecutionImpl.java | 202 +
.../org/apache/usergrid/batch/JobFactory.java | 19 +
.../usergrid/batch/JobNotFoundException.java | 23 +
.../org/apache/usergrid/batch/JobRuntime.java | 40 +
.../usergrid/batch/JobRuntimeException.java | 49 +
.../usergrid/batch/UsergridJobFactory.java | 37 +
.../apache/usergrid/batch/job/OnlyOnceJob.java | 85 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../usergrid/batch/repository/JobAccessor.java | 36 +
.../batch/repository/JobDescriptor.java | 80 +
.../usergrid/batch/repository/package-info.java | 18 +
.../org/apache/usergrid/batch/service/App.java | 70 +
.../usergrid/batch/service/JobListener.java | 50 +
.../batch/service/JobRuntimeService.java | 49 +
.../batch/service/JobSchedulerService.java | 315 +
.../batch/service/SchedulerService.java | 54 +
.../batch/service/SchedulerServiceImpl.java | 428 +
.../usergrid/batch/service/package-info.java | 18 +
.../hazelcast/HazelcastLifecycleMonitor.java | 78 +
.../apache/usergrid/count/AbstractBatcher.java | 175 +
.../apache/usergrid/count/BatchSubmitter.java | 30 +
.../java/org/apache/usergrid/count/Batcher.java | 35 +
.../usergrid/count/CassandraCounterStore.java | 100 +
.../usergrid/count/CassandraSubmitter.java | 77 +
.../apache/usergrid/count/CountProducer.java | 25 +
.../CounterProcessingUnavailableException.java | 38 +
.../org/apache/usergrid/count/CounterStore.java | 30 +
.../apache/usergrid/count/SimpleBatcher.java | 40 +
.../usergrid/count/Slf4JBatchSubmitter.java | 77 +
.../org/apache/usergrid/count/common/Count.java | 139 +
.../usergrid/count/common/CountSerDeUtils.java | 51 +
.../common/CountTransportSerDeException.java | 38 +
.../org/apache/usergrid/count/package-info.java | 2 +
.../usergrid/exception/JsonReadException.java | 27 +
.../usergrid/exception/JsonWriteException.java | 27 +
.../exception/NotImplementedException.java | 58 +
.../java/org/apache/usergrid/locking/Lock.java | 44 +
.../org/apache/usergrid/locking/LockHelper.java | 51 +
.../apache/usergrid/locking/LockManager.java | 40 +
.../usergrid/locking/LockPathBuilder.java | 68 +
.../locking/cassandra/HectorLockImpl.java | 85 +
.../cassandra/HectorLockManagerImpl.java | 141 +
.../locking/exception/UGLockException.java | 49 +
.../usergrid/locking/noop/NoOpLockImpl.java | 61 +
.../locking/noop/NoOpLockManagerImpl.java | 40 +
.../locking/singlenode/SingleNodeLockImpl.java | 70 +
.../singlenode/SingleNodeLockManagerImpl.java | 93 +
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 +
.../locking/zookeeper/ZookeeperLockImpl.java | 87 +
.../org/apache/usergrid/mq/CounterQuery.java | 313 +
.../java/org/apache/usergrid/mq/Message.java | 512 +
.../main/java/org/apache/usergrid/mq/Query.java | 1857 +
.../apache/usergrid/mq/QueryFilterLexer.java | 1842 +
.../apache/usergrid/mq/QueryFilterParser.java | 1102 +
.../org/apache/usergrid/mq/QueryProcessor.java | 562 +
.../main/java/org/apache/usergrid/mq/Queue.java | 291 +
.../org/apache/usergrid/mq/QueueManager.java | 130 +
.../apache/usergrid/mq/QueueManagerFactory.java | 41 +
.../org/apache/usergrid/mq/QueuePosition.java | 59 +
.../java/org/apache/usergrid/mq/QueueQuery.java | 306 +
.../org/apache/usergrid/mq/QueueResults.java | 128 +
.../java/org/apache/usergrid/mq/QueueSet.java | 192 +
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 +
.../mq/cassandra/MessageIndexUpdate.java | 120 +
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 +
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 +
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 +
.../apache/usergrid/mq/cassandra/QueuesCF.java | 156 +
.../mq/cassandra/io/AbstractSearch.java | 358 +
.../mq/cassandra/io/ConsumerTransaction.java | 471 +
.../usergrid/mq/cassandra/io/EndSearch.java | 69 +
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 +
.../mq/cassandra/io/NoTransactionSearch.java | 132 +
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 +
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 +
.../usergrid/mq/cassandra/io/StartSearch.java | 68 +
.../usergrid/persistence/AbstractEntity.java | 341 +
.../usergrid/persistence/AggregateCounter.java | 48 +
.../persistence/AggregateCounterSet.java | 116 +
.../persistence/AssociatedEntityRef.java | 21 +
.../usergrid/persistence/CollectionRef.java | 26 +
.../persistence/ConnectedEntityRef.java | 22 +
.../usergrid/persistence/ConnectionRef.java | 34 +
.../usergrid/persistence/CounterQuery.java | 312 +
.../usergrid/persistence/CounterResolution.java | 84 +
.../usergrid/persistence/CredentialsInfo.java | 176 +
.../usergrid/persistence/DynamicEntity.java | 111 +
.../org/apache/usergrid/persistence/Entity.java | 102 +
.../usergrid/persistence/EntityFactory.java | 131 +
.../usergrid/persistence/EntityManager.java | 620 +
.../persistence/EntityManagerFactory.java | 108 +
.../persistence/EntityPropertyComparator.java | 55 +
.../apache/usergrid/persistence/EntityRef.java | 37 +
.../usergrid/persistence/EntityUtils.java | 53 +
.../apache/usergrid/persistence/Identifier.java | 226 +
.../persistence/IndexBucketLocator.java | 75 +
.../persistence/MultiQueryIterator.java | 106 +
.../persistence/PagingResultsIterator.java | 109 +
.../apache/usergrid/persistence/PathQuery.java | 115 +
.../org/apache/usergrid/persistence/Query.java | 1310 +
.../apache/usergrid/persistence/QueryUtils.java | 34 +
.../usergrid/persistence/RelationManager.java | 113 +
.../apache/usergrid/persistence/Results.java | 1294 +
.../apache/usergrid/persistence/RoleRef.java | 31 +
.../org/apache/usergrid/persistence/Schema.java | 1788 +
.../persistence/SimpleCollectionRef.java | 84 +
.../usergrid/persistence/SimpleEntityRef.java | 149 +
.../usergrid/persistence/SimpleRoleRef.java | 125 +
.../usergrid/persistence/TypedEntity.java | 37 +
.../org/apache/usergrid/persistence/Update.java | 75 +
.../annotations/EntityCollection.java | 43 +
.../annotations/EntityDictionary.java | 38 +
.../persistence/annotations/EntityProperty.java | 54 +
.../persistence/cassandra/ApplicationCF.java | 160 +
.../usergrid/persistence/cassandra/CFEnum.java | 37 +
.../cassandra/CassandraPersistenceUtils.java | 486 +
.../persistence/cassandra/CassandraService.java | 1138 +
.../cassandra/ConnectedEntityRefImpl.java | 61 +
.../cassandra/ConnectionRefImpl.java | 628 +
.../persistence/cassandra/CounterUtils.java | 400 +
.../persistence/cassandra/CursorCache.java | 121 +
.../cassandra/EntityManagerFactoryImpl.java | 411 +
.../cassandra/EntityManagerImpl.java | 2858 +
.../cassandra/EntityValueSerializer.java | 52 +
.../persistence/cassandra/GeoIndexManager.java | 323 +
.../persistence/cassandra/IndexUpdate.java | 450 +
.../persistence/cassandra/QueryProcessor.java | 720 +
.../cassandra/RelationManagerImpl.java | 2334 +
.../usergrid/persistence/cassandra/Setup.java | 206 +
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 +
.../cassandra/index/ConnectedIndexScanner.java | 281 +
.../cassandra/index/IndexBucketScanner.java | 239 +
.../index/IndexMultiBucketSetLoader.java | 138 +
.../cassandra/index/IndexScanner.java | 39 +
.../cassandra/index/NoOpIndexScanner.java | 94 +
.../cassandra/util/Slf4jTraceTagReporter.java | 47 +
.../cassandra/util/TaggedOpTimer.java | 38 +
.../persistence/cassandra/util/TimedOpTag.java | 101 +
.../cassandra/util/TraceParticipant.java | 20 +
.../persistence/cassandra/util/TraceTag.java | 77 +
.../cassandra/util/TraceTagAspect.java | 41 +
.../cassandra/util/TraceTagManager.java | 156 +
.../cassandra/util/TraceTagReporter.java | 10 +
.../usergrid/persistence/entities/Activity.java | 685 +
.../persistence/entities/Application.java | 609 +
.../usergrid/persistence/entities/Asset.java | 93 +
.../usergrid/persistence/entities/Device.java | 105 +
.../usergrid/persistence/entities/Event.java | 155 +
.../usergrid/persistence/entities/Folder.java | 93 +
.../usergrid/persistence/entities/Group.java | 168 +
.../usergrid/persistence/entities/JobData.java | 54 +
.../usergrid/persistence/entities/JobStat.java | 175 +
.../usergrid/persistence/entities/Message.java | 77 +
.../usergrid/persistence/entities/Role.java | 153 +
.../usergrid/persistence/entities/User.java | 348 +
.../ApplicationAlreadyExistsException.java | 37 +
.../DuplicateUniquePropertyExistsException.java | 52 +
.../exceptions/EntityNotFoundException.java | 45 +
.../exceptions/LockingException.java | 65 +
.../exceptions/NoFullTextIndexException.java | 50 +
.../exceptions/NoIndexException.java | 50 +
.../exceptions/PersistenceException.java | 45 +
.../PropertyTypeConversionException.java | 71 +
.../exceptions/QueryIterationException.java | 13 +
.../exceptions/QueryParseException.java | 63 +
.../exceptions/QueryTokenException.java | 52 +
.../persistence/exceptions/QueueException.java | 61 +
.../RequiredPropertyNotFoundException.java | 41 +
.../TransactionNotFoundException.java | 45 +
.../UnexpectedEntityTypeException.java | 45 +
.../persistence/geo/CollectionGeoSearch.java | 52 +
.../persistence/geo/ConnectionGeoSearch.java | 51 +
.../persistence/geo/EntityLocationRef.java | 211 +
.../EntityLocationRefDistanceComparator.java | 77 +
.../persistence/geo/GeoIndexSearcher.java | 368 +
.../persistence/geo/GeocellManager.java | 179 +
.../usergrid/persistence/geo/GeocellUtils.java | 539 +
.../geo/comparator/DoubleTupleComparator.java | 23 +
.../persistence/geo/model/BoundingBox.java | 71 +
.../persistence/geo/model/CostFunction.java | 33 +
.../geo/model/DefaultCostFunction.java | 34 +
.../usergrid/persistence/geo/model/Point.java | 58 +
.../usergrid/persistence/geo/model/Tuple.java | 24 +
.../usergrid/persistence/query/ir/AllNode.java | 54 +
.../usergrid/persistence/query/ir/AndNode.java | 43 +
.../persistence/query/ir/BooleanNode.java | 48 +
.../query/ir/EmailIdentifierNode.java | 31 +
.../query/ir/NameIdentifierNode.java | 28 +
.../persistence/query/ir/NodeVisitor.java | 78 +
.../usergrid/persistence/query/ir/NotNode.java | 62 +
.../usergrid/persistence/query/ir/OrNode.java | 52 +
.../persistence/query/ir/OrderByNode.java | 92 +
.../persistence/query/ir/QueryNode.java | 28 +
.../persistence/query/ir/QuerySlice.java | 344 +
.../persistence/query/ir/SearchVisitor.java | 254 +
.../persistence/query/ir/SliceNode.java | 167 +
.../query/ir/UuidIdentifierNode.java | 32 +
.../persistence/query/ir/WithinNode.java | 96 +
.../query/ir/result/AbstractScanColumn.java | 70 +
.../result/CollectionResultsLoaderFactory.java | 23 +
.../ir/result/ConnectionIndexSliceParser.java | 86 +
.../query/ir/result/ConnectionRefLoader.java | 65 +
.../result/ConnectionResultsLoaderFactory.java | 32 +
.../ir/result/ConnectionTypesIterator.java | 179 +
.../query/ir/result/EmptyIterator.java | 47 +
.../query/ir/result/EntityRefLoader.java | 50 +
.../query/ir/result/EntityResultsLoader.java | 46 +
.../query/ir/result/GeoIterator.java | 355 +
.../persistence/query/ir/result/IDLoader.java | 24 +
.../query/ir/result/IntersectionIterator.java | 169 +
.../query/ir/result/MergeIterator.java | 149 +
.../query/ir/result/MultiIterator.java | 54 +
.../query/ir/result/OrderByIterator.java | 252 +
.../query/ir/result/ResultIterator.java | 43 +
.../query/ir/result/ResultsLoader.java | 29 +
.../query/ir/result/ResultsLoaderFactory.java | 21 +
.../persistence/query/ir/result/ScanColumn.java | 16 +
.../query/ir/result/ScanColumnTransformer.java | 23 +
.../ir/result/SecondaryIndexSliceParser.java | 60 +
.../query/ir/result/SliceIterator.java | 241 +
.../query/ir/result/SliceParser.java | 31 +
.../query/ir/result/StaticIdIterator.java | 66 +
.../query/ir/result/SubtractionIterator.java | 108 +
.../query/ir/result/UUIDIndexSliceParser.java | 50 +
.../query/ir/result/UnionIterator.java | 267 +
.../usergrid/persistence/query/tree/.gitignore | 2 +
.../persistence/query/tree/AndOperand.java | 48 +
.../persistence/query/tree/BooleanLiteral.java | 48 +
.../persistence/query/tree/BooleanOperand.java | 48 +
.../persistence/query/tree/ContainsOperand.java | 69 +
.../query/tree/ContainsProperty.java | 57 +
.../usergrid/persistence/query/tree/Equal.java | 52 +
.../persistence/query/tree/EqualityOperand.java | 88 +
.../persistence/query/tree/FloatLiteral.java | 57 +
.../persistence/query/tree/GreaterThan.java | 52 +
.../query/tree/GreaterThanEqual.java | 56 +
.../persistence/query/tree/LessThan.java | 52 +
.../persistence/query/tree/LessThanEqual.java | 54 +
.../persistence/query/tree/Literal.java | 38 +
.../persistence/query/tree/LiteralFactory.java | 58 +
.../persistence/query/tree/LongLiteral.java | 64 +
.../persistence/query/tree/NotOperand.java | 45 +
.../persistence/query/tree/NumericLiteral.java | 24 +
.../persistence/query/tree/Operand.java | 47 +
.../persistence/query/tree/OrOperand.java | 53 +
.../persistence/query/tree/Property.java | 62 +
.../persistence/query/tree/QueryVisitor.java | 90 +
.../persistence/query/tree/StringLiteral.java | 82 +
.../persistence/query/tree/UUIDLiteral.java | 49 +
.../persistence/query/tree/WithinOperand.java | 111 +
.../persistence/query/tree/WithinProperty.java | 54 +
.../persistence/schema/CollectionInfo.java | 207 +
.../persistence/schema/DictionaryInfo.java | 117 +
.../usergrid/persistence/schema/EntityInfo.java | 299 +
.../persistence/schema/PropertyInfo.java | 218 +
.../usergrid/system/UsergridSystemMonitor.java | 95 +
.../org/apache/usergrid/utils/AESUtils.java | 84 +
.../java/org/apache/usergrid/utils/BCrypt.java | 627 +
.../org/apache/usergrid/utils/ClassUtils.java | 58 +
.../org/apache/usergrid/utils/CodecUtils.java | 45 +
.../apache/usergrid/utils/CompositeUtils.java | 54 +
.../apache/usergrid/utils/ConversionUtils.java | 765 +
.../org/apache/usergrid/utils/DateUtils.java | 88 +
.../org/apache/usergrid/utils/HttpUtils.java | 51 +
.../org/apache/usergrid/utils/IndexUtils.java | 218 +
.../apache/usergrid/utils/InflectionUtils.java | 51 +
.../org/apache/usergrid/utils/Inflector.java | 553 +
.../org/apache/usergrid/utils/JsonUtils.java | 329 +
.../org/apache/usergrid/utils/ListUtils.java | 230 +
.../org/apache/usergrid/utils/MailUtils.java | 154 +
.../org/apache/usergrid/utils/MapUtils.java | 377 +
.../org/apache/usergrid/utils/NumberUtils.java | 35 +
.../apache/usergrid/utils/PasswordUtils.java | 28 +
.../org/apache/usergrid/utils/StringUtils.java | 172 +
.../org/apache/usergrid/utils/TimeUtils.java | 88 +
.../org/apache/usergrid/utils/UUIDUtils.java | 412 +
.../java/org/apache/usergrid/utils/Version.java | 428 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../main/java/org/usergrid/batch/AppArgs.java | 57 -
.../src/main/java/org/usergrid/batch/Job.java | 20 -
.../java/org/usergrid/batch/JobExecution.java | 91 -
.../org/usergrid/batch/JobExecutionImpl.java | 202 -
.../java/org/usergrid/batch/JobFactory.java | 19 -
.../usergrid/batch/JobNotFoundException.java | 23 -
.../java/org/usergrid/batch/JobRuntime.java | 40 -
.../org/usergrid/batch/JobRuntimeException.java | 49 -
.../org/usergrid/batch/UsergridJobFactory.java | 37 -
.../org/usergrid/batch/job/OnlyOnceJob.java | 85 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../usergrid/batch/repository/JobAccessor.java | 36 -
.../batch/repository/JobDescriptor.java | 80 -
.../usergrid/batch/repository/package-info.java | 18 -
.../java/org/usergrid/batch/service/App.java | 70 -
.../org/usergrid/batch/service/JobListener.java | 50 -
.../batch/service/JobRuntimeService.java | 49 -
.../batch/service/JobSchedulerService.java | 315 -
.../batch/service/SchedulerService.java | 54 -
.../batch/service/SchedulerServiceImpl.java | 428 -
.../usergrid/batch/service/package-info.java | 18 -
.../hazelcast/HazelcastLifecycleMonitor.java | 78 -
.../org/usergrid/count/AbstractBatcher.java | 175 -
.../java/org/usergrid/count/BatchSubmitter.java | 30 -
.../main/java/org/usergrid/count/Batcher.java | 35 -
.../usergrid/count/CassandraCounterStore.java | 100 -
.../org/usergrid/count/CassandraSubmitter.java | 77 -
.../java/org/usergrid/count/CountProducer.java | 25 -
.../CounterProcessingUnavailableException.java | 38 -
.../java/org/usergrid/count/CounterStore.java | 30 -
.../java/org/usergrid/count/SimpleBatcher.java | 40 -
.../org/usergrid/count/Slf4JBatchSubmitter.java | 77 -
.../java/org/usergrid/count/common/Count.java | 139 -
.../usergrid/count/common/CountSerDeUtils.java | 51 -
.../common/CountTransportSerDeException.java | 38 -
.../java/org/usergrid/count/package-info.java | 0
.../usergrid/exception/JsonReadException.java | 27 -
.../usergrid/exception/JsonWriteException.java | 27 -
.../exception/NotImplementedException.java | 58 -
.../main/java/org/usergrid/locking/Lock.java | 44 -
.../java/org/usergrid/locking/LockHelper.java | 51 -
.../java/org/usergrid/locking/LockManager.java | 40 -
.../org/usergrid/locking/LockPathBuilder.java | 68 -
.../locking/cassandra/HectorLockImpl.java | 85 -
.../cassandra/HectorLockManagerImpl.java | 141 -
.../locking/exception/UGLockException.java | 49 -
.../org/usergrid/locking/noop/NoOpLockImpl.java | 61 -
.../locking/noop/NoOpLockManagerImpl.java | 40 -
.../locking/singlenode/SingleNodeLockImpl.java | 70 -
.../singlenode/SingleNodeLockManagerImpl.java | 93 -
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 -
.../locking/zookeeper/ZookeeperLockImpl.java | 87 -
.../main/java/org/usergrid/mq/CounterQuery.java | 314 -
.../src/main/java/org/usergrid/mq/Message.java | 512 -
.../src/main/java/org/usergrid/mq/Query.java | 1857 -
.../java/org/usergrid/mq/QueryFilterLexer.java | 1842 -
.../java/org/usergrid/mq/QueryFilterParser.java | 1102 -
.../java/org/usergrid/mq/QueryProcessor.java | 562 -
.../src/main/java/org/usergrid/mq/Queue.java | 291 -
.../main/java/org/usergrid/mq/QueueManager.java | 130 -
.../org/usergrid/mq/QueueManagerFactory.java | 41 -
.../java/org/usergrid/mq/QueuePosition.java | 59 -
.../main/java/org/usergrid/mq/QueueQuery.java | 306 -
.../main/java/org/usergrid/mq/QueueResults.java | 128 -
.../src/main/java/org/usergrid/mq/QueueSet.java | 192 -
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 -
.../mq/cassandra/MessageIndexUpdate.java | 120 -
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 -
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 -
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 -
.../org/usergrid/mq/cassandra/QueuesCF.java | 156 -
.../mq/cassandra/io/AbstractSearch.java | 358 -
.../mq/cassandra/io/ConsumerTransaction.java | 471 -
.../org/usergrid/mq/cassandra/io/EndSearch.java | 69 -
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 -
.../mq/cassandra/io/NoTransactionSearch.java | 132 -
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 -
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 -
.../usergrid/mq/cassandra/io/StartSearch.java | 68 -
.../usergrid/persistence/AbstractEntity.java | 342 -
.../usergrid/persistence/AggregateCounter.java | 48 -
.../persistence/AggregateCounterSet.java | 116 -
.../persistence/AssociatedEntityRef.java | 21 -
.../org/usergrid/persistence/CollectionRef.java | 26 -
.../persistence/ConnectedEntityRef.java | 22 -
.../org/usergrid/persistence/ConnectionRef.java | 34 -
.../org/usergrid/persistence/CounterQuery.java | 313 -
.../usergrid/persistence/CounterResolution.java | 84 -
.../usergrid/persistence/CredentialsInfo.java | 176 -
.../org/usergrid/persistence/DynamicEntity.java | 111 -
.../java/org/usergrid/persistence/Entity.java | 103 -
.../org/usergrid/persistence/EntityFactory.java | 131 -
.../org/usergrid/persistence/EntityManager.java | 620 -
.../persistence/EntityManagerFactory.java | 108 -
.../persistence/EntityPropertyComparator.java | 55 -
.../org/usergrid/persistence/EntityRef.java | 37 -
.../org/usergrid/persistence/EntityUtils.java | 53 -
.../org/usergrid/persistence/Identifier.java | 226 -
.../persistence/IndexBucketLocator.java | 75 -
.../persistence/MultiQueryIterator.java | 106 -
.../persistence/PagingResultsIterator.java | 109 -
.../org/usergrid/persistence/PathQuery.java | 115 -
.../java/org/usergrid/persistence/Query.java | 1310 -
.../org/usergrid/persistence/QueryUtils.java | 34 -
.../usergrid/persistence/RelationManager.java | 113 -
.../java/org/usergrid/persistence/Results.java | 1294 -
.../java/org/usergrid/persistence/RoleRef.java | 31 -
.../java/org/usergrid/persistence/Schema.java | 1788 -
.../persistence/SimpleCollectionRef.java | 84 -
.../usergrid/persistence/SimpleEntityRef.java | 149 -
.../org/usergrid/persistence/SimpleRoleRef.java | 125 -
.../org/usergrid/persistence/TypedEntity.java | 37 -
.../java/org/usergrid/persistence/Update.java | 75 -
.../annotations/EntityCollection.java | 43 -
.../annotations/EntityDictionary.java | 38 -
.../persistence/annotations/EntityProperty.java | 54 -
.../persistence/cassandra/ApplicationCF.java | 160 -
.../usergrid/persistence/cassandra/CFEnum.java | 37 -
.../cassandra/CassandraPersistenceUtils.java | 486 -
.../persistence/cassandra/CassandraService.java | 1135 -
.../cassandra/ConnectedEntityRefImpl.java | 61 -
.../cassandra/ConnectionRefImpl.java | 628 -
.../persistence/cassandra/CounterUtils.java | 400 -
.../persistence/cassandra/CursorCache.java | 121 -
.../cassandra/EntityManagerFactoryImpl.java | 411 -
.../cassandra/EntityManagerImpl.java | 2858 -
.../cassandra/EntityValueSerializer.java | 52 -
.../persistence/cassandra/GeoIndexManager.java | 323 -
.../persistence/cassandra/IndexUpdate.java | 450 -
.../persistence/cassandra/QueryProcessor.java | 720 -
.../cassandra/RelationManagerImpl.java | 2339 -
.../usergrid/persistence/cassandra/Setup.java | 206 -
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 -
.../cassandra/index/ConnectedIndexScanner.java | 232 -
.../cassandra/index/IndexBucketScanner.java | 218 -
.../index/IndexMultiBucketSetLoader.java | 138 -
.../cassandra/index/IndexScanner.java | 39 -
.../cassandra/index/NoOpIndexScanner.java | 94 -
.../cassandra/util/Slf4jTraceTagReporter.java | 47 -
.../cassandra/util/TaggedOpTimer.java | 38 -
.../persistence/cassandra/util/TimedOpTag.java | 101 -
.../cassandra/util/TraceParticipant.java | 20 -
.../persistence/cassandra/util/TraceTag.java | 77 -
.../cassandra/util/TraceTagAspect.java | 41 -
.../cassandra/util/TraceTagManager.java | 156 -
.../cassandra/util/TraceTagReporter.java | 10 -
.../usergrid/persistence/entities/Activity.java | 685 -
.../persistence/entities/Application.java | 609 -
.../usergrid/persistence/entities/Asset.java | 93 -
.../usergrid/persistence/entities/Device.java | 105 -
.../usergrid/persistence/entities/Event.java | 155 -
.../usergrid/persistence/entities/Folder.java | 93 -
.../usergrid/persistence/entities/Group.java | 168 -
.../usergrid/persistence/entities/JobData.java | 54 -
.../usergrid/persistence/entities/JobStat.java | 175 -
.../usergrid/persistence/entities/Message.java | 77 -
.../org/usergrid/persistence/entities/Role.java | 153 -
.../org/usergrid/persistence/entities/User.java | 348 -
.../ApplicationAlreadyExistsException.java | 37 -
.../DuplicateUniquePropertyExistsException.java | 52 -
.../exceptions/EntityNotFoundException.java | 45 -
.../exceptions/LockingException.java | 65 -
.../exceptions/NoFullTextIndexException.java | 50 -
.../exceptions/NoIndexException.java | 50 -
.../exceptions/PersistenceException.java | 45 -
.../PropertyTypeConversionException.java | 71 -
.../exceptions/QueryIterationException.java | 13 -
.../exceptions/QueryParseException.java | 63 -
.../exceptions/QueryTokenException.java | 52 -
.../persistence/exceptions/QueueException.java | 61 -
.../RequiredPropertyNotFoundException.java | 41 -
.../TransactionNotFoundException.java | 45 -
.../UnexpectedEntityTypeException.java | 45 -
.../persistence/geo/CollectionGeoSearch.java | 52 -
.../persistence/geo/ConnectionGeoSearch.java | 51 -
.../persistence/geo/EntityLocationRef.java | 211 -
.../EntityLocationRefDistanceComparator.java | 77 -
.../persistence/geo/GeoIndexSearcher.java | 368 -
.../persistence/geo/GeocellManager.java | 179 -
.../usergrid/persistence/geo/GeocellUtils.java | 539 -
.../geo/comparator/DoubleTupleComparator.java | 23 -
.../persistence/geo/model/BoundingBox.java | 71 -
.../persistence/geo/model/CostFunction.java | 33 -
.../geo/model/DefaultCostFunction.java | 34 -
.../usergrid/persistence/geo/model/Point.java | 58 -
.../usergrid/persistence/geo/model/Tuple.java | 24 -
.../usergrid/persistence/query/ir/AllNode.java | 54 -
.../usergrid/persistence/query/ir/AndNode.java | 43 -
.../persistence/query/ir/BooleanNode.java | 48 -
.../query/ir/EmailIdentifierNode.java | 31 -
.../query/ir/NameIdentifierNode.java | 28 -
.../persistence/query/ir/NodeVisitor.java | 78 -
.../usergrid/persistence/query/ir/NotNode.java | 62 -
.../usergrid/persistence/query/ir/OrNode.java | 52 -
.../persistence/query/ir/OrderByNode.java | 92 -
.../persistence/query/ir/QueryNode.java | 28 -
.../persistence/query/ir/QuerySlice.java | 344 -
.../persistence/query/ir/SearchVisitor.java | 255 -
.../persistence/query/ir/SliceNode.java | 168 -
.../query/ir/UuidIdentifierNode.java | 32 -
.../persistence/query/ir/WithinNode.java | 96 -
.../query/ir/result/AbstractScanColumn.java | 70 -
.../result/CollectionResultsLoaderFactory.java | 23 -
.../ir/result/ConnectionIndexSliceParser.java | 86 -
.../query/ir/result/ConnectionRefLoader.java | 65 -
.../result/ConnectionResultsLoaderFactory.java | 32 -
.../ir/result/ConnectionTypesIterator.java | 179 -
.../query/ir/result/EmptyIterator.java | 47 -
.../query/ir/result/EntityRefLoader.java | 50 -
.../query/ir/result/EntityResultsLoader.java | 46 -
.../query/ir/result/GeoIterator.java | 355 -
.../persistence/query/ir/result/IDLoader.java | 24 -
.../query/ir/result/IntersectionIterator.java | 167 -
.../query/ir/result/MergeIterator.java | 137 -
.../query/ir/result/MultiIterator.java | 54 -
.../query/ir/result/OrderByIterator.java | 252 -
.../query/ir/result/ResultIterator.java | 43 -
.../query/ir/result/ResultsLoader.java | 29 -
.../query/ir/result/ResultsLoaderFactory.java | 21 -
.../persistence/query/ir/result/ScanColumn.java | 16 -
.../query/ir/result/ScanColumnTransformer.java | 23 -
.../ir/result/SecondaryIndexSliceParser.java | 60 -
.../query/ir/result/SliceIterator.java | 251 -
.../query/ir/result/SliceParser.java | 31 -
.../query/ir/result/StaticIdIterator.java | 66 -
.../query/ir/result/SubtractionIterator.java | 108 -
.../query/ir/result/UUIDIndexSliceParser.java | 50 -
.../query/ir/result/UnionIterator.java | 252 -
.../usergrid/persistence/query/tree/.gitignore | 2 -
.../persistence/query/tree/AndOperand.java | 48 -
.../persistence/query/tree/BooleanLiteral.java | 48 -
.../persistence/query/tree/BooleanOperand.java | 48 -
.../persistence/query/tree/ContainsOperand.java | 69 -
.../query/tree/ContainsProperty.java | 57 -
.../usergrid/persistence/query/tree/Equal.java | 52 -
.../persistence/query/tree/EqualityOperand.java | 88 -
.../persistence/query/tree/FloatLiteral.java | 57 -
.../persistence/query/tree/GreaterThan.java | 52 -
.../query/tree/GreaterThanEqual.java | 56 -
.../persistence/query/tree/LessThan.java | 52 -
.../persistence/query/tree/LessThanEqual.java | 54 -
.../persistence/query/tree/Literal.java | 38 -
.../persistence/query/tree/LiteralFactory.java | 58 -
.../persistence/query/tree/LongLiteral.java | 64 -
.../persistence/query/tree/NotOperand.java | 45 -
.../persistence/query/tree/NumericLiteral.java | 24 -
.../persistence/query/tree/Operand.java | 47 -
.../persistence/query/tree/OrOperand.java | 53 -
.../persistence/query/tree/Property.java | 62 -
.../persistence/query/tree/QueryVisitor.java | 90 -
.../persistence/query/tree/StringLiteral.java | 82 -
.../persistence/query/tree/UUIDLiteral.java | 49 -
.../persistence/query/tree/WithinOperand.java | 111 -
.../persistence/query/tree/WithinProperty.java | 54 -
.../persistence/schema/CollectionInfo.java | 207 -
.../persistence/schema/DictionaryInfo.java | 117 -
.../usergrid/persistence/schema/EntityInfo.java | 299 -
.../persistence/schema/PropertyInfo.java | 218 -
.../usergrid/system/UsergridSystemMonitor.java | 95 -
.../main/java/org/usergrid/utils/AESUtils.java | 84 -
.../main/java/org/usergrid/utils/BCrypt.java | 627 -
.../java/org/usergrid/utils/ClassUtils.java | 58 -
.../java/org/usergrid/utils/CodecUtils.java | 45 -
.../java/org/usergrid/utils/CompositeUtils.java | 54 -
.../org/usergrid/utils/ConversionUtils.java | 765 -
.../main/java/org/usergrid/utils/DateUtils.java | 88 -
.../main/java/org/usergrid/utils/HttpUtils.java | 51 -
.../java/org/usergrid/utils/IndexUtils.java | 218 -
.../org/usergrid/utils/InflectionUtils.java | 51 -
.../main/java/org/usergrid/utils/Inflector.java | 553 -
.../main/java/org/usergrid/utils/JsonUtils.java | 329 -
.../main/java/org/usergrid/utils/ListUtils.java | 230 -
.../main/java/org/usergrid/utils/MailUtils.java | 154 -
.../main/java/org/usergrid/utils/MapUtils.java | 377 -
.../java/org/usergrid/utils/NumberUtils.java | 35 -
.../java/org/usergrid/utils/PasswordUtils.java | 28 -
.../java/org/usergrid/utils/StringUtils.java | 172 -
.../main/java/org/usergrid/utils/TimeUtils.java | 88 -
.../main/java/org/usergrid/utils/UUIDUtils.java | 412 -
.../main/java/org/usergrid/utils/Version.java | 428 -
.../java/org/usergrid/utils/package-info.java | 18 -
.../main/resources/usergrid-core-context.xml | 52 +-
.../resources/usergrid-scheduler-context.xml | 8 +-
stack/core/src/test/java/io/baas/Simple.java | 4 +-
.../org/apache/usergrid/AbstractCoreIT.java | 45 +
.../java/org/apache/usergrid/Application.java | 124 +
.../apache/usergrid/ConcurrentCoreITSuite.java | 50 +
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 +
.../usergrid/ConcurrentCoreTestSuite.java | 33 +
.../org/apache/usergrid/CoreApplication.java | 171 +
.../java/org/apache/usergrid/CoreITSetup.java | 43 +
.../org/apache/usergrid/CoreITSetupImpl.java | 145 +
.../java/org/apache/usergrid/CoreITSuite.java | 34 +
.../java/org/apache/usergrid/CoreTestSuite.java | 47 +
.../org/apache/usergrid/batch/AppArgsTest.java | 52 +
.../batch/BulkJobExecutionUnitTest.java | 209 +
.../apache/usergrid/batch/BulkTestUtils.java | 38 +
.../batch/ConcurrentSchedulerITSuite.java | 31 +
.../batch/ConcurrentSchedulerTestSuite.java | 19 +
.../apache/usergrid/batch/SchedulerITSuite.java | 34 +
.../usergrid/batch/SchedulerTestSuite.java | 18 +
.../usergrid/batch/UsergridJobFactoryTest.java | 31 +
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 +
.../usergrid/batch/job/CountdownLatchJob.java | 67 +
.../usergrid/batch/job/DelayExecution.java | 104 +
.../usergrid/batch/job/DelayHeartbeat.java | 106 +
.../batch/job/FailureJobExceuction.java | 74 +
.../usergrid/batch/job/OnlyOnceExceution.java | 116 +
.../job/OnlyOnceUnlockOnFailExceution.java | 126 +
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 +
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 +
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 +
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 +
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 +
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 +
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 +
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 +
.../usergrid/batch/job/TestJobListener.java | 121 +
.../usergrid/batch/job/TestJobListenerTest.java | 144 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../clustering/hazelcast/HazelcastTest.java | 111 +
.../count/BatchCountParallelismTest.java | 122 +
.../usergrid/count/SimpleBatcherTest.java | 50 +
.../count/common/CountSerDeUtilsTest.java | 68 +
.../apache/usergrid/count/common/CountTest.java | 68 +
.../locking/cassandra/HectorLockManagerIT.java | 185 +
.../SingleNodeLockTestSingleNode.java | 168 +
.../zookeeper/AbstractZooKeeperTest.java | 126 +
.../usergrid/locking/zookeeper/ZooPut.java | 113 +
.../zookeeper/ZookeeperLockManagerTest.java | 182 +
.../java/org/apache/usergrid/mq/MessagesIT.java | 278 +
.../org/apache/usergrid/mq/QueuePathsTest.java | 48 +
.../usergrid/persistence/CollectionIT.java | 1637 +
.../usergrid/persistence/CoreSchemaManager.java | 66 +
.../apache/usergrid/persistence/CounterIT.java | 235 +
.../persistence/EntityConnectionsIT.java | 292 +
.../persistence/EntityDictionaryIT.java | 133 +
.../usergrid/persistence/EntityManagerIT.java | 563 +
.../EntityPropertyComparatorTest.java | 206 +
.../apache/usergrid/persistence/EntityTest.java | 100 +
.../org/apache/usergrid/persistence/GeoIT.java | 524 +
.../apache/usergrid/persistence/IndexIT.java | 462 +
.../usergrid/persistence/PathQueryIT.java | 164 +
.../usergrid/persistence/PermissionsIT.java | 191 +
.../apache/usergrid/persistence/QueryTest.java | 311 +
.../usergrid/persistence/QueryUtilsTest.java | 41 +
.../apache/usergrid/persistence/SchemaTest.java | 127 +
.../apache/usergrid/persistence/UtilsTest.java | 38 +
.../cassandra/EntityManagerFactoryImplIT.java | 175 +
.../cassandra/QueryProcessorTest.java | 726 +
.../SimpleIndexBucketLocatorImplTest.java | 176 +
.../cassandra/util/TraceTagUnitTest.java | 38 +
.../persistence/entities/SampleEntity.java | 58 +
...EntityLocationRefDistanceComparatorTest.java | 102 +
.../query/AbstractIteratingQueryIT.java | 1299 +
.../persistence/query/AllInCollectionIT.java | 28 +
.../persistence/query/AllInConnectionIT.java | 28 +
.../query/AllInConnectionNoTypeIT.java | 56 +
.../query/IntersectionUnionPagingIT.java | 167 +
.../query/MultiOrderByCollectionIT.java | 28 +
.../MultiOrderByComplexUnionCollectionIT.java | 28 +
.../MultiOrderByComplexUnionConnectionIT.java | 28 +
.../query/MultiOrderByConnectionIT.java | 31 +
.../query/NotOrderByCollectionIT.java | 28 +
.../query/NotOrderByConnectionIT.java | 28 +
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 +
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 +
...leOrderByBoundRangeScanDescCollectionIT.java | 28 +
...leOrderByBoundRangeScanDescConnectionIT.java | 28 +
...eOrderByComplexIntersectionCollectionIT.java | 28 +
...eOrderByComplexIntersectionConnectionIT.java | 29 +
.../SingleOrderByComplexUnionCollectionIT.java | 28 +
.../SingleOrderByComplexUnionConnectionIT.java | 28 +
.../SingleOrderByIntersectionCollectionIT.java | 30 +
.../SingleOrderByIntersectionConnectionIT.java | 30 +
.../SingleOrderByLessThanLimitCollectionIT.java | 28 +
.../SingleOrderByLessThanLimitConnectionIT.java | 28 +
.../SingleOrderByMaxLimitCollectionIT.java | 29 +
.../SingleOrderByMaxLimitConnectionIT.java | 29 +
...SingleOrderByNoIntersectionCollectionIT.java | 28 +
...SingleOrderByNoIntersectionConnectionIT.java | 28 +
.../query/SingleOrderByNotCollectionIT.java | 28 +
.../query/SingleOrderByNotConnectionIT.java | 28 +
...OrderBySameRangeScanGreaterCollectionIT.java | 28 +
...OrderBySameRangeScanGreaterConnectionIT.java | 28 +
...meRangeScanGreaterThanEqualCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessConnectionIT.java | 28 +
...ySameRangeScanLessThanEqualCollectionIT.java | 28 +
...ySameRangeScanLessThanEqualConnectionIT.java | 28 +
.../query/ir/result/AbstractScanColumnTest.java | 84 +
.../query/ir/result/InOrderIterator.java | 115 +
.../ir/result/IntersectionIteratorTest.java | 306 +
.../query/ir/result/IteratorHelper.java | 18 +
.../ir/result/SubtractionIteratorTest.java | 180 +
.../query/ir/result/UnionIteratorTest.java | 466 +
.../persistence/query/tree/GrammarTreeTest.java | 592 +
.../persistence/query/tree/LongLiteralTest.java | 61 +
.../query/tree/StringLiteralTest.java | 87 +
.../system/UsergridSystemMonitorIT.java | 51 +
.../usergrid/utils/ConversionUtilsTest.java | 49 +
.../apache/usergrid/utils/IndexUtilsTest.java | 71 +
.../apache/usergrid/utils/JsonUtilsTest.java | 85 +
.../apache/usergrid/utils/ListUtilsTest.java | 53 +
.../apache/usergrid/utils/MailUtilsTest.java | 90 +
.../org/apache/usergrid/utils/MapUtilsTest.java | 41 +
.../apache/usergrid/utils/TestInflector.java | 81 +
.../apache/usergrid/utils/TimeUtilsTest.java | 60 +
.../apache/usergrid/utils/UUIDUtilsTest.java | 371 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../test/java/org/usergrid/AbstractCoreIT.java | 45 -
.../src/test/java/org/usergrid/Application.java | 124 -
.../org/usergrid/ConcurrentCoreITSuite.java | 50 -
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 -
.../org/usergrid/ConcurrentCoreTestSuite.java | 33 -
.../test/java/org/usergrid/CoreApplication.java | 171 -
.../src/test/java/org/usergrid/CoreITSetup.java | 43 -
.../test/java/org/usergrid/CoreITSetupImpl.java | 145 -
.../src/test/java/org/usergrid/CoreITSuite.java | 34 -
.../test/java/org/usergrid/CoreTestSuite.java | 47 -
.../java/org/usergrid/batch/AppArgsTest.java | 52 -
.../batch/BulkJobExecutionUnitTest.java | 209 -
.../java/org/usergrid/batch/BulkTestUtils.java | 38 -
.../batch/ConcurrentSchedulerITSuite.java | 31 -
.../batch/ConcurrentSchedulerTestSuite.java | 19 -
.../org/usergrid/batch/SchedulerITSuite.java | 34 -
.../org/usergrid/batch/SchedulerTestSuite.java | 18 -
.../usergrid/batch/UsergridJobFactoryTest.java | 31 -
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 -
.../usergrid/batch/job/CountdownLatchJob.java | 67 -
.../org/usergrid/batch/job/DelayExecution.java | 104 -
.../org/usergrid/batch/job/DelayHeartbeat.java | 106 -
.../batch/job/FailureJobExceuction.java | 74 -
.../usergrid/batch/job/OnlyOnceExceution.java | 116 -
.../job/OnlyOnceUnlockOnFailExceution.java | 126 -
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 -
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 -
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 -
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 -
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 -
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 -
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 -
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 -
.../org/usergrid/batch/job/TestJobListener.java | 121 -
.../usergrid/batch/job/TestJobListenerTest.java | 144 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../clustering/hazelcast/HazelcastTest.java | 111 -
.../count/BatchCountParallelismTest.java | 122 -
.../org/usergrid/count/SimpleBatcherTest.java | 51 -
.../count/common/CountSerDeUtilsTest.java | 68 -
.../org/usergrid/count/common/CountTest.java | 68 -
.../locking/cassandra/HectorLockManagerIT.java | 185 -
.../SingleNodeLockTestSingleNode.java | 168 -
.../zookeeper/AbstractZooKeeperTest.java | 126 -
.../org/usergrid/locking/zookeeper/ZooPut.java | 113 -
.../zookeeper/ZookeeperLockManagerTest.java | 182 -
.../test/java/org/usergrid/mq/MessagesIT.java | 278 -
.../java/org/usergrid/mq/QueuePathsTest.java | 48 -
.../org/usergrid/persistence/CollectionIT.java | 1637 -
.../usergrid/persistence/CoreSchemaManager.java | 66 -
.../org/usergrid/persistence/CounterIT.java | 235 -
.../persistence/EntityConnectionsIT.java | 292 -
.../persistence/EntityDictionaryIT.java | 133 -
.../usergrid/persistence/EntityManagerIT.java | 563 -
.../EntityPropertyComparatorTest.java | 206 -
.../org/usergrid/persistence/EntityTest.java | 100 -
.../java/org/usergrid/persistence/GeoIT.java | 524 -
.../java/org/usergrid/persistence/IndexIT.java | 462 -
.../org/usergrid/persistence/PathQueryIT.java | 164 -
.../org/usergrid/persistence/PermissionsIT.java | 191 -
.../org/usergrid/persistence/QueryTest.java | 311 -
.../usergrid/persistence/QueryUtilsTest.java | 41 -
.../org/usergrid/persistence/SchemaTest.java | 127 -
.../org/usergrid/persistence/UtilsTest.java | 38 -
.../cassandra/EntityManagerFactoryImplIT.java | 175 -
.../cassandra/QueryProcessorTest.java | 726 -
.../SimpleIndexBucketLocatorImplTest.java | 176 -
.../cassandra/util/TraceTagUnitTest.java | 38 -
.../persistence/entities/SampleEntity.java | 58 -
...EntityLocationRefDistanceComparatorTest.java | 102 -
.../query/AbstractIteratingQueryIT.java | 1299 -
.../persistence/query/AllInCollectionIT.java | 28 -
.../persistence/query/AllInConnectionIT.java | 28 -
.../query/AllInConnectionNoTypeIT.java | 55 -
.../query/IntersectionUnionPagingIT.java | 163 -
.../query/MultiOrderByCollectionIT.java | 28 -
.../MultiOrderByComplexUnionCollectionIT.java | 28 -
.../MultiOrderByComplexUnionConnectionIT.java | 28 -
.../query/MultiOrderByConnectionIT.java | 31 -
.../query/NotOrderByCollectionIT.java | 28 -
.../query/NotOrderByConnectionIT.java | 28 -
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 -
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 -
...leOrderByBoundRangeScanDescCollectionIT.java | 28 -
...leOrderByBoundRangeScanDescConnectionIT.java | 28 -
...eOrderByComplexIntersectionCollectionIT.java | 28 -
...eOrderByComplexIntersectionConnectionIT.java | 29 -
.../SingleOrderByComplexUnionCollectionIT.java | 28 -
.../SingleOrderByComplexUnionConnectionIT.java | 28 -
.../SingleOrderByIntersectionCollectionIT.java | 30 -
.../SingleOrderByIntersectionConnectionIT.java | 30 -
.../SingleOrderByLessThanLimitCollectionIT.java | 28 -
.../SingleOrderByLessThanLimitConnectionIT.java | 28 -
.../SingleOrderByMaxLimitCollectionIT.java | 29 -
.../SingleOrderByMaxLimitConnectionIT.java | 29 -
...SingleOrderByNoIntersectionCollectionIT.java | 28 -
...SingleOrderByNoIntersectionConnectionIT.java | 28 -
.../query/SingleOrderByNotCollectionIT.java | 28 -
.../query/SingleOrderByNotConnectionIT.java | 28 -
...OrderBySameRangeScanGreaterCollectionIT.java | 28 -
...OrderBySameRangeScanGreaterConnectionIT.java | 28 -
...meRangeScanGreaterThanEqualCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessConnectionIT.java | 28 -
...ySameRangeScanLessThanEqualCollectionIT.java | 28 -
...ySameRangeScanLessThanEqualConnectionIT.java | 28 -
.../query/ir/result/AbstractScanColumnTest.java | 84 -
.../query/ir/result/InOrderIterator.java | 115 -
.../ir/result/IntersectionIteratorTest.java | 304 -
.../query/ir/result/IteratorHelper.java | 18 -
.../ir/result/SubtractionIteratorTest.java | 180 -
.../query/ir/result/UnionIteratorTest.java | 378 -
.../persistence/query/tree/GrammarTreeTest.java | 592 -
.../persistence/query/tree/LongLiteralTest.java | 61 -
.../query/tree/StringLiteralTest.java | 87 -
.../system/UsergridSystemMonitorIT.java | 51 -
.../org/usergrid/utils/ConversionUtilsTest.java | 49 -
.../java/org/usergrid/utils/IndexUtilsTest.java | 71 -
.../java/org/usergrid/utils/JsonUtilsTest.java | 85 -
.../java/org/usergrid/utils/ListUtilsTest.java | 53 -
.../java/org/usergrid/utils/MailUtilsTest.java | 90 -
.../java/org/usergrid/utils/MapUtilsTest.java | 41 -
.../java/org/usergrid/utils/TestInflector.java | 81 -
.../java/org/usergrid/utils/TimeUtilsTest.java | 60 -
.../java/org/usergrid/utils/UUIDUtilsTest.java | 371 -
.../java/org/usergrid/utils/package-info.java | 18 -
stack/core/src/test/resources/log4j.properties | 16 +-
.../test/resources/usergrid-test-context.xml | 4 +-
stack/launcher/pom.xml | 12 +-
.../java/org/apache/usergrid/launcher/App.java | 288 +
.../apache/usergrid/launcher/AppleUtils.java | 38 +
.../launcher/ClasspathStaticHttpHandler.java | 320 +
.../launcher/CustomJSPTemplateProcessor.java | 137 +
.../usergrid/launcher/EmbeddedServerHelper.java | 193 +
.../org/apache/usergrid/launcher/JarMain.java | 40 +
.../apache/usergrid/launcher/LauncherFrame.java | 461 +
.../usergrid/launcher/LogViewerFrame.java | 104 +
.../org/apache/usergrid/launcher/Server.java | 618 +
.../apache/usergrid/launcher/package-info.java | 18 +
.../main/java/org/usergrid/launcher/App.java | 288 -
.../java/org/usergrid/launcher/AppleUtils.java | 38 -
.../launcher/ClasspathStaticHttpHandler.java | 320 -
.../launcher/CustomJSPTemplateProcessor.java | 137 -
.../usergrid/launcher/EmbeddedServerHelper.java | 193 -
.../java/org/usergrid/launcher/JarMain.java | 40 -
.../org/usergrid/launcher/LauncherFrame.java | 461 -
.../org/usergrid/launcher/LogViewerFrame.java | 104 -
.../main/java/org/usergrid/launcher/Server.java | 618 -
.../org/usergrid/launcher/package-info.java | 18 -
.../src/main/resources/log4j.properties | 14 +-
.../org/apache/usergrid/launcher/dock_icon.png | Bin 0 -> 11592 bytes
.../org/apache/usergrid/launcher/icon_16.png | Bin 0 -> 3273 bytes
.../org/apache/usergrid/launcher/icon_256.png | Bin 0 -> 12578 bytes
.../org/apache/usergrid/launcher/icon_32.png | Bin 0 -> 3862 bytes
.../org/apache/usergrid/launcher/icon_64.png | Bin 0 -> 5079 bytes
.../org/apache/usergrid/launcher/log_viewer.png | Bin 0 -> 6610 bytes
.../org/apache/usergrid/launcher/start.png | Bin 0 -> 9253 bytes
.../apache/usergrid/launcher/start_active.png | Bin 0 -> 9334 bytes
.../apache/usergrid/launcher/status_green.png | Bin 0 -> 2048 bytes
.../org/apache/usergrid/launcher/status_off.png | Bin 0 -> 1847 bytes
.../org/apache/usergrid/launcher/status_red.png | Bin 0 -> 2047 bytes
.../apache/usergrid/launcher/status_yellow.png | Bin 0 -> 2092 bytes
.../org/apache/usergrid/launcher/stop.png | Bin 0 -> 8858 bytes
.../apache/usergrid/launcher/stop_active.png | Bin 0 -> 8844 bytes
.../apache/usergrid/launcher/web_browser.png | Bin 0 -> 4531 bytes
.../org/usergrid/launcher/dock_icon.png | Bin 11592 -> 0 bytes
.../resources/org/usergrid/launcher/icon_16.png | Bin 3273 -> 0 bytes
.../org/usergrid/launcher/icon_256.png | Bin 12578 -> 0 bytes
.../resources/org/usergrid/launcher/icon_32.png | Bin 3862 -> 0 bytes
.../resources/org/usergrid/launcher/icon_64.png | Bin 5079 -> 0 bytes
.../org/usergrid/launcher/log_viewer.png | Bin 6610 -> 0 bytes
.../resources/org/usergrid/launcher/start.png | Bin 9253 -> 0 bytes
.../org/usergrid/launcher/start_active.png | Bin 9334 -> 0 bytes
.../org/usergrid/launcher/status_green.png | Bin 2048 -> 0 bytes
.../org/usergrid/launcher/status_off.png | Bin 1847 -> 0 bytes
.../org/usergrid/launcher/status_red.png | Bin 2047 -> 0 bytes
.../org/usergrid/launcher/status_yellow.png | Bin 2092 -> 0 bytes
.../resources/org/usergrid/launcher/stop.png | Bin 8858 -> 0 bytes
.../org/usergrid/launcher/stop_active.png | Bin 8844 -> 0 bytes
.../org/usergrid/launcher/web_browser.png | Bin 4531 -> 0 bytes
.../resources/usergrid-standalone-context.xml | 2 +-
.../0.0.3/usergrid-java-client-0.0.3.jar | Bin 0 -> 45750 bytes
.../usergrid-java-client-0.0.3.jar.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.jar.sha1 | 1 +
.../0.0.3/usergrid-java-client-0.0.3.pom | 87 +
.../usergrid-java-client-0.0.3.pom.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.pom.sha1 | 1 +
.../maven-metadata-local.xml | 13 +
stack/mongo-emulator/README.txt | 2 +-
stack/mongo-emulator/pom.xml | 14 +-
.../usergrid/mongo/MongoChannelHandler.java | 144 +
.../usergrid/mongo/MongoMessageDecoder.java | 115 +
.../usergrid/mongo/MongoMessageEncoder.java | 46 +
.../org/apache/usergrid/mongo/MongoQuery.java | 30 +
.../org/apache/usergrid/mongo/MongoServer.java | 171 +
.../mongo/MongoServerPipelineFactory.java | 55 +
.../usergrid/mongo/commands/Buildinfo.java | 43 +
.../usergrid/mongo/commands/Collstats.java | 58 +
.../apache/usergrid/mongo/commands/Count.java | 65 +
.../apache/usergrid/mongo/commands/Dbstats.java | 40 +
.../usergrid/mongo/commands/Getlasterror.java | 48 +
.../usergrid/mongo/commands/ListDatabases.java | 51 +
.../usergrid/mongo/commands/MongoCommand.java | 81 +
.../mongo/commands/ReplSetGetStatus.java | 37 +
.../usergrid/mongo/commands/ServerStatus.java | 62 +
.../usergrid/mongo/commands/Whatsmyuri.java | 41 +
.../apache/usergrid/mongo/protocol/Message.java | 191 +
.../apache/usergrid/mongo/protocol/OpCrud.java | 46 +
.../usergrid/mongo/protocol/OpDelete.java | 196 +
.../usergrid/mongo/protocol/OpGetMore.java | 112 +
.../usergrid/mongo/protocol/OpInsert.java | 180 +
.../usergrid/mongo/protocol/OpKillCursors.java | 115 +
.../apache/usergrid/mongo/protocol/OpMsg.java | 77 +
.../apache/usergrid/mongo/protocol/OpQuery.java | 447 +
.../apache/usergrid/mongo/protocol/OpReply.java | 189 +
.../usergrid/mongo/protocol/OpUpdate.java | 206 +
.../usergrid/mongo/query/MongoQueryParser.java | 291 +
.../mongo/testproxy/MongoMessageFrame.java | 55 +
.../testproxy/MongoProxyInboundHandler.java | 197 +
.../testproxy/MongoProxyPipelineFactory.java | 53 +
.../mongo/testproxy/MongoProxyServer.java | 55 +
.../testproxy/MongoProxyServerHandler.java | 58 +
.../apache/usergrid/mongo/utils/BSONUtils.java | 50 +
.../org/usergrid/mongo/MongoChannelHandler.java | 144 -
.../org/usergrid/mongo/MongoMessageDecoder.java | 115 -
.../org/usergrid/mongo/MongoMessageEncoder.java | 46 -
.../java/org/usergrid/mongo/MongoQuery.java | 30 -
.../java/org/usergrid/mongo/MongoServer.java | 171 -
.../mongo/MongoServerPipelineFactory.java | 55 -
.../org/usergrid/mongo/commands/Buildinfo.java | 43 -
.../org/usergrid/mongo/commands/Collstats.java | 58 -
.../java/org/usergrid/mongo/commands/Count.java | 65 -
.../org/usergrid/mongo/commands/Dbstats.java | 40 -
.../usergrid/mongo/commands/Getlasterror.java | 48 -
.../usergrid/mongo/commands/ListDatabases.java | 51 -
.../usergrid/mongo/commands/MongoCommand.java | 81 -
.../mongo/commands/ReplSetGetStatus.java | 37 -
.../usergrid/mongo/commands/ServerStatus.java | 63 -
.../org/usergrid/mongo/commands/Whatsmyuri.java | 41 -
.../org/usergrid/mongo/protocol/Message.java | 191 -
.../org/usergrid/mongo/protocol/OpCrud.java | 46 -
.../org/usergrid/mongo/protocol/OpDelete.java | 196 -
.../org/usergrid/mongo/protocol/OpGetMore.java | 112 -
.../org/usergrid/mongo/protocol/OpInsert.java | 180 -
.../usergrid/mongo/protocol/OpKillCursors.java | 115 -
.../java/org/usergrid/mongo/protocol/OpMsg.java | 77 -
.../org/usergrid/mongo/protocol/OpQuery.java | 447 -
.../org/usergrid/mongo/protocol/OpReply.java | 189 -
.../org/usergrid/mongo/protocol/OpUpdate.java | 206 -
.../usergrid/mongo/query/MongoQueryParser.java | 291 -
.../mongo/testproxy/MongoMessageFrame.java | 55 -
.../testproxy/MongoProxyInboundHandler.java | 197 -
.../testproxy/MongoProxyPipelineFactory.java | 53 -
.../mongo/testproxy/MongoProxyServer.java | 55 -
.../testproxy/MongoProxyServerHandler.java | 58 -
.../org/usergrid/mongo/utils/BSONUtils.java | 50 -
.../usergrid/mongo/AbstractMongoTest.java | 62 +
.../apache/usergrid/mongo/BasicMongoTest.java | 340 +
.../usergrid/mongo/DatabaseInitializer.java | 145 +
.../apache/usergrid/mongo/MongoQueryTest.java | 503 +
.../org/usergrid/mongo/AbstractMongoTest.java | 61 -
.../java/org/usergrid/mongo/BasicMongoTest.java | 340 -
.../org/usergrid/mongo/DatabaseInitializer.java | 145 -
.../java/org/usergrid/mongo/MongoQueryTest.java | 503 -
.../test/resources/usergrid-test-context.xml | 4 +-
stack/pom.xml | 41 +-
stack/query-validator/pom.xml | 22 +-
.../query/validator/ApiServerRunner.java | 24 +-
.../usergrid/query/validator/QueryEntity.java | 4 +-
.../usergrid/query/validator/QueryRequest.java | 2 +-
.../usergrid/query/validator/QueryResponse.java | 4 +-
.../usergrid/query/validator/QueryRunner.java | 4 +-
.../validator/QueryValidationConfiguration.java | 6 +-
.../query/validator/QueryValidator.java | 4 +-
.../usergrid/query/validator/SqliteRunner.java | 6 +-
.../usergrid-query-validator-context.xml | 2 +-
.../query/validator/QueryValidationTest.java | 2 +-
.../query/validator/QueryValidatorRunner.java | 14 +-
.../src/test/resources/log4j.properties | 18 +-
.../test/resources/usergrid-test-context.xml | 4 +-
stack/rest/pom.xml | 20 +-
.../usergrid/rest/AbstractContextResource.java | 164 +
.../org/apache/usergrid/rest/ApiResponse.java | 636 +
.../rest/JacksonCustomMapperProvider.java | 65 +
.../org/apache/usergrid/rest/RootResource.java | 397 +
.../rest/ServerEnvironmentProperties.java | 47 +
.../apache/usergrid/rest/SwaggerServlet.java | 171 +
.../apache/usergrid/rest/SystemResource.java | 110 +
.../usergrid/rest/TextToJsonSwapWriter.java | 119 +
.../rest/applications/ApplicationResource.java | 610 +
.../rest/applications/AuthResource.java | 251 +
.../rest/applications/ServiceResource.java | 662 +
.../applications/assets/AssetsResource.java | 190 +
.../applications/events/EventsResource.java | 69 +
.../rest/applications/queues/QueueResource.java | 204 +
.../queues/QueueSubscriberResource.java | 158 +
.../queues/QueueSubscriptionResource.java | 160 +
.../queues/QueueTransactionsResource.java | 99 +
.../users/AbstractUserExtensionResource.java | 47 +
.../rest/applications/users/UserResource.java | 580 +
.../rest/applications/users/UsersResource.java | 264 +
.../exceptions/AbstractExceptionMapper.java | 106 +
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 +
.../AuthorizationExceptionMapper.java | 36 +
...cateUniquePropertyExistsExceptionMapper.java | 35 +
.../EntityNotFoundExceptionMapper.java | 34 +
...orbiddenServiceOperationExceptionMapper.java | 35 +
.../IllegalArgumentExceptionMapper.java | 32 +
.../exceptions/JsonReadExceptionMapper.java | 35 +
.../exceptions/JsonWriteExceptionMapper.java | 35 +
.../exceptions/ManagementExceptionMapper.java | 38 +
.../usergrid/rest/exceptions/NoOpException.java | 50 +
.../rest/exceptions/NoOpExceptionMapper.java | 32 +
.../NotImplementedExceptionMapper.java | 32 +
.../exceptions/OAuthProblemExceptionMapper.java | 51 +
...rganizationApplicationNotFoundException.java | 39 +
...ationApplicationNotFoundExceptionMapper.java | 16 +
.../exceptions/PersistenceExceptionMapper.java | 27 +
.../exceptions/QueryParseExceptionMapper.java | 34 +
.../exceptions/QueryTokenExceptionMapper.java | 36 +
.../RecentlyUsedPasswordExceptionMapper.java | 21 +
.../rest/exceptions/RedirectionException.java | 27 +
.../exceptions/RedirectionExceptionMapper.java | 30 +
...RequiredPropertyNotFoundExceptionMapper.java | 35 +
.../rest/exceptions/SecurityException.java | 88 +
.../exceptions/SecurityExceptionMapper.java | 45 +
.../rest/exceptions/ServiceExceptionMapper.java | 28 +
.../ServiceResourceNotFoundExceptionMapper.java | 41 +
.../rest/exceptions/ThrowableMapper.java | 26 +
.../TransactionNotFoundExceptionMapper.java | 34 +
.../rest/filters/ContentTypeFilter.java | 323 +
.../rest/filters/JSONPCallbackFilter.java | 66 +
.../usergrid/rest/filters/MeteringFilter.java | 343 +
.../usergrid/rest/filters/TracingFilter.java | 74 +
.../rest/management/ManagementResource.java | 478 +
.../management/metrics/MetricsResource.java | 39 +
.../organizations/OrganizationResource.java | 254 +
.../organizations/OrganizationsResource.java | 192 +
.../applications/ApplicationResource.java | 195 +
.../applications/ApplicationsResource.java | 158 +
.../organizations/users/UsersResource.java | 341 +
.../rest/management/users/UserResource.java | 423 +
.../rest/management/users/UsersResource.java | 211 +
.../organizations/OrganizationsResource.java | 206 +
.../organizations/OrganizationResource.java | 159 +
.../rest/security/CrossOriginRequestFilter.java | 38 +
.../security/SecuredResourceFilterFactory.java | 325 +
.../annotations/RequireAdminUserAccess.java | 31 +
.../annotations/RequireApplicationAccess.java | 34 +
.../annotations/RequireOrganizationAccess.java | 34 +
.../annotations/RequireSystemAccess.java | 31 +
.../security/shiro/RestSecurityManager.java | 60 +
.../ShiroAuthenticationExceptionMapper.java | 59 +
.../shiro/filters/BasicAuthSecurityFilter.java | 111 +
.../ClientCredentialsSecurityFilter.java | 69 +
.../OAuth2AccessTokenSecurityFilter.java | 211 +
.../security/shiro/filters/SecurityFilter.java | 136 +
.../session/HttpRequestSessionManager.java | 87 +
.../session/HttpServletRequestSession.java | 132 +
.../usergrid/rest/test/PropertiesResource.java | 87 +
.../apache/usergrid/rest/utils/CORSUtils.java | 173 +
.../apache/usergrid/rest/utils/JSONPUtils.java | 103 +
.../usergrid/rest/utils/PathingUtils.java | 35 +
.../usergrid/rest/AbstractContextResource.java | 164 -
.../java/org/usergrid/rest/ApiResponse.java | 636 -
.../rest/JacksonCustomMapperProvider.java | 65 -
.../java/org/usergrid/rest/RootResource.java | 397 -
.../rest/ServerEnvironmentProperties.java | 47 -
.../java/org/usergrid/rest/SwaggerServlet.java | 171 -
.../java/org/usergrid/rest/SystemResource.java | 110 -
.../org/usergrid/rest/TextToJsonSwapWriter.java | 119 -
.../rest/applications/ApplicationResource.java | 610 -
.../rest/applications/AuthResource.java | 251 -
.../rest/applications/ServiceResource.java | 662 -
.../applications/assets/AssetsResource.java | 190 -
.../applications/events/EventsResource.java | 69 -
.../rest/applications/queues/QueueResource.java | 204 -
.../queues/QueueSubscriberResource.java | 158 -
.../queues/QueueSubscriptionResource.java | 160 -
.../queues/QueueTransactionsResource.java | 99 -
.../users/AbstractUserExtensionResource.java | 47 -
.../rest/applications/users/UserResource.java | 580 -
.../rest/applications/users/UsersResource.java | 264 -
.../exceptions/AbstractExceptionMapper.java | 106 -
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 -
.../AuthorizationExceptionMapper.java | 36 -
...cateUniquePropertyExistsExceptionMapper.java | 35 -
.../EntityNotFoundExceptionMapper.java | 34 -
...orbiddenServiceOperationExceptionMapper.java | 35 -
.../IllegalArgumentExceptionMapper.java | 32 -
.../exceptions/JsonReadExceptionMapper.java | 35 -
.../exceptions/JsonWriteExceptionMapper.java | 35 -
.../exceptions/ManagementExceptionMapper.java | 38 -
.../usergrid/rest/exceptions/NoOpException.java | 50 -
.../rest/exceptions/NoOpExceptionMapper.java | 32 -
.../NotImplementedExceptionMapper.java | 32 -
.../exceptions/OAuthProblemExceptionMapper.java | 51 -
...rganizationApplicationNotFoundException.java | 39 -
...ationApplicationNotFoundExceptionMapper.java | 16 -
.../exceptions/PersistenceExceptionMapper.java | 27 -
.../exceptions/QueryParseExceptionMapper.java | 34 -
.../exceptions/QueryTokenExceptionMapper.java | 36 -
.../RecentlyUsedPasswordExceptionMapper.java | 21 -
.../rest/exceptions/RedirectionException.java | 27 -
.../exceptions/RedirectionExceptionMapper.java | 30 -
...RequiredPropertyNotFoundExceptionMapper.java | 35 -
.../rest/exceptions/SecurityException.java | 88 -
.../exceptions/SecurityExceptionMapper.java | 45 -
.../rest/exceptions/ServiceExceptionMapper.java | 28 -
.../ServiceResourceNotFoundExceptionMapper.java | 41 -
.../rest/exceptions/ThrowableMapper.java | 26 -
.../TransactionNotFoundExceptionMapper.java | 34 -
.../rest/filters/ContentTypeFilter.java | 323 -
.../rest/filters/JSONPCallbackFilter.java | 66 -
.../usergrid/rest/filters/MeteringFilter.java | 343 -
.../usergrid/rest/filters/TracingFilter.java | 74 -
.../rest/management/ManagementResource.java | 478 -
.../management/metrics/MetricsResource.java | 39 -
.../organizations/OrganizationResource.java | 254 -
.../organizations/OrganizationsResource.java | 192 -
.../applications/ApplicationResource.java | 195 -
.../applications/ApplicationsResource.java | 158 -
.../organizations/users/UsersResource.java | 341 -
.../rest/management/users/UserResource.java | 423 -
.../rest/management/users/UsersResource.java | 211 -
.../organizations/OrganizationsResource.java | 206 -
.../organizations/OrganizationResource.java | 159 -
.../rest/security/CrossOriginRequestFilter.java | 38 -
.../security/SecuredResourceFilterFactory.java | 325 -
.../annotations/RequireAdminUserAccess.java | 31 -
.../annotations/RequireApplicationAccess.java | 34 -
.../annotations/RequireOrganizationAccess.java | 34 -
.../annotations/RequireSystemAccess.java | 31 -
.../security/shiro/RestSecurityManager.java | 60 -
.../ShiroAuthenticationExceptionMapper.java | 59 -
.../shiro/filters/BasicAuthSecurityFilter.java | 111 -
.../ClientCredentialsSecurityFilter.java | 69 -
.../OAuth2AccessTokenSecurityFilter.java | 211 -
.../security/shiro/filters/SecurityFilter.java | 136 -
.../session/HttpRequestSessionManager.java | 87 -
.../session/HttpServletRequestSession.java | 132 -
.../usergrid/rest/test/PropertiesResource.java | 87 -
.../java/org/usergrid/rest/utils/CORSUtils.java | 173 -
.../org/usergrid/rest/utils/JSONPUtils.java | 103 -
.../org/usergrid/rest/utils/PathingUtils.java | 35 -
.../main/resources/usergrid-rest-context.xml | 12 +-
.../apache/usergrid/rest/TestResource/error.jsp | 17 +
.../apache/usergrid/rest/TestResource/test.jsp | 13 +
.../ApplicationResource/authorize_form.jsp | 43 +
.../applications/ApplicationResource/error.jsp | 17 +
.../users/UserResource/activate.jsp | 16 +
.../applications/users/UserResource/confirm.jsp | 17 +
.../applications/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../applications/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 37 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../ManagementResource/authorize_form.jsp | 43 +
.../management/ManagementResource/error.jsp | 17 +
.../OrganizationResource/activate.jsp | 16 +
.../OrganizationResource/confirm.jsp | 17 +
.../OrganizationResource/error.jsp | 17 +
.../management/users/UserResource/activate.jsp | 16 +
.../management/users/UserResource/confirm.jsp | 17 +
.../management/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../management/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 34 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../org/usergrid/rest/TestResource/error.jsp | 17 -
.../jsp/org/usergrid/rest/TestResource/test.jsp | 13 -
.../ApplicationResource/authorize_form.jsp | 43 -
.../applications/ApplicationResource/error.jsp | 17 -
.../users/UserResource/activate.jsp | 16 -
.../applications/users/UserResource/confirm.jsp | 17 -
.../applications/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../applications/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 37 -
.../UsersResource/resetpw_email_success.jsp | 19 -
.../ManagementResource/authorize_form.jsp | 43 -
.../management/ManagementResource/error.jsp | 17 -
.../OrganizationResource/activate.jsp | 16 -
.../OrganizationResource/confirm.jsp | 17 -
.../OrganizationResource/error.jsp | 17 -
.../management/users/UserResource/activate.jsp | 16 -
.../management/users/UserResource/confirm.jsp | 17 -
.../management/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../management/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 34 -
.../UsersResource/resetpw_email_success.jsp | 19 -
stack/rest/src/main/webapp/WEB-INF/web.xml | 169 +-
.../apache/usergrid/rest/AbstractRestIT.java | 355 +
.../java/org/apache/usergrid/rest/BasicIT.java | 310 +
.../usergrid/rest/ConcurrentRestITSuite.java | 47 +
.../usergrid/rest/DatabaseInitializer.java | 145 +
.../java/org/apache/usergrid/rest/ITSetup.java | 166 +
.../org/apache/usergrid/rest/RestITSuite.java | 55 +
.../apache/usergrid/rest/TestContextSetup.java | 58 +
.../apache/usergrid/rest/TomcatResource.java | 74 +
.../ApplicationRequestCounterIT.java | 93 +
.../applications/ApplicationResourceIT.java | 531 +
.../rest/applications/DevicesResourceIT.java | 62 +
.../applications/assets/AssetResourceIT.java | 260 +
.../collection/BadGrammarQueryTest.java | 60 +
.../collection/BrowserCompatibilityTest.java | 86 +
.../collection/PagingResourceIT.java | 218 +
.../collection/activities/AndOrQueryTest.java | 176 +
.../collection/activities/OrderByTest.java | 149 +
.../activities/PagingEntitiesTest.java | 119 +
.../collection/activities/PutTest.java | 64 +
.../collection/groups/GeoPagingTest.java | 124 +
.../collection/groups/UpdateGroupIT.java | 108 +
.../applications/events/EventsResourceIT.java | 109 +
.../queues/AbstractQueueResourceIT.java | 468 +
.../queues/QueueResourceLong1IT.java | 130 +
.../queues/QueueResourceLong2IT.java | 82 +
.../queues/QueueResourceLong3IT.java | 184 +
.../queues/QueueResourceShortIT.java | 415 +
.../applications/users/ActivityResourceIT.java | 180 +
.../users/CollectionsResourceIT.java | 199 +
.../users/ConnectionResourceTest.java | 236 +
.../applications/users/GroupResourceIT.java | 270 +
.../applications/users/OwnershipResourceIT.java | 344 +
.../users/PermissionsResourceIT.java | 699 +
.../applications/users/RetrieveUsersTest.java | 66 +
.../rest/applications/users/UserResourceIT.java | 1286 +
.../users/extensions/TestResource.java | 50 +
.../rest/applications/utils/TestUtils.java | 46 +
.../rest/applications/utils/UserRepo.java | 65 +
.../rest/filters/ContentTypeResourceIT.java | 310 +
.../rest/management/ManagementResourceIT.java | 531 +
.../rest/management/RegistrationIT.java | 351 +
.../organizations/AdminEmailEncodingIT.java | 101 +
.../organizations/OrganizationResourceIT.java | 71 +
.../organizations/OrganizationsResourceIT.java | 257 +
.../rest/management/users/MUUserResourceIT.java | 602 +
.../UsersOrganizationsResourceIT.java | 56 +
.../rest/test/PropertiesResourceIT.java | 75 +
.../rest/test/resource/CollectionResource.java | 26 +
.../usergrid/rest/test/resource/Connection.java | 51 +
.../rest/test/resource/CustomCollection.java | 31 +
.../rest/test/resource/EntityResource.java | 104 +
.../apache/usergrid/rest/test/resource/Me.java | 35 +
.../rest/test/resource/NamedResource.java | 185 +
.../rest/test/resource/ResultsParser.java | 22 +
.../rest/test/resource/RootResource.java | 64 +
.../rest/test/resource/SetResource.java | 82 +
.../rest/test/resource/TestContext.java | 170 +
.../rest/test/resource/ValueResource.java | 307 +
.../rest/test/resource/app/Application.java | 72 +
.../usergrid/rest/test/resource/app/Device.java | 48 +
.../usergrid/rest/test/resource/app/User.java | 54 +
.../rest/test/resource/app/UsersCollection.java | 62 +
.../resource/app/queue/DevicesCollection.java | 36 +
.../rest/test/resource/app/queue/Queue.java | 183 +
.../resource/app/queue/QueuesCollection.java | 35 +
.../app/queue/SubscribersCollection.java | 59 +
.../test/resource/app/queue/Transaction.java | 76 +
.../app/queue/TransactionsCollection.java | 35 +
.../rest/test/resource/mgmt/Application.java | 48 +
.../resource/mgmt/ApplicationsCollection.java | 51 +
.../rest/test/resource/mgmt/Management.java | 93 +
.../rest/test/resource/mgmt/Organization.java | 59 +
.../resource/mgmt/OrganizationsCollection.java | 54 +
.../rest/test/security/TestAdminUser.java | 53 +
.../rest/test/security/TestAppUser.java | 53 +
.../usergrid/rest/test/security/TestUser.java | 126 +
.../java/org/usergrid/rest/AbstractRestIT.java | 355 -
.../test/java/org/usergrid/rest/BasicIT.java | 310 -
.../usergrid/rest/ConcurrentRestITSuite.java | 47 -
.../org/usergrid/rest/DatabaseInitializer.java | 145 -
.../test/java/org/usergrid/rest/ITSetup.java | 166 -
.../java/org/usergrid/rest/RestITSuite.java | 55 -
.../org/usergrid/rest/TestContextSetup.java | 58 -
.../java/org/usergrid/rest/TomcatResource.java | 74 -
.../ApplicationRequestCounterIT.java | 93 -
.../applications/ApplicationResourceIT.java | 531 -
.../rest/applications/DevicesResourceIT.java | 62 -
.../applications/assets/AssetResourceIT.java | 260 -
.../collection/BadGrammarQueryTest.java | 60 -
.../collection/BrowserCompatibilityTest.java | 86 -
.../collection/PagingResourceIT.java | 218 -
.../collection/activities/AndOrQueryTest.java | 176 -
.../collection/activities/OrderByTest.java | 149 -
.../activities/PagingEntitiesTest.java | 119 -
.../collection/activities/PutTest.java | 64 -
.../collection/groups/GeoPagingTest.java | 124 -
.../collection/groups/UpdateGroupIT.java | 108 -
.../applications/events/EventsResourceIT.java | 109 -
.../queues/AbstractQueueResourceIT.java | 468 -
.../queues/QueueResourceLong1IT.java | 130 -
.../queues/QueueResourceLong2IT.java | 82 -
.../queues/QueueResourceLong3IT.java | 184 -
.../queues/QueueResourceShortIT.java | 415 -
.../applications/users/ActivityResourceIT.java | 180 -
.../users/CollectionsResourceIT.java | 199 -
.../users/ConnectionResourceTest.java | 193 -
.../applications/users/GroupResourceIT.java | 270 -
.../applications/users/OwnershipResourceIT.java | 344 -
.../users/PermissionsResourceIT.java | 699 -
.../applications/users/RetrieveUsersTest.java | 66 -
.../rest/applications/users/UserResourceIT.java | 1286 -
.../users/extensions/TestResource.java | 50 -
.../rest/applications/utils/TestUtils.java | 46 -
.../rest/applications/utils/UserRepo.java | 65 -
.../rest/filters/ContentTypeResourceIT.java | 310 -
.../rest/management/ManagementResourceIT.java | 531 -
.../rest/management/RegistrationIT.java | 351 -
.../organizations/AdminEmailEncodingIT.java | 101 -
.../organizations/OrganizationResourceIT.java | 70 -
.../organizations/OrganizationsResourceIT.java | 256 -
.../rest/management/users/MUUserResourceIT.java | 602 -
.../UsersOrganizationsResourceIT.java | 56 -
.../rest/test/PropertiesResourceIT.java | 75 -
.../rest/test/resource/CollectionResource.java | 26 -
.../usergrid/rest/test/resource/Connection.java | 51 -
.../rest/test/resource/CustomCollection.java | 31 -
.../rest/test/resource/EntityResource.java | 104 -
.../org/usergrid/rest/test/resource/Me.java | 35 -
.../rest/test/resource/NamedResource.java | 185 -
.../rest/test/resource/ResultsParser.java | 22 -
.../rest/test/resource/RootResource.java | 64 -
.../rest/test/resource/SetResource.java | 82 -
.../rest/test/resource/TestContext.java | 170 -
.../rest/test/resource/ValueResource.java | 307 -
.../rest/test/resource/app/Application.java | 72 -
.../usergrid/rest/test/resource/app/Device.java | 48 -
.../usergrid/rest/test/resource/app/User.java | 54 -
.../rest/test/resource/app/UsersCollection.java | 62 -
.../resource/app/queue/DevicesCollection.java | 36 -
.../rest/test/resource/app/queue/Queue.java | 183 -
.../resource/app/queue/QueuesCollection.java | 35 -
.../app/queue/SubscribersCollection.java | 59 -
.../test/resource/app/queue/Transaction.java | 76 -
.../app/queue/TransactionsCollection.java | 35 -
.../rest/test/resource/mgmt/Application.java | 48 -
.../resource/mgmt/ApplicationsCollection.java | 51 -
.../rest/test/resource/mgmt/Management.java | 93 -
.../rest/test/resource/mgmt/Organization.java | 59 -
.../resource/mgmt/OrganizationsCollection.java | 54 -
.../rest/test/security/TestAdminUser.java | 53 -
.../rest/test/security/TestAppUser.java | 53 -
.../usergrid/rest/test/security/TestUser.java | 126 -
stack/rest/src/test/resources/log4j.properties | 14 +-
.../test/resources/usergrid-test-context.xml | 12 +-
stack/services/groupstest.out | 64570 -----------------
stack/services/pom.xml | 14 +-
.../management/AccountCreationProps.java | 128 +
.../usergrid/management/ActivationState.java | 8 +
.../usergrid/management/ApplicationCreator.java | 14 +
.../usergrid/management/ApplicationInfo.java | 134 +
.../usergrid/management/ManagementService.java | 319 +
.../usergrid/management/OrganizationInfo.java | 185 +
.../management/OrganizationOwnerInfo.java | 53 +
.../management/OrganizationProfile.java | 87 +
.../apache/usergrid/management/UserInfo.java | 149 +
.../cassandra/AccountCreationPropsImpl.java | 157 +
.../cassandra/ApplicationCreatorImpl.java | 77 +
.../cassandra/ManagementServiceImpl.java | 2890 +
.../ApplicationCreationException.java | 26 +
.../exceptions/DisabledAdminUserException.java | 42 +
.../exceptions/DisabledAppUserException.java | 42 +
.../exceptions/IncorrectPasswordException.java | 42 +
.../exceptions/ManagementException.java | 42 +
.../RecentlyUsedPasswordException.java | 27 +
.../UnableToLeaveOrganizationException.java | 42 +
.../UnactivatedAdminUserException.java | 42 +
.../exceptions/UnactivatedAppUserException.java | 42 +
.../UnactivatedOrganizationException.java | 42 +
.../UnconfirmedAdminUserException.java | 42 +
.../usergrid/management/utils/AccountUtils.java | 41 +
.../usergrid/security/AuthPrincipalInfo.java | 71 +
.../usergrid/security/AuthPrincipalType.java | 115 +
.../security/crypto/EncryptionService.java | 70 +
.../security/crypto/EncryptionServiceImpl.java | 208 +
.../security/crypto/command/BcryptCommand.java | 92 +
.../crypto/command/EncryptionCommand.java | 49 +
.../security/crypto/command/Md5HashCommand.java | 61 +
.../crypto/command/PlainTextCommand.java | 64 +
.../crypto/command/SaltedHasherCommand.java | 67 +
.../crypto/command/Sha1HashCommand.java | 73 +
.../usergrid/security/oauth/AccessInfo.java | 187 +
.../security/oauth/ClientCredentialsInfo.java | 93 +
.../usergrid/security/oauth/OAuthProxy.java | 43 +
.../security/oauth/OAuthProxyFactory.java | 31 +
.../security/providers/AbstractProvider.java | 61 +
.../security/providers/FacebookProvider.java | 183 +
.../security/providers/FoursquareProvider.java | 159 +
.../providers/PingIdentityProvider.java | 143 +
.../security/providers/SignInAsProvider.java | 19 +
.../providers/SignInProviderFactory.java | 51 +
.../security/salt/NoOpSaltProvider.java | 36 +
.../security/salt/PropertiesSaltProvider.java | 53 +
.../usergrid/security/salt/SaltProvider.java | 31 +
.../security/shiro/CustomPermission.java | 225 +
.../shiro/CustomPermissionResolver.java | 29 +
.../shiro/PrincipalCredentialsToken.java | 139 +
.../apache/usergrid/security/shiro/Realm.java | 540 +
.../AbstractAccessTokenCredentials.java | 33 +
.../credentials/AbstractClientCredentials.java | 28 +
.../AbstractPasswordCredentials.java | 33 +
.../credentials/AccessTokenCredentials.java | 22 +
.../shiro/credentials/AdminUserAccessToken.java | 24 +
.../shiro/credentials/AdminUserCredentials.java | 21 +
.../shiro/credentials/AdminUserPassword.java | 24 +
.../credentials/ApplicationAccessToken.java | 24 +
.../ApplicationClientCredentials.java | 24 +
.../credentials/ApplicationCredentials.java | 21 +
.../shiro/credentials/ApplicationGuest.java | 24 +
.../credentials/ApplicationUserAccessToken.java | 24 +
.../credentials/ApplicationUserCredentials.java | 21 +
.../credentials/ApplicationUserPassword.java | 24 +
.../shiro/credentials/ClientCredentials.java | 24 +
.../credentials/OrganizationAccessToken.java | 24 +
.../OrganizationClientCredentials.java | 24 +
.../credentials/OrganizationCredentials.java | 21 +
.../shiro/credentials/PasswordCredentials.java | 22 +
.../shiro/credentials/PrincipalCredentials.java | 21 +
.../shiro/principals/AdminUserPrincipal.java | 29 +
.../principals/ApplicationGuestPrincipal.java | 48 +
.../shiro/principals/ApplicationPrincipal.java | 48 +
.../principals/ApplicationUserPrincipal.java | 35 +
.../shiro/principals/OrganizationPrincipal.java | 48 +
.../shiro/principals/PrincipalIdentifier.java | 51 +
.../shiro/principals/UserPrincipal.java | 69 +
.../security/shiro/utils/SubjectUtils.java | 449 +
.../usergrid/security/tokens/TokenCategory.java | 83 +
.../usergrid/security/tokens/TokenInfo.java | 125 +
.../usergrid/security/tokens/TokenService.java | 39 +
.../tokens/cassandra/TokenServiceImpl.java | 627 +
.../tokens/exceptions/BadTokenException.java | 32 +
.../exceptions/ExpiredTokenException.java | 32 +
.../exceptions/InvalidTokenException.java | 32 +
.../tokens/exceptions/TokenException.java | 35 +
.../services/AbstractCollectionService.java | 571 +
.../services/AbstractConnectionsService.java | 520 +
.../AbstractPathBasedColllectionService.java | 148 +
.../usergrid/services/AbstractService.java | 1306 +
.../org/apache/usergrid/services/Service.java | 49 +
.../apache/usergrid/services/ServiceAction.java | 21 +
.../ServiceCollectionEventListener.java | 22 +
.../usergrid/services/ServiceContext.java | 448 +
.../services/ServiceExecutionEvent.java | 79 +
.../services/ServiceExecutionEventListener.java | 22 +
.../apache/usergrid/services/ServiceInfo.java | 438 +
.../usergrid/services/ServiceManager.java | 431 +
.../services/ServiceManagerFactory.java | 131 +
.../usergrid/services/ServiceParameter.java | 452 +
.../usergrid/services/ServicePayload.java | 199 +
.../usergrid/services/ServiceRequest.java | 372 +
.../usergrid/services/ServiceResults.java | 304 +
.../apache/usergrid/services/ServiceUtils.java | 21 +
.../services/activities/ActivitiesService.java | 33 +
.../applications/ApplicationsService.java | 215 +
.../usergrid/services/assets/AssetsService.java | 57 +
.../services/assets/data/AssetMimeHandler.java | 90 +
.../services/assets/data/AssetUtils.java | 107 +
.../services/assets/data/BinaryStore.java | 27 +
.../assets/data/LocalFileBinaryStore.java | 85 +
.../services/assets/data/S3BinaryStore.java | 202 +
.../services/devices/DevicesService.java | 51 +
.../services/devices/users/UsersService.java | 32 +
.../ForbiddenServiceOperationException.java | 41 +
.../services/exceptions/ServiceException.java | 45 +
.../exceptions/ServiceInvocationException.java | 83 +
.../ServiceResourceNotFoundException.java | 39 +
.../UndefinedServiceEntityTypeException.java | 45 +
.../UnsupportedServiceOperationException.java | 39 +
.../generic/GenericCollectionService.java | 27 +
.../generic/GenericConnectionsService.java | 27 +
.../services/generic/RootCollectionService.java | 27 +
.../usergrid/services/groups/GroupsService.java | 224 +
.../groups/activities/ActivitiesService.java | 74 +
.../services/groups/roles/RolesService.java | 32 +
.../services/groups/users/UsersService.java | 32 +
.../users/activities/ActivitiesService.java | 84 +
.../groups/users/devices/DevicesService.java | 32 +
.../services/messages/MessagesService.java | 33 +
.../usergrid/services/roles/RolesService.java | 236 +
.../services/roles/groups/GroupsService.java | 32 +
.../services/roles/users/UsersService.java | 84 +
.../usergrid/services/users/UsersService.java | 287 +
.../users/activities/ActivitiesService.java | 142 +
.../services/users/devices/DevicesService.java | 32 +
.../users/following/FollowingService.java | 47 +
.../services/users/groups/GroupsService.java | 32 +
.../services/users/roles/RolesService.java | 84 +
.../org/apache/usergrid/utils/PythonUtils.java | 102 +
.../management/AccountCreationProps.java | 119 -
.../usergrid/management/ActivationState.java | 8 -
.../usergrid/management/ApplicationCreator.java | 14 -
.../usergrid/management/ApplicationInfo.java | 134 -
.../usergrid/management/ManagementService.java | 319 -
.../usergrid/management/OrganizationInfo.java | 185 -
.../management/OrganizationOwnerInfo.java | 53 -
.../management/OrganizationProfile.java | 87 -
.../java/org/usergrid/management/UserInfo.java | 149 -
.../cassandra/AccountCreationPropsImpl.java | 112 -
.../cassandra/ApplicationCreatorImpl.java | 77 -
.../cassandra/ManagementServiceImpl.java | 2909 -
.../ApplicationCreationException.java | 26 -
.../exceptions/DisabledAdminUserException.java | 42 -
.../exceptions/DisabledAppUserException.java | 42 -
.../exceptions/IncorrectPasswordException.java | 42 -
.../exceptions/ManagementException.java | 42 -
.../RecentlyUsedPasswordException.java | 27 -
.../UnableToLeaveOrganizationException.java | 42 -
.../UnactivatedAdminUserException.java | 42 -
.../exceptions/UnactivatedAppUserException.java | 42 -
.../UnactivatedOrganizationException.java | 42 -
.../UnconfirmedAdminUserException.java | 42 -
.../usergrid/management/utils/AccountUtils.java | 42 -
.../usergrid/security/AuthPrincipalInfo.java | 71 -
.../usergrid/security/AuthPrincipalType.java | 115 -
.../security/crypto/EncryptionService.java | 70 -
.../security/crypto/EncryptionServiceImpl.java | 208 -
.../security/crypto/command/BcryptCommand.java | 92 -
.../crypto/command/EncryptionCommand.java | 49 -
.../security/crypto/command/Md5HashCommand.java | 61 -
.../crypto/command/PlainTextCommand.java | 64 -
.../crypto/command/SaltedHasherCommand.java | 67 -
.../crypto/command/Sha1HashCommand.java | 73 -
.../org/usergrid/security/oauth/AccessInfo.java | 187 -
.../security/oauth/ClientCredentialsInfo.java | 93 -
.../org/usergrid/security/oauth/OAuthProxy.java | 43 -
.../security/oauth/OAuthProxyFactory.java | 31 -
.../security/providers/AbstractProvider.java | 61 -
.../security/providers/FacebookProvider.java | 183 -
.../security/providers/FoursquareProvider.java | 159 -
.../providers/PingIdentityProvider.java | 143 -
.../security/providers/SignInAsProvider.java | 19 -
.../providers/SignInProviderFactory.java | 51 -
.../security/salt/NoOpSaltProvider.java | 36 -
.../security/salt/PropertiesSaltProvider.java | 53 -
.../usergrid/security/salt/SaltProvider.java | 31 -
.../security/shiro/CustomPermission.java | 225 -
.../shiro/CustomPermissionResolver.java | 29 -
.../shiro/PrincipalCredentialsToken.java | 139 -
.../java/org/usergrid/security/shiro/Realm.java | 540 -
.../AbstractAccessTokenCredentials.java | 33 -
.../credentials/AbstractClientCredentials.java | 28 -
.../AbstractPasswordCredentials.java | 33 -
.../credentials/AccessTokenCredentials.java | 22 -
.../shiro/credentials/AdminUserAccessToken.java | 24 -
.../shiro/credentials/AdminUserCredentials.java | 21 -
.../shiro/credentials/AdminUserPassword.java | 24 -
.../credentials/ApplicationAccessToken.java | 24 -
.../ApplicationClientCredentials.java | 24 -
.../credentials/ApplicationCredentials.java | 21 -
.../shiro/credentials/ApplicationGuest.java | 24 -
.../credentials/ApplicationUserAccessToken.java | 24 -
.../credentials/ApplicationUserCredentials.java | 21 -
.../credentials/ApplicationUserPassword.java | 24 -
.../shiro/credentials/ClientCredentials.java | 24 -
.../credentials/OrganizationAccessToken.java | 24 -
.../OrganizationClientCredentials.java | 24 -
.../credentials/OrganizationCredentials.java | 21 -
.../shiro/credentials/PasswordCredentials.java | 22 -
.../shiro/credentials/PrincipalCredentials.java | 21 -
.../shiro/principals/AdminUserPrincipal.java | 29 -
.../principals/ApplicationGuestPrincipal.java | 48 -
.../shiro/principals/ApplicationPrincipal.java | 48 -
.../principals/ApplicationUserPrincipal.java | 35 -
.../shiro/principals/OrganizationPrincipal.java | 48 -
.../shiro/principals/PrincipalIdentifier.java | 51 -
.../shiro/principals/UserPrincipal.java | 69 -
.../security/shiro/utils/SubjectUtils.java | 449 -
.../usergrid/security/tokens/TokenCategory.java | 83 -
.../org/usergrid/security/tokens/TokenInfo.java | 125 -
.../usergrid/security/tokens/TokenService.java | 39 -
.../tokens/cassandra/TokenServiceImpl.java | 627 -
.../tokens/exceptions/BadTokenException.java | 32 -
.../exceptions/ExpiredTokenException.java | 32 -
.../exceptions/InvalidTokenException.java | 32 -
.../tokens/exceptions/TokenException.java | 35 -
.../services/AbstractCollectionService.java | 571 -
.../services/AbstractConnectionsService.java | 521 -
.../AbstractPathBasedColllectionService.java | 149 -
.../org/usergrid/services/AbstractService.java | 1306 -
.../java/org/usergrid/services/Service.java | 49 -
.../org/usergrid/services/ServiceAction.java | 21 -
.../ServiceCollectionEventListener.java | 22 -
.../org/usergrid/services/ServiceContext.java | 449 -
.../services/ServiceExecutionEvent.java | 79 -
.../services/ServiceExecutionEventListener.java | 22 -
.../java/org/usergrid/services/ServiceInfo.java | 438 -
.../org/usergrid/services/ServiceManager.java | 431 -
.../services/ServiceManagerFactory.java | 131 -
.../org/usergrid/services/ServiceParameter.java | 452 -
.../org/usergrid/services/ServicePayload.java | 199 -
.../org/usergrid/services/ServiceRequest.java | 372 -
.../org/usergrid/services/ServiceResults.java | 304 -
.../org/usergrid/services/ServiceUtils.java | 21 -
.../services/activities/ActivitiesService.java | 33 -
.../applications/ApplicationsService.java | 215 -
.../usergrid/services/assets/AssetsService.java | 57 -
.../services/assets/data/AssetMimeHandler.java | 90 -
.../services/assets/data/AssetUtils.java | 107 -
.../services/assets/data/BinaryStore.java | 27 -
.../assets/data/LocalFileBinaryStore.java | 85 -
.../services/assets/data/S3BinaryStore.java | 202 -
.../services/devices/DevicesService.java | 51 -
.../services/devices/users/UsersService.java | 32 -
.../ForbiddenServiceOperationException.java | 41 -
.../services/exceptions/ServiceException.java | 45 -
.../exceptions/ServiceInvocationException.java | 83 -
.../ServiceResourceNotFoundException.java | 39 -
.../UndefinedServiceEntityTypeException.java | 45 -
.../UnsupportedServiceOperationException.java | 39 -
.../generic/GenericCollectionService.java | 27 -
.../generic/GenericConnectionsService.java | 27 -
.../services/generic/RootCollectionService.java | 27 -
.../usergrid/services/groups/GroupsService.java | 224 -
.../groups/activities/ActivitiesService.java | 74 -
.../services/groups/roles/RolesService.java | 32 -
.../services/groups/users/UsersService.java | 32 -
.../users/activities/ActivitiesService.java | 84 -
.../groups/users/devices/DevicesService.java | 32 -
.../services/messages/MessagesService.java | 33 -
.../usergrid/services/roles/RolesService.java | 236 -
.../services/roles/groups/GroupsService.java | 32 -
.../services/roles/users/UsersService.java | 84 -
.../usergrid/services/users/UsersService.java | 287 -
.../users/activities/ActivitiesService.java | 142 -
.../services/users/devices/DevicesService.java | 32 -
.../users/following/FollowingService.java | 47 -
.../services/users/groups/GroupsService.java | 32 -
.../services/users/roles/RolesService.java | 84 -
.../java/org/usergrid/utils/PythonUtils.java | 102 -
.../pyusergrid/services/pytest/PytestService.py | 4 +-
.../python/pyusergrid/services/pytest/test.py | 2 +-
stack/services/src/main/python/test/test.py | 2 +-
.../resources/usergrid-services-context.xml | 18 +-
.../test/java/baas/io/simple/SimpleService.java | 2 +-
.../usergrid/ConcurrentServiceITSuite.java | 43 +
.../org/apache/usergrid/ServiceApplication.java | 188 +
.../org/apache/usergrid/ServiceITSetup.java | 44 +
.../org/apache/usergrid/ServiceITSetupImpl.java | 129 +
.../org/apache/usergrid/ServiceITSuite.java | 41 +
.../apache/usergrid/management/EmailFlowIT.java | 419 +
.../management/ManagementTestHelper.java | 40 +
.../usergrid/management/MockImapClient.java | 83 +
.../usergrid/management/OrganizationIT.java | 229 +
.../org/apache/usergrid/management/RoleIT.java | 97 +
.../cassandra/ApplicationCreatorIT.java | 66 +
.../cassandra/ManagementServiceIT.java | 729 +
.../cassandra/ManagementTestHelperImpl.java | 85 +
.../org/apache/usergrid/python/JythonTest.java | 38 +
.../usergrid/security/CustomResolverTest.java | 169 +
.../crypto/EncryptionServiceImplTest.java | 170 +
.../crypto/command/BcryptCommandTest.java | 165 +
.../crypto/command/Md5HashCommandTest.java | 71 +
.../crypto/command/Sha1HashCommandTest.java | 67 +
.../security/providers/FacebookProviderIT.java | 81 +
.../providers/PingIdentityProviderIT.java | 63 +
.../security/tokens/TokenServiceIT.java | 440 +
.../usergrid/services/AbstractServiceIT.java | 38 +
.../usergrid/services/ActivitiesServiceIT.java | 111 +
.../services/ApplicationsServiceIT.java | 35 +
.../usergrid/services/CollectionServiceIT.java | 290 +
.../usergrid/services/ConnectionsServiceIT.java | 82 +
.../usergrid/services/GroupServiceIT.java | 80 +
.../usergrid/services/RolesServiceIT.java | 279 +
.../usergrid/services/ServiceFactoryIT.java | 57 +
.../usergrid/services/ServiceInfoTest.java | 108 +
.../usergrid/services/ServiceInvocationIT.java | 145 +
.../usergrid/services/ServiceRequestIT.java | 78 +
.../usergrid/services/UsersServiceIT.java | 52 +
.../services/assets/data/AssetUtilsTest.java | 44 +
.../org/usergrid/ConcurrentServiceITSuite.java | 43 -
.../java/org/usergrid/ServiceApplication.java | 188 -
.../test/java/org/usergrid/ServiceITSetup.java | 44 -
.../java/org/usergrid/ServiceITSetupImpl.java | 129 -
.../test/java/org/usergrid/ServiceITSuite.java | 41 -
.../org/usergrid/management/EmailFlowIT.java | 419 -
.../management/ManagementTestHelper.java | 40 -
.../org/usergrid/management/MockImapClient.java | 83 -
.../org/usergrid/management/OrganizationIT.java | 229 -
.../java/org/usergrid/management/RoleIT.java | 97 -
.../cassandra/ApplicationCreatorIT.java | 66 -
.../cassandra/ManagementServiceIT.java | 729 -
.../cassandra/ManagementTestHelperImpl.java | 85 -
.../java/org/usergrid/python/JythonTest.java | 38 -
.../usergrid/security/CustomResolverTest.java | 169 -
.../crypto/EncryptionServiceImplTest.java | 170 -
.../crypto/command/BcryptCommandTest.java | 165 -
.../crypto/command/Md5HashCommandTest.java | 71 -
.../crypto/command/Sha1HashCommandTest.java | 67 -
.../security/providers/FacebookProviderIT.java | 81 -
.../providers/PingIdentityProviderIT.java | 63 -
.../security/tokens/TokenServiceIT.java | 440 -
.../usergrid/services/AbstractServiceIT.java | 38 -
.../usergrid/services/ActivitiesServiceIT.java | 111 -
.../services/ApplicationsServiceIT.java | 35 -
.../usergrid/services/CollectionServiceIT.java | 290 -
.../usergrid/services/ConnectionsServiceIT.java | 82 -
.../org/usergrid/services/GroupServiceIT.java | 80 -
.../org/usergrid/services/RolesServiceIT.java | 279 -
.../org/usergrid/services/ServiceFactoryIT.java | 57 -
.../org/usergrid/services/ServiceInfoTest.java | 108 -
.../usergrid/services/ServiceInvocationIT.java | 145 -
.../org/usergrid/services/ServiceRequestIT.java | 78 -
.../org/usergrid/services/UsersServiceIT.java | 52 -
.../services/assets/data/AssetUtilsTest.java | 44 -
.../src/test/resources/log4j.properties | 14 +-
.../test/resources/usergrid-test-context.xml | 8 +-
stack/test-utils/pom.xml | 8 +-
.../apache/usergrid/NoExitSecurityManager.java | 64 +
.../usergrid/cassandra/AvailablePortFinder.java | 211 +
.../usergrid/cassandra/CassandraResource.java | 505 +
.../usergrid/cassandra/ClearShiroSubject.java | 31 +
.../apache/usergrid/cassandra/Concurrent.java | 15 +
.../cassandra/ConcurrentJunitRunner.java | 75 +
.../usergrid/cassandra/ConcurrentSuite.java | 101 +
.../apache/usergrid/cassandra/DataControl.java | 17 +
.../apache/usergrid/cassandra/DataLoader.java | 9 +
.../usergrid/cassandra/SchemaManager.java | 18 +
.../org/usergrid/NoExitSecurityManager.java | 64 -
.../usergrid/cassandra/AvailablePortFinder.java | 211 -
.../usergrid/cassandra/CassandraResource.java | 505 -
.../usergrid/cassandra/ClearShiroSubject.java | 31 -
.../java/org/usergrid/cassandra/Concurrent.java | 15 -
.../cassandra/ConcurrentJunitRunner.java | 75 -
.../org/usergrid/cassandra/ConcurrentSuite.java | 101 -
.../org/usergrid/cassandra/DataControl.java | 17 -
.../java/org/usergrid/cassandra/DataLoader.java | 9 -
.../org/usergrid/cassandra/SchemaManager.java | 18 -
.../cassandra/AnotherCassandraResourceIT.java | 68 +
.../cassandra/CassandraResourceITSuite.java | 25 +
.../cassandra/CassandraResourceTest.java | 104 +
.../usergrid/cassandra/FakeSchemaManager.java | 32 +
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 +
.../YetAnotherCassandraResourceIT.java | 70 +
.../cassandra/AnotherCassandraResourceIT.java | 68 -
.../cassandra/CassandraResourceITSuite.java | 25 -
.../cassandra/CassandraResourceTest.java | 104 -
.../usergrid/cassandra/FakeSchemaManager.java | 32 -
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 -
.../YetAnotherCassandraResourceIT.java | 70 -
.../test/resources/usergrid-test-context.xml | 6 +-
stack/tools/README.md | 4 +-
stack/tools/pom.xml | 20 +-
.../java/org/apache/usergrid/tools/ApiDoc.java | 114 +
.../org/apache/usergrid/tools/AppAudit.java | 231 +
.../org/apache/usergrid/tools/AppNameFix.java | 109 +
.../java/org/apache/usergrid/tools/Cli.java | 269 +
.../java/org/apache/usergrid/tools/Command.java | 99 +
.../org/apache/usergrid/tools/CredExport.java | 122 +
.../apache/usergrid/tools/DupAdminRepair.java | 310 +
.../org/apache/usergrid/tools/DupOrgRepair.java | 266 +
.../apache/usergrid/tools/EntityCleanup.java | 176 +
.../usergrid/tools/EntityInsertBenchMark.java | 273 +
.../usergrid/tools/EntityReadBenchMark.java | 360 +
.../org/apache/usergrid/tools/EntityUpdate.java | 191 +
.../java/org/apache/usergrid/tools/Export.java | 431 +
.../usergrid/tools/ExportDataCreator.java | 105 +
.../usergrid/tools/ExportingToolBase.java | 183 +
.../java/org/apache/usergrid/tools/Import.java | 545 +
.../org/apache/usergrid/tools/ImportFB.java | 101 +
.../org/apache/usergrid/tools/IndexRebuild.java | 206 +
.../java/org/apache/usergrid/tools/Metrics.java | 213 +
.../usergrid/tools/OrganizationExport.java | 117 +
.../apache/usergrid/tools/PopulateSample.java | 142 +
.../apache/usergrid/tools/ResetSuperUser.java | 105 +
.../java/org/apache/usergrid/tools/SetupDB.java | 57 +
.../java/org/apache/usergrid/tools/Test.java | 53 +
.../org/apache/usergrid/tools/ToolBase.java | 246 +
.../usergrid/tools/UniqueIndexCleanup.java | 381 +
.../org/apache/usergrid/tools/UserManager.java | 45 +
.../apache/usergrid/tools/WarehouseExport.java | 516 +
.../apache/usergrid/tools/WarehouseUpsert.java | 153 +
.../usergrid/tools/apidoc/swagger/Api.java | 92 +
.../tools/apidoc/swagger/ApiListing.java | 145 +
.../tools/apidoc/swagger/ApiOperation.java | 247 +
.../tools/apidoc/swagger/ApiOperationError.java | 60 +
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 +
.../apidoc/swagger/ApiParamAllowableValues.java | 62 +
.../apache/usergrid/tools/bean/AppScore.java | 82 +
.../apache/usergrid/tools/bean/ExportOrg.java | 69 +
.../apache/usergrid/tools/bean/MetricLine.java | 82 +
.../apache/usergrid/tools/bean/MetricQuery.java | 93 +
.../apache/usergrid/tools/bean/MetricSort.java | 26 +
.../apache/usergrid/tools/bean/OrgScore.java | 93 +
.../main/java/org/usergrid/tools/ApiDoc.java | 114 -
.../main/java/org/usergrid/tools/AppAudit.java | 231 -
.../java/org/usergrid/tools/AppNameFix.java | 109 -
.../src/main/java/org/usergrid/tools/Cli.java | 269 -
.../main/java/org/usergrid/tools/Command.java | 99 -
.../java/org/usergrid/tools/CredExport.java | 122 -
.../java/org/usergrid/tools/DupAdminRepair.java | 310 -
.../java/org/usergrid/tools/DupOrgRepair.java | 266 -
.../java/org/usergrid/tools/EntityCleanup.java | 176 -
.../usergrid/tools/EntityInsertBenchMark.java | 273 -
.../org/usergrid/tools/EntityReadBenchMark.java | 360 -
.../java/org/usergrid/tools/EntityUpdate.java | 191 -
.../main/java/org/usergrid/tools/Export.java | 431 -
.../org/usergrid/tools/ExportDataCreator.java | 105 -
.../org/usergrid/tools/ExportingToolBase.java | 183 -
.../main/java/org/usergrid/tools/Import.java | 545 -
.../main/java/org/usergrid/tools/ImportFB.java | 101 -
.../java/org/usergrid/tools/IndexRebuild.java | 206 -
.../main/java/org/usergrid/tools/Metrics.java | 213 -
.../org/usergrid/tools/OrganizationExport.java | 117 -
.../java/org/usergrid/tools/PopulateSample.java | 142 -
.../java/org/usergrid/tools/ResetSuperUser.java | 105 -
.../main/java/org/usergrid/tools/SetupDB.java | 57 -
.../src/main/java/org/usergrid/tools/Test.java | 53 -
.../main/java/org/usergrid/tools/ToolBase.java | 246 -
.../org/usergrid/tools/UniqueIndexCleanup.java | 381 -
.../java/org/usergrid/tools/UserManager.java | 45 -
.../org/usergrid/tools/WarehouseExport.java | 516 -
.../org/usergrid/tools/WarehouseUpsert.java | 153 -
.../org/usergrid/tools/apidoc/swagger/Api.java | 92 -
.../tools/apidoc/swagger/ApiListing.java | 145 -
.../tools/apidoc/swagger/ApiOperation.java | 247 -
.../tools/apidoc/swagger/ApiOperationError.java | 60 -
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 -
.../apidoc/swagger/ApiParamAllowableValues.java | 62 -
.../java/org/usergrid/tools/bean/AppScore.java | 82 -
.../java/org/usergrid/tools/bean/ExportOrg.java | 58 -
.../org/usergrid/tools/bean/MetricLine.java | 82 -
.../org/usergrid/tools/bean/MetricQuery.java | 93 -
.../org/usergrid/tools/bean/MetricSort.java | 26 -
.../java/org/usergrid/tools/bean/OrgScore.java | 93 -
stack/tools/src/main/resources/log4j.xml | 2 +-
stack/websocket/pom.xml | 12 +-
.../websocket/WebSocketChannelHandler.java | 357 +
.../usergrid/websocket/WebSocketKeyStore.java | 49 +
.../usergrid/websocket/WebSocketServer.java | 195 +
.../websocket/WebSocketServerIndexPage.java | 71 +
.../WebSocketServerPipelineFactory.java | 75 +
.../websocket/WebSocketSslContextFactory.java | 62 +
.../websocket/WebSocketChannelHandler.java | 357 -
.../usergrid/websocket/WebSocketKeyStore.java | 49 -
.../org/usergrid/websocket/WebSocketServer.java | 195 -
.../websocket/WebSocketServerIndexPage.java | 71 -
.../WebSocketServerPipelineFactory.java | 75 -
.../websocket/WebSocketSslContextFactory.java | 62 -
.../usergrid/websocket/ExampleListener.java | 41 +
.../websocket/SimpleMessageProducer.java | 61 +
.../usergrid/websocket/WebSocketServerTest.java | 43 +
.../org/usergrid/websocket/ExampleListener.java | 41 -
.../websocket/SimpleMessageProducer.java | 61 -
.../usergrid/websocket/WebSocketServerTest.java | 42 -
.../test/resources/testApplicationContext.xml | 20 +-
2261 files changed, 167527 insertions(+), 263803 deletions(-)
----------------------------------------------------------------------
[05/50] [abbrv] git commit: fixing issues in test cases
Posted by sn...@apache.org.
fixing issues in test cases
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/017cf300
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/017cf300
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/017cf300
Branch: refs/heads/optimistic-tx-semantics
Commit: 017cf300087a66d70faef91cdbf3d87799b024b8
Parents: 9dfc562
Author: ryan bridges <rb...@apigee.com>
Authored: Mon Feb 10 14:26:34 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Mon Feb 10 14:26:34 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/Gruntfile.js | 3 +-
sdks/html5-javascript/lib/Usergrid.js | 257 +-----
sdks/html5-javascript/lib/modules/Asset.js | 2 +-
sdks/html5-javascript/lib/modules/Client.js | 91 +-
sdks/html5-javascript/lib/modules/Entity.js | 4 +-
sdks/html5-javascript/lib/modules/Folder.js | 2 +-
sdks/html5-javascript/lib/modules/util/Ajax.js | 24 +-
sdks/html5-javascript/tests/mocha/test.js | 71 +-
sdks/html5-javascript/usergrid.js | 918 +++++++++++++++-----
sdks/html5-javascript/usergrid.min.js | 6 +-
10 files changed, 807 insertions(+), 571 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/Gruntfile.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/Gruntfile.js b/sdks/html5-javascript/Gruntfile.js
index 58d5a2a..527633d 100644
--- a/sdks/html5-javascript/Gruntfile.js
+++ b/sdks/html5-javascript/Gruntfile.js
@@ -5,9 +5,8 @@ module.exports = function(grunt) {
"lib/modules/util/Promise.js",
"lib/modules/util/Ajax.js",
"lib/modules/util/Storable.js",
-// "lib/modules/util/KeyStore.js",
"lib/Usergrid.js",
-// "lib/modules/Client.js",
+ "lib/modules/Client.js",
"lib/modules/Entity.js",
"lib/modules/Collection.js",
"lib/modules/Group.js",
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index 1a4e5dd..f545964 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -133,18 +133,19 @@ function isFunction(f) {
* @return Returns whatever would be returned by the callback. or false.
*/
function doCallback(callback, params, context) {
+ console.info("CALLED FROM", this.name||(context)?context.name:"UNKNOWN");
var returnValue;
if (isFunction(callback)) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- try {
+ //try {
returnValue = callback.apply(context, params);
- } catch (ex) {
+ /*} catch (ex) {
if (console && console.error) {
console.error("Callback error:", ex);
}
- }
+ }*/
}
return returnValue;
}
@@ -185,7 +186,7 @@ function doCallback(callback, params, context) {
Prepare our request
*/
if (!isValidUrl(this.endpoint)) {
- this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint), api_uri, orgName, appName);
+ this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint));
throw new UsergridError("The provided endpoint is not valid: " + this.endpoint);
}
/* a callback to make the request */
@@ -272,254 +273,6 @@ function doCallback(callback, params, context) {
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(){};
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/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
index 0eed742..8af84e1 100644
--- a/sdks/html5-javascript/lib/modules/Asset.js
+++ b/sdks/html5-javascript/lib/modules/Asset.js
@@ -38,7 +38,7 @@ Usergrid.Asset = function(options, callback) {
if (err) {
doCallback(callback, [true, new Usergrid.Error(data)], self);
} else {
- if (data.entities.length){
+ if (data && data.entities && data.entities.length){
self.set(data.entities[0]);
}
doCallback(callback, [false, self], self);
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/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
index 727e257..cf78df7 100644
--- a/sdks/html5-javascript/lib/modules/Client.js
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -1,6 +1,6 @@
(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';
@@ -21,10 +21,6 @@ exports = (function() {
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');
- });
};
/*
@@ -71,8 +67,21 @@ exports = (function() {
xhr.withCredentials = true;
*/
}
-
- //append params to the path
+ var req = new Usergrid.Request(method, uri, 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);
+ });
+ /*//append params to the path
var encoded_params = encodeParams(qs);
if (encoded_params) {
uri += "?" + encoded_params;
@@ -175,7 +184,7 @@ exports = (function() {
this.buildCurlCall(curlOptions);
}
this._start = new Date().getTime();
- xhr.send(body);
+ xhr.send(body);*/
}
/*
@@ -250,35 +259,33 @@ exports = (function() {
* @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);
- }
+ 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) {
+ //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 && getOnExist)||(err && err.name && common_errors.indexOf(err.name) !== -1);
+
+ 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, [null, entity, data]);
+ }
});
- } else {
- if (typeof(callback) === 'function') {
- callback(err, entity, data);
- }
- }
- });
-
- };
+ };
/*
* Main function for getting existing entities - should be called directly.
*
@@ -300,9 +307,7 @@ exports = (function() {
}
var entity = new Usergrid.Entity(options);
entity.fetch(function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, entity, data);
- }
+ doCallback(callback, [err, entity, data]);
});
};
@@ -340,9 +345,7 @@ exports = (function() {
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);
- }
+ doCallback(callback, [err, collection, data]);
});
};
@@ -465,7 +468,7 @@ exports = (function() {
"height":80,
"url":user.get("picture"),
"width":80
- },
+ }
},
"verb":"post",
"content":content
@@ -846,9 +849,7 @@ exports = (function() {
return image;
}
}
- return Usergrid.Client;
-}());
- global[name] = exports;
+ global[name] = Usergrid.Client;
global[name].noConflict = function() {
if(overwrittenName){
global[name] = overwrittenName;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/lib/modules/Entity.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Entity.js b/sdks/html5-javascript/lib/modules/Entity.js
index e84e400..05ea970 100644
--- a/sdks/html5-javascript/lib/modules/Entity.js
+++ b/sdks/html5-javascript/lib/modules/Entity.js
@@ -260,7 +260,7 @@ Usergrid.Entity.prototype.fetch = function (callback) {
if(entity){
self.set(entity);
}
- console.log("AFTER FETCH", self.get(), entity, response);
+ console.log("AFTER FETCH", err, self.get(), entity, response);
doCallback(callback,[err, entity, self]);
});
};
@@ -417,7 +417,7 @@ Usergrid.Entity.prototype.getConnections = function (connection, callback) {
self[connection] = {};
- var length = data.entities.length;
+ var length = (data && data.entities)?data.entities.length:0;
for (var i = 0; i < length; i++) {
if (data.entities[i].type === 'user'){
self[connection][data.entities[i].username] = data.entities[i];
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/lib/modules/Folder.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Folder.js b/sdks/html5-javascript/lib/modules/Folder.js
index 11d7521..7e2821f 100644
--- a/sdks/html5-javascript/lib/modules/Folder.js
+++ b/sdks/html5-javascript/lib/modules/Folder.js
@@ -20,7 +20,7 @@ Usergrid.Folder = function(options, callback) {
if (err) {
doCallback(callback, [true, new Usergrid.Error(data)], self);
} else {
- if (data.entities.length){
+ if (data && data.entities && data.entities.length){
self.set(data.entities[0]);
}
doCallback(callback, [false, self], self);
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/lib/modules/util/Ajax.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/util/Ajax.js b/sdks/html5-javascript/lib/modules/util/Ajax.js
index e8228ea..5b36ad5 100644
--- a/sdks/html5-javascript/lib/modules/util/Ajax.js
+++ b/sdks/html5-javascript/lib/modules/util/Ajax.js
@@ -2,12 +2,16 @@
(function() {
var name = 'Ajax', global = this, overwrittenName = global[name], exports;
- Function.prototype.partial = function() {
+ /*Function.prototype.partial = function() {
var fn = this,b = [].slice.call(arguments);
return fn.bind(undefined, b);
+ }*/
+ function partial(fn){
+ var args = Array.prototype.slice.call(arguments,1);
+ return function(){
+ return fn.apply(this, args.concat(Array.prototype.slice(arguments,0)))
+ }
}
-
- exports = (function() {
function Ajax() {
this.logger=new global.Logger(name);
var self=this;
@@ -25,7 +29,7 @@
}
return result;
}
- var request = function(m, u, d) {
+ function request(m, u, d) {
var p = new Promise(), timeout;
self.logger.time(m + ' ' + u);
self.logger.timeEnd(m + ' ' + u);
@@ -56,14 +60,12 @@
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');
+ this.get = partial(request, 'GET');
+ this.post = partial(request, 'POST');
+ this.put = partial(request, 'PUT');
+ this.delete = partial(request, 'DELETE');
}
- return new Ajax();
- }());
- global[name] = exports;
+ global[name] = new Ajax();
global[name].noConflict = function() {
if(overwrittenName){
global[name] = overwrittenName;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index ec132a8..50229e1 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -221,6 +221,7 @@ describe('Usergrid', function() {
if (done) done();
}
before(function(done) {
+ console.log("remove existing dogs");
//Make sure our dog doesn't already exist
var options = {
type: 'dogs',
@@ -234,11 +235,12 @@ describe('Usergrid', function() {
assert(!err, "could not retrieve list of dogs: " + dogs.error_description);
//we got 50 dogs, now display the Entities:
//do doggy cleanup
- if (dogs.hasNextEntity()) {
+ //if (dogs.hasNextEntity()) {
while (dogs.hasNextEntity()) {
//get a reference to the dog
var dog = dogs.getNextEntity();
//notice('removing dog ' + dogname + ' from database');
+ if(dog === null) continue;
dog.destroy(function(err, data) {
assert(!err, dog.get('name') + " not removed: " + data.error_description);
if (!dogs.hasNextEntity()) {
@@ -246,30 +248,12 @@ describe('Usergrid', function() {
}
});
}
- } else {
+ //} else {
done();
- }
+ //}
}
});
});
- before(function(done) {
- this.timeout(10000);
- var totalDogs = 30;
- Array.apply(0, Array(totalDogs)).forEach(function(x, y) {
- var dogNum = y + 1;
- var options = {
- type: 'dogs',
- name: 'dog' + dogNum,
- index: y
- }
- client.createEntity(options, function(err, dog) {
- assert(!err, " not created: " + dog.error_description);
- if (dogNum === totalDogs) {
- done();
- }
- });
- })
- });
it('should CREATE a new dogs collection', function(done) {
var options = {
type: 'dogs',
@@ -284,9 +268,28 @@ describe('Usergrid', function() {
done();
});
});
- it('should RETRIEVE dogs from the collection', function(done) {
- loop(done);
- });
+ it('should CREATE dogs in the collection', function(done) {
+ this.timeout(10000);
+ var totalDogs = 30;
+ Array.apply(0, Array(totalDogs)).forEach(function(x, y) {
+ var dogNum = y + 1;
+ var options = {
+ type: 'dogs',
+ name: 'dog' + dogNum,
+ index: y
+ }
+ client.createEntity(options, function(err, dog) {
+ console.log(err, dog);
+ assert(!err, "dog not created");
+ if (dogNum === totalDogs) {
+ done();
+ }
+ });
+ })
+ });
+ it('should RETRIEVE dogs from the collection', function(done) {
+ loop(done);
+ });
it('should RETRIEVE the next page of dogs from the collection', function(done) {
if (dogs.hasNextPage()) {
dogs.getNextPage(function(err) {
@@ -425,9 +428,11 @@ describe('Usergrid', function() {
req.onload = function() {
test_image = req.response;
image_type = req.getResponseHeader('Content-Type');
+ console.log(test_image, image_type);
done();
}
req.onerror = function(err) {
+ console.error(err);
done();
};
req.send(null);
@@ -438,9 +443,12 @@ describe('Usergrid', function() {
method: 'GET',
endpoint: 'Assets'
}, function(err, data) {
- var assets = data.entities.filter(function(asset) {
- return asset.name === filename
- });
+ var assets = [];
+ if(data && data.entities && data.entities.length){
+ assets.concat(data.entities.filter(function(asset) {
+ return asset.name === filename
+ }));
+ }
if (assets.length) {
assets.forEach(function(asset) {
client.request({
@@ -460,9 +468,12 @@ describe('Usergrid', function() {
method: 'GET',
endpoint: 'folders'
}, function(err, data) {
- var folders = data.entities.filter(function(folder) {
- return folder.name === foldername
- });
+ var folders = [];
+ if(data && data.entities && data.entities.length){
+ folders.concat(data.entities.filter(function(folder) {
+ return folder.name === foldername
+ }));
+ }
if (folders.length) {
folders.forEach(function(folder) {
client.request({
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/017cf300/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 8990b83..542fb38 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -1,4 +1,4 @@
-/*! usergrid@0.0.0 2014-02-06 */
+/*! usergrid@0.0.0 2014-02-10 */
var UsergridEventable = function() {
throw Error("'UsergridEventable' is not intended to be invoked directly");
};
@@ -181,68 +181,71 @@ UsergridEventable.mixin = function(destObject) {
//Ajax
(function() {
var name = "Ajax", global = this, overwrittenName = global[name], exports;
- Function.prototype.partial = function() {
- var fn = this, b = [].slice.call(arguments);
+ /*Function.prototype.partial = function() {
+ var fn = this,b = [].slice.call(arguments);
return fn.bind(undefined, b);
- };
- 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]);
- }
+ }*/
+ function partial(fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function() {
+ return fn.apply(this, args.concat(Array.prototype.slice(arguments, 0)));
+ };
+ }
+ 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(), timeout;
- self.logger.time(m + " " + u);
- self.logger.timeEnd(m + " " + u);
- (function(xhr) {
- xhr.onreadystatechange = function() {
- this.readyState ^ 4 || (self.logger.timeEnd(m + " " + u), clearTimeout(timeout),
- p.done(null, this));
- };
- xhr.onerror = function(response) {
- clearTimeout(timeout);
- p.done(response, null);
- };
- xhr.oncomplete = function(response) {
- clearTimeout(timeout);
- self.info("%s request to %s returned %s", m, u, this.status);
- };
- xhr.open(m, u);
- if (d) {
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.setRequestHeader("Accept", "application/json");
- }
- timeout = setTimeout(function() {
- xhr.abort();
- p.done("API Call timed out.", null);
- }, 3e4);
- //TODO stick that timeout in a config variable
- 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();
- }();
- global[name] = exports;
+ return result;
+ }
+ function request(m, u, d) {
+ var p = new Promise(), timeout;
+ self.logger.time(m + " " + u);
+ self.logger.timeEnd(m + " " + u);
+ (function(xhr) {
+ xhr.onreadystatechange = function() {
+ this.readyState ^ 4 || (self.logger.timeEnd(m + " " + u), clearTimeout(timeout),
+ p.done(null, this));
+ };
+ xhr.onerror = function(response) {
+ clearTimeout(timeout);
+ p.done(response, null);
+ };
+ xhr.oncomplete = function(response) {
+ clearTimeout(timeout);
+ self.info("%s request to %s returned %s", m, u, this.status);
+ };
+ xhr.open(m, u);
+ if (d) {
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.setRequestHeader("Accept", "application/json");
+ }
+ timeout = setTimeout(function() {
+ xhr.abort();
+ p.done("API Call timed out.", null);
+ }, 3e4);
+ //TODO stick that timeout in a config variable
+ xhr.send(encode(d));
+ })(new XMLHttpRequest());
+ return p;
+ }
+ this.request = request;
+ this.get = partial(request, "GET");
+ this.post = partial(request, "POST");
+ this.put = partial(request, "PUT");
+ this.delete = partial(request, "DELETE");
+ }
+ global[name] = new Ajax();
global[name].noConflict = function() {
if (overwrittenName) {
global[name] = overwrittenName;
@@ -491,18 +494,14 @@ function isFunction(f) {
* @return Returns whatever would be returned by the callback. or false.
*/
function doCallback(callback, params, context) {
+ console.info("CALLED FROM", this.name || context ? context.name : "UNKNOWN");
var returnValue;
if (isFunction(callback)) {
if (!params) params = [];
if (!context) context = this;
params.push(context);
- try {
- returnValue = callback.apply(context, params);
- } catch (ex) {
- if (console && console.error) {
- console.error("Callback error:", ex);
- }
- }
+ //try {
+ returnValue = callback.apply(context, params);
}
return returnValue;
}
@@ -539,7 +538,7 @@ function doCallback(callback, params, context) {
Prepare our request
*/
if (!isValidUrl(this.endpoint)) {
- this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint), api_uri, orgName, appName);
+ this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint));
throw new UsergridError("The provided endpoint is not valid: " + this.endpoint);
}
/* a callback to make the request */
@@ -629,96 +628,56 @@ function doCallback(callback, params, context) {
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);
- };
- /*
- 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;
+ //Usergrid.Entity=function(){};
+ //Usergrid.Collection=function(){};
+ global[name] = Usergrid;
+ global[name].noConflict = function() {
+ if (overwrittenName) {
+ global[name] = overwrittenName;
}
- return assetURL;
+ return Usergrid;
};
- /*
- * 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;
+ return global[name];
+})(this);
+
+(function() {
+ var name = "Client", global = this, overwrittenName = global[name], exports;
+ 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);
}
- var encoded_params = encodeParams(qs);
- if (encoded_params) {
- assetURL += "?" + encoded_params;
+ if (options.appName) {
+ this.set("appName", options.appName);
}
- return assetURL;
+ //other options
+ this.buildCurl = options.buildCurl || false;
+ this.logging = options.logging || false;
+ //timeout and callbacks
+ this._callTimeout = options.callTimeout || 3e4;
+ //default to 30 seconds
+ this._callTimeoutCallback = options.callTimeoutCallback || null;
+ this.logoutCallback = options.logoutCallback || null;
};
/*
- * 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)
- */
+ * 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;
@@ -726,39 +685,92 @@ function doCallback(callback, params, context) {
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("/");
+ 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 {
- endpoint = [ api_uri, endpoint ].join("/");
+ uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
}
- var req = new Usergrid.Request(method, endpoint, qs, body, function(err, response) {
+ if (self.getToken()) {
+ qs.access_token = self.getToken();
+ }
+ var req = new Usergrid.Request(method, uri, 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) {}
doCallback(callback, [ err, response ]);
- p.done(err, response);
});
- return p;
};
/*
- * 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)
- */
+ * 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.
@@ -773,10 +785,9 @@ function doCallback(callback, params, context) {
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;
+ var okToSave = !err && getOnExist || err && err.name && common_errors.indexOf(err.name) !== -1;
if (okToSave) {
entity.set(entity_data.data);
//add the data again just in case
@@ -784,80 +795,539 @@ function doCallback(callback, params, context) {
doCallback(callback, [ err, entity, data ]);
});
} else {
- doCallback(callback, [ err, entity, data ]);
+ doCallback(callback, [ null, 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])
- */
+ * 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 entity_data = {
+ var options = {
client: this,
data: options
};
- var entity = new Usergrid.Entity(entity_data);
+ var entity = new Usergrid.Entity(options);
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
- */
+ * 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({
+ var data = JSON.parse(serializedObject);
+ var options = {
client: this,
- data: JSON.parse(serializedObject)
- });
+ 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)
- */
+ * 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) {
+ doCallback(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") {
- callback(err, collection, data);
+ if (err) {
+ callback(err);
+ } else {
+ callback(err, data, data.entities);
+ }
}
});
};
- //Usergrid.Entity=function(){};
- //Usergrid.Collection=function(){};
- global[name] = Usergrid;
+ /*
+ * 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) {} finally {
+ return image;
+ }
+ };
+ global[name] = Usergrid.Client;
global[name].noConflict = function() {
if (overwrittenName) {
global[name] = overwrittenName;
}
- return Usergrid;
+ return exports;
};
return global[name];
-})(this);
+})();
/*
* A class to Model a Usergrid Entity.
@@ -1059,7 +1529,7 @@ Usergrid.Entity.prototype.fetch = function(callback) {
if (entity) {
self.set(entity);
}
- console.log("AFTER FETCH", self.get(), entity, response);
+ console.log("AFTER FETCH", err, self.get(), entity, response);
doCallback(callback, [ err, entity, self ]);
});
};
@@ -1206,7 +1676,7 @@ Usergrid.Entity.prototype.getConnections = function(connection, callback) {
console.log("entity could not be connected");
}
self[connection] = {};
- var length = data.entities.length;
+ var length = data && data.entities ? data.entities.length : 0;
for (var i = 0; i < length; i++) {
if (data.entities[i].type === "user") {
self[connection][data.entities[i].username] = data.entities[i];
@@ -2307,7 +2777,7 @@ Usergrid.Folder = function(options, callback) {
if (err) {
doCallback(callback, [ true, new Usergrid.Error(data) ], self);
} else {
- if (data.entities.length) {
+ if (data && data.entities && data.entities.length) {
self.set(data.entities[0]);
}
doCallback(callback, [ false, self ], self);
@@ -2495,7 +2965,7 @@ Usergrid.Asset = function(options, callback) {
if (err) {
doCallback(callback, [ true, new Usergrid.Error(data) ], self);
} else {
- if (data.entities.length) {
+ if (data && data.entities && data.entities.length) {
self.set(data.entities[0]);
}
doCallback(callback, [ false, self ], self);
[12/50] [abbrv] Fixed issues with
Usergrid.Client.prototype.createGroup. Added more tests
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/49783334/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index eb8fafa..f7b4d36 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-10 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;if(isFunction(callback)){params||(params=[]),context||(context=this),params.push(context);try{returnValue=callback.apply(context,params)}catch(ex){console&&console.error&&console.error("Callback error:",ex)}}return returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventabl
e.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.ini
t(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&c
onsole[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new
Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)})
,p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-T
ype","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStora
ge' is not a browser Storage interface. using sessionStorage"),this._storage=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token
){return this.set("token",token)},UsergridStorable.prototype.getToken=function(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DEL
ETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logge
r.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]
=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_
specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;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;okToSave?group.save(function(err){"function"==typeof callback&&callback(err,group)}):"function"==typeof callback&&callback(err,group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.En
tity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callba
ck){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),th
is.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),loc
alStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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 tryi
ng to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.pu
sh(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergri
d.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridEr
ror("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();enti
ty&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error)
,callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"
/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Use
rgrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].
picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,
data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==
typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._c
lient=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var
collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
+function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint,this.method=method.toUpperCase(),this.query_params=query_params,this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,self=this,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutC
allback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,self.getToken()&&(qs.access_token=self.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_no
t_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prot
otype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){"function"==typeof callback&&(err?callback(err):callback(err,data,data.entities))})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Enti
ty(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=va
lue,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,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.acc
ess_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.access_token),"function"==typeof callback&&callback(err)})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.na
me,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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.set
Token(data.access_token)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(err,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){return"undefined"!=typeof this.getToken()},Usergrid.Client.prototype.logout=function(){this.setToken(null)},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.key
s(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntit
y=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");"users"===type&&nameProperties.unsh
ift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){v
ar endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)retu
rn void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._clien
t.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get
("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof call
back&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"
==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connectio
n,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterat
or=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.rese
tEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},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}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=func
tion(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._p
ath=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={type:entityData.t
ype,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this._path+"/feed"
,options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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.counter
s=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(options,callba
ck){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});para
ms.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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.enti
ties[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);else{var endpoi
nt=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBy
tes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)return callback.call(self,err,folder);va
r endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}
function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.
duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
[11/50] [abbrv] git commit: removed unused functions from
Usergrid.Request. stubbed out the remaining test cases for Usergrid.Client
Posted by sn...@apache.org.
removed unused functions from Usergrid.Request. stubbed out the remaining test cases for Usergrid.Client
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/e104c3e9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/e104c3e9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/e104c3e9
Branch: refs/heads/optimistic-tx-semantics
Commit: e104c3e94f0a8616af3abed33ba23d98336120c0
Parents: a976d1a
Author: ryan bridges <rb...@apigee.com>
Authored: Mon Feb 10 17:48:10 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Mon Feb 10 17:48:10 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/lib/Usergrid.js | 18 +---
sdks/html5-javascript/tests/mocha/test.js | 128 ++++++++++++++++++++++++-
sdks/html5-javascript/usergrid.js | 17 +---
sdks/html5-javascript/usergrid.min.js | 4 +-
4 files changed, 129 insertions(+), 38 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/e104c3e9/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index e607075..ec10de1 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -186,7 +186,7 @@ function doCallback(callback, params, context) {
*/
if (!isValidUrl(this.endpoint)) {
this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint));
- throw new UsergridError("The provided endpoint is not valid: " + this.endpoint);
+ throw new UsergridInvalidURIError("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);
@@ -205,22 +205,6 @@ function doCallback(callback, params, context) {
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();
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/e104c3e9/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index 350706c..2ecf944 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -94,6 +94,26 @@ describe('Usergrid Request/Response', function() {
done();
})
})
+ it('should GET an array of entity data from the Usergrid.Response object',function(done){
+ var req=new Usergrid.Request("GET", dogURI, {}, null, function(err, response){
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ var entities=response.getEntities();
+ console.log("ENTITIES",entities);
+ assert(entities && entities.length, "Nothing was returned")
+ done();
+ })
+ })
+ it('should GET entity data from the Usergrid.Response object',function(done){
+ var req=new Usergrid.Request("GET", dogURI+'/'+dogName, {}, null, function(err, response){
+ var entity=response.getEntity();
+ console.log("ENTITY",entity);
+ assert(!err, err);
+ assert(response instanceof Usergrid.Response, "Response is not and instance of Usergrid.Response");
+ assert(entity, "Nothing was returned")
+ done();
+ })
+ })
it('should PUT to a URI',function(done){
var req=new Usergrid.Request("PUT", dogURI+'/'+dogName, {}, {favorite:true}, function(err, response){
assert(!err, err);
@@ -108,6 +128,28 @@ describe('Usergrid Request/Response', function() {
done();
})
})
+ it('should NOT allow an invalid method',function(done){
+ try{
+ var req=new Usergrid.Request("INVALID", dogURI+'/'+dogName, {}, null, function(err, response){
+ assert(true, "Should have thrown an UsergridInvalidHTTPMethodError");
+ done();
+ })
+ }catch(e){
+ assert(e instanceof UsergridInvalidHTTPMethodError, "Error is not and instance of UsergridInvalidHTTPMethodError");
+ done()
+ }
+ })
+ it('should NOT allow an invalid URI',function(done){
+ try{
+ var req=new Usergrid.Request("GET", "://apigee.com", {}, null, function(err, response){
+ assert(true, "Should have thrown an UsergridInvalidURIError");
+ done();
+ })
+ }catch(e){
+ assert(e instanceof UsergridInvalidURIError, "Error is not and instance of UsergridInvalidURIError");
+ done()
+ }
+ })
it('should return a UsergridError object on an invalid URI',function(done){
var req=new Usergrid.Request("GET", dogURI+'/'+dogName+'zzzzz', {}, null, function(err, response){
assert(err, "Should have returned an error");
@@ -117,9 +159,9 @@ describe('Usergrid Request/Response', function() {
})
})
});
-describe('Usergrid', function() {
+describe('Usergrid Client', function() {
var client = getClient();
- describe('Usergrid CRUD', function() {
+ describe('Usergrid CRUD request', function() {
before(function(done) {
//Make sure our dog doesn't already exist
client.request({
@@ -223,7 +265,87 @@ describe('Usergrid', function() {
});
});
});
- describe('Usergrid Entity', function() {
+ describe('Usergrid convenience methods', function(){
+ it('createEntity',function(done){
+ done();
+ })
+ it('createCollection',function(done){
+ done();
+ })
+ it('createGroup',function(done){
+ done();
+ })
+ it('buildAssetURL',function(done){
+ done();
+ })
+ it('getEntity',function(done){
+ done();
+ })
+ it('restoreEntity',function(done){
+ done();
+ })
+ it('restoreCollection',function(done){
+ done();
+ })
+ it('getFeedForUser',function(done){
+ done();
+ })
+ it('createUserActivity',function(done){
+ done();
+ })
+ it('createUserActivityWithEntity',function(done){
+ done();
+ })
+ it('set',function(done){
+ done();
+ })
+ it('get',function(done){
+ done();
+ })
+ it('setObject',function(done){
+ done();
+ })
+ it('getObject',function(done){
+ done();
+ })
+ it('setToken',function(done){
+ done();
+ })
+ it('getToken',function(done){
+ done();
+ })
+ it('signup',function(done){
+ done();
+ })
+ it('login',function(done){
+ done();
+ })
+ it('reAuthenticateLite',function(done){
+ done();
+ })
+ it('reAuthenticate',function(done){
+ done();
+ })
+ it('loginFacebook',function(done){
+ done();
+ })
+ it('getLoggedInUser',function(done){
+ done();
+ })
+ it('isLoggedIn',function(done){
+ done();
+ })
+ it('logout',function(done){
+ done();
+ })
+ it('buildCurlCall',function(done){
+ done();
+ })
+ it('getDisplayImage',function(done){
+ done();
+ })
+ });
+ describe('Usergrid Entity', function() {
var dog;
before(function(done) {
//Make sure our dog doesn't already exist
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/e104c3e9/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 7d4bc06..38a8011 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -541,7 +541,7 @@ function doCallback(callback, params, context) {
*/
if (!isValidUrl(this.endpoint)) {
this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint));
- throw new UsergridError("The provided endpoint is not valid: " + this.endpoint);
+ throw new UsergridInvalidURIError("The provided endpoint is not valid: " + this.endpoint);
}
/* a callback to make the request */
var request = function() {
@@ -563,21 +563,6 @@ function doCallback(callback, params, context) {
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();
[24/50] [abbrv] removed Storable and references
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/6b03eed1/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index c93af87..458734f 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-11 */
-function UsergridStorable(){}function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(argume
nts).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._eve
nts[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return
Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console
,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function()
{return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwritt
enName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),
timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),UsergridStorable.prototype.setStorage=function(storage){return storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),storage=sessionStorage),this._storage=storage},UsergridStorable.prototype.getStorage=function(){return this._storage instanceof Storage||(console.warn("parameter passed to 'setStorage' is not a browser Storage interface. using sessionStorage"),this._storage
=sessionStorage),this._storage},UsergridStorable.prototype.getStorageKey=function(key){return this._keyPrefix||(this._keyPrefix="usergrid_js_sdk_"),this._keyPrefix+key},UsergridStorable.prototype.get=function(key){var value;if(arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),this._storage instanceof Storage)if(key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(this[key]=JSON.parse(this.getStorage().getItem(this.getStorageKey(key))),value=this[key]);return value},UsergridStorable.prototype.set=function(key,value){this._storage instanceof Storage&&(value?(this[key]=JSON.stringify(value),this.getStorage().setItem(this.getStorageKey(key),this[key])):(delete this[key],this.getStorage().removeItem(this.getStorageKey(key))))},UsergridStorable.prototype.setToken=function(token){return this.set("token",token)},UsergridStorable.prototype.getToken=functi
on(){return this.get("token")},UsergridStorable.mixin=function(destObject){for(var props=["getStorage","setStorage","getStorageKey","get","set","getToken","setToken"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridStorable.prototype[props[i]]},window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,cal
lback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise
.chain([request,response]).then(oncomplete),p},Usergrid.Request.prototype=new UsergridStorable,Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global
[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();
uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","
no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.rest
oreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options
);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof St
orage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={cl
ient:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"func
tion"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"=
=typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid
.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===
type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.En
tity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=
this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(op
tions,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=th
is,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.follow
ing=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user ro
les"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entit
y.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{}
,this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("functi
on"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));
-user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.pro
totype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key]
;if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.get
PrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(o
ptions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={ty
pe:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+thi
s._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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",thi
s._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function
(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].j
oin("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&sel
f.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);
else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sDa
ta){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):doCallback(callback,[null,self],self)};var fr=new FileReader;fr.onload=functio
n(){var binary=fr.result;xhr.overrideMimeType("application/octet-stream"),setTimeout(function(){xhr.sendAsBinary(binary)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.excep
tion=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.time
stamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){ret
urn a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event
]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error
","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.set
LogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(contex
t,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwri
ttenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function()
{xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var
p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([req
uest,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),funct
ion(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+a
ppName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&
&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(se
rializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){doCallback(callback,[err,entity
])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localSto
rage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Cl
ient.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),
organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid
.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT
"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj
)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===type||"user"===type)&&nameProperties.unshift("username");va
r names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=t
his;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"
==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console
.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activit
ies",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err
,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&
&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback)
{var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterato
r||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();c
ollection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._js
on=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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 th
is._list.splice(key,1)}return!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key];
+if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getP
revEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(op
tions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={typ
e:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this
._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(
options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].jo
in("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(cal
<TRUNCATED>
[27/50] [abbrv] git commit: Fixes to improve backward-compatibility.
Fixed password update functionality.
Posted by sn...@apache.org.
Fixes to improve backward-compatibility. Fixed password update functionality.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/52f0e028
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/52f0e028
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/52f0e028
Branch: refs/heads/optimistic-tx-semantics
Commit: 52f0e028cf1bd6b1a2a4cc02cbe189b0944bb762
Parents: 6b03eed
Author: ryan bridges <rb...@apigee.com>
Authored: Tue Feb 11 15:12:54 2014 -0500
Committer: ryan bridges <rb...@apigee.com>
Committed: Tue Feb 11 15:12:54 2014 -0500
----------------------------------------------------------------------
sdks/html5-javascript/lib/Usergrid.js | 52 ++++++---
sdks/html5-javascript/lib/modules/Client.js | 8 +-
sdks/html5-javascript/lib/modules/Entity.js | 78 +++++---------
sdks/html5-javascript/tests/mocha/test.js | 44 ++------
sdks/html5-javascript/usergrid.js | 128 ++++++++++++++++-------
sdks/html5-javascript/usergrid.min.js | 4 +-
6 files changed, 164 insertions(+), 150 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index 9ef2583..305b41f 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -207,22 +207,47 @@ function doCallback(callback, params, context) {
//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;
+ var data=null;
try {
data = JSON.parse(response.responseText);
} catch (e) {
//this.logger.error("Error parsing response text: ",this.text);
- this.logger.error("Caught error ", e.message);
+ //this.logger.error("Caught error ", e.message);
data = {}
- } finally {
- this.data = data;
}
- this.status = parseInt(response.status);
- this.statusGroup = (this.status - this.status % 100);
+ Object.keys(data).forEach(function(key){
+ Object.defineProperty(this, key, { value : data[key], enumerable:true });
+ }.bind(this));
+ Object.defineProperty(this, "logger", {
+ enumerable: false,
+ configurable: false,
+ writable: false,
+ value: new global.Logger(name)
+ });
+ Object.defineProperty(this, "success", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: true
+ });
+ Object.defineProperty(this, "err", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: err
+ });
+ Object.defineProperty(this, "status", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: parseInt(response.status)
+ });
+ Object.defineProperty(this, "statusGroup", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: (this.status - this.status % 100)
+ });
switch (this.statusGroup) {
case 200:
this.success = true;
@@ -236,18 +261,17 @@ function doCallback(callback, params, context) {
this.success = false;
break;
}
- var self = this;
if (this.success) {
p.done(null, this);
} else {
- p.done(UsergridError.fromResponse(this.data), this);
+ p.done(UsergridError.fromResponse(data), this);
}
return p;
};
Usergrid.Response.prototype.getEntities = function () {
var entities=[]
- if (this.success && this.data.entities) {
- entities=this.data.entities;
+ if (this.success) {
+ entities=(this.data)?this.data.entities:this.entities;
}
return entities;
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/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
index 683b78c..340626d 100644
--- a/sdks/html5-javascript/lib/modules/Client.js
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -279,7 +279,7 @@
if(err) {
doCallback(callback, [err]);
} else {
- doCallback(callback, [err, data, data.data.entities]);
+ doCallback(callback, [err, data, data.getEntities()]);
}
});
};
@@ -486,9 +486,8 @@
grant_type: 'password'
}
};
- self.request(options, function(err, response) {
+ self.request(options, function(err, data) {
var user = {};
- var data=response.data;
if (err) {
if(self.logging)console.log('error trying to log user in');
} else {
@@ -645,8 +644,7 @@
method:'GET',
endpoint:'users/me'
};
- this.request(options, function(err, response) {
- var data=response.data;
+ this.request(options, function(err, data) {
if (err) {
if (self.logging) {
console.log('error trying to log user in');
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/sdks/html5-javascript/lib/modules/Entity.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Entity.js b/sdks/html5-javascript/lib/modules/Entity.js
index 8b21bd5..c3314e5 100644
--- a/sdks/html5-javascript/lib/modules/Entity.js
+++ b/sdks/html5-javascript/lib/modules/Entity.js
@@ -118,7 +118,8 @@ Usergrid.Entity.prototype.getEndpoint = function () {
var names= this.get(nameProperties).filter(function(x){return "undefined"!==typeof x});
if (names.length===0) {
- throw new UsergridError("Cannot infer an UUID or type from the entity", 'no_name_specified');
+ //throw new UsergridError("Cannot infer an UUID or type from the entity", 'no_name_specified');
+ return type;
}else{
name=names.shift();
}
@@ -139,14 +140,13 @@ Usergrid.Entity.prototype.save = function (callback) {
entityId=this.get("uuid"),
data = {},
entityData = this.get(),
- /*password = this.get('password'),
+ password = this.get('password'),
oldpassword = this.get('oldpassword'),
- newpassword = this.get('newpassword'),*/
+ newpassword = this.get('newpassword'),
options={
method:method,
endpoint:type
};
- console.log("SAVE DATA #1", entityId, entityData);
//update the entity
if (entityId) {
@@ -160,22 +160,20 @@ Usergrid.Entity.prototype.save = function (callback) {
.forEach(function(key){
data[key]= entityData[key];
});
- console.log("SAVE DATA #2", data);
options.body=data;
//save the entity first
this._client.request(options, function (err, response) {
- console.log("SAVE DATA #3", response);
var entity=response.getEntity();
if(entity){
self.set(entity);
+ self.set('type', (/^\//.test(response.path))?response.path.substring(1):response.path);
}
- doCallback(callback,[err, self]);
+// doCallback(callback,[err, self]);
/*
TODO move user logic to its own entity
*/
- /*
//clear out pw info if present
self.set('password', null);
@@ -183,50 +181,38 @@ Usergrid.Entity.prototype.save = function (callback) {
self.set('newpassword', null);
if (err && self._client.logging) {
console.log('could not save entity');
- if (typeof(callback) === 'function') {
- return callback(err, retdata, self);
- }
- } else {
- if (retdata.entities) {
- if (retdata.entities.length) {
- var entity = retdata.entities[0];
- self.set(entity);
- var path = retdata.path;
- //for connections, API returns type
- while (path.substring(0, 1) === "/") {
- path = path.substring(1);
- }
- self.set('type', path);
- }
- }
- //if this is a user, update the password if it has been specified;
- var needPasswordChange = ((self.get('type') === 'user' || self.get('type') === 'users') && oldpassword && newpassword);
- if (needPasswordChange) {
+ doCallback(callback,[err, response, self]);
+ }else if ((/^users?/.test(self.get('type'))) && oldpassword && newpassword) {
+ //if this is a user, update the password if it has been specified;
//Note: we have a ticket in to change PUT calls to /users to accept the password change
// once that is done, we will remove this call and merge it all into one
- var pwdata = {};
- pwdata.oldpassword = oldpassword;
- pwdata.newpassword = newpassword;
var options = {
method:'PUT',
- endpoint:type+'/password',
- body:pwdata
+ endpoint:type+'/'+self.get("uuid")+'/password',
+ body:{
+ uuid:self.get("uuid"),
+ username:self.get("username"),
+ password:password,
+ oldpassword:oldpassword,
+ newpassword:newpassword
+ }
}
self._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('could not update user');
}
//remove old and new password fields so they don't end up as part of the entity object
- self.set('oldpassword', null);
- self.set('newpassword', null);
- if (typeof(callback) === 'function') {
- callback(err, data, self);
- }
+ self.set({
+ 'password':null,
+ 'oldpassword': null,
+ 'newpassword': null
+ });
+ doCallback(callback,[err, data, self]);
});
- } else if (typeof(callback) === 'function') {
- callback(err, retdata, self);
+ } else {
+ doCallback(callback,[err, response, self]);
}
- }*/
+
});
};
@@ -240,18 +226,7 @@ Usergrid.Entity.prototype.save = function (callback) {
*/
Usergrid.Entity.prototype.fetch = function (callback) {
var endpoint, self = this;
-
- //Check for an entity type, then if a uuid is available, use that, otherwise, use the name
- //try {
endpoint=this.getEndpoint();
- /*} catch (e) {
- if (self._client.logging) {
- console.log(e);
- }
- return callback(true, {
- error: e
- }, self);
- }*/
var options = {
method: 'GET',
endpoint: endpoint
@@ -261,7 +236,6 @@ Usergrid.Entity.prototype.fetch = function (callback) {
if(entity){
self.set(entity);
}
- console.log("AFTER FETCH", err, self.get(), entity, response);
doCallback(callback,[err, entity, self]);
});
};
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/sdks/html5-javascript/tests/mocha/test.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/tests/mocha/test.js b/sdks/html5-javascript/tests/mocha/test.js
index 216aa0a..20cab0b 100644
--- a/sdks/html5-javascript/tests/mocha/test.js
+++ b/sdks/html5-javascript/tests/mocha/test.js
@@ -15,7 +15,7 @@ function getClient() {
and run any number of additional tests
*/
function usergridTestHarness(err, data, done, tests, ignoreError) {
- if (!ignoreError) assert(!err, data.error_description);
+ if (!ignoreError) assert(!err, (err)?err.error_description:"unknown");
if (tests) {
if ("function" === typeof tests) {
tests(err, data);
@@ -186,7 +186,6 @@ describe('Usergrid Client', function() {
}
}, function(err, data) {
usergridTestHarness(err, data, done, [
-
function(err, data) {
assert(true)
}
@@ -246,8 +245,8 @@ describe('Usergrid Client', function() {
usergridTestHarness(err, data, done, [
function(err, data) {
- assert(!data.entities);
- console.log(JSON.stringify(data))
+ assert(data.entities.length>=0, "Request should return at least one user");
+ //console.log(JSON.stringify(data))
}
]);
});
@@ -260,13 +259,14 @@ describe('Usergrid Client', function() {
usergridTestHarness(err, data, done, [
function(err, data) {
- assert(!data.entities)
+ assert(data.entities.length===0, "Request should return no entities");
}
]);
});
});
});
describe('Usergrid convenience methods', function(){
+ before(function(){ client.logout();});
it('createEntity',function(done){
client.createEntity({type:'dog',name:'createEntityTestDog'}, function(err, dog){
assert(!err, "createEntity returned an error")
@@ -359,29 +359,6 @@ describe('Usergrid Client', function() {
done();
}
})
-// client.request({
-// method: 'GET',
-// endpoint: 'users/testActivityUser'
-// }, function(err, data) {
-// if(err){
-// client.request({
-// method: 'POST',
-// endpoint: 'users',
-// body: {
-// username: 'testActivityUser',
-// password: 'secret'
-// }
-// }, function(err, data) {
-// activityUser=data;
-// console.log(activityUser);
-// done();
-// });
-// }else{
-// activityUser=data;
-// console.log(activityUser);
-// done();
-// }
-// });
})
it('createUserActivity',function(done){
var options = {
@@ -424,15 +401,6 @@ describe('Usergrid Client', function() {
done();
})
})
- /*after(function(done){
- client.request({
- method: 'DELETE',
- endpoint: 'users/testActivityUser'
- }, function(err, data) {
- done();
- });
-
- })*/
var testProperty="____test_item"+Math.floor(Math.random()*10000),
testPropertyValue="test"+Math.floor(Math.random()*10000),
testPropertyObjectValue={test:testPropertyValue};
@@ -754,7 +722,7 @@ describe('Usergrid Client', function() {
assert(dogs.getPrevEntity(), "Could not retrieve the previous dog");
});
it('should DELETE the entities from the collection', function(done) {
- this.timeout(10000);
+ this.timeout(20000);
function remove(){
if(dogs.hasNextEntity()){
dogs.destroyEntity(dogs.getNextEntity(),function(err, data){
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/sdks/html5-javascript/usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.js b/sdks/html5-javascript/usergrid.js
index 59e80ef..6f37963 100644
--- a/sdks/html5-javascript/usergrid.js
+++ b/sdks/html5-javascript/usergrid.js
@@ -464,22 +464,50 @@ function doCallback(callback, params, context) {
//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;
+ var data = null;
try {
data = JSON.parse(response.responseText);
} catch (e) {
//this.logger.error("Error parsing response text: ",this.text);
- this.logger.error("Caught error ", e.message);
+ //this.logger.error("Caught error ", e.message);
data = {};
- } finally {
- this.data = data;
}
- this.status = parseInt(response.status);
- this.statusGroup = this.status - this.status % 100;
+ Object.keys(data).forEach(function(key) {
+ Object.defineProperty(this, key, {
+ value: data[key],
+ enumerable: true
+ });
+ }.bind(this));
+ Object.defineProperty(this, "logger", {
+ enumerable: false,
+ configurable: false,
+ writable: false,
+ value: new global.Logger(name)
+ });
+ Object.defineProperty(this, "success", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: true
+ });
+ Object.defineProperty(this, "err", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: err
+ });
+ Object.defineProperty(this, "status", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: parseInt(response.status)
+ });
+ Object.defineProperty(this, "statusGroup", {
+ enumerable: false,
+ configurable: false,
+ writable: true,
+ value: this.status - this.status % 100
+ });
switch (this.statusGroup) {
case 200:
this.success = true;
@@ -494,18 +522,17 @@ function doCallback(callback, params, context) {
this.success = false;
break;
}
- var self = this;
if (this.success) {
p.done(null, this);
} else {
- p.done(UsergridError.fromResponse(this.data), this);
+ p.done(UsergridError.fromResponse(data), this);
}
return p;
};
Usergrid.Response.prototype.getEntities = function() {
var entities = [];
- if (this.success && this.data.entities) {
- entities = this.data.entities;
+ if (this.success) {
+ entities = this.data ? this.data.entities : this.entities;
}
return entities;
};
@@ -779,7 +806,7 @@ function doCallback(callback, params, context) {
if (err) {
doCallback(callback, [ err ]);
} else {
- doCallback(callback, [ err, data, data.data.entities ]);
+ doCallback(callback, [ err, data, data.getEntities() ]);
}
});
};
@@ -972,9 +999,8 @@ function doCallback(callback, params, context) {
grant_type: "password"
}
};
- self.request(options, function(err, response) {
+ self.request(options, function(err, data) {
var user = {};
- var data = response.data;
if (err) {
if (self.logging) console.log("error trying to log user in");
} else {
@@ -1116,8 +1142,7 @@ function doCallback(callback, params, context) {
method: "GET",
endpoint: "users/me"
};
- this.request(options, function(err, response) {
- var data = response.data;
+ this.request(options, function(err, data) {
if (err) {
if (self.logging) {
console.log("error trying to log user in");
@@ -1334,7 +1359,8 @@ Usergrid.Entity.prototype.getEndpoint = function() {
return "undefined" !== typeof x;
});
if (names.length === 0) {
- throw new UsergridError("Cannot infer an UUID or type from the entity", "no_name_specified");
+ //throw new UsergridError("Cannot infer an UUID or type from the entity", 'no_name_specified');
+ return type;
} else {
name = names.shift();
}
@@ -1350,14 +1376,10 @@ Usergrid.Entity.prototype.getEndpoint = function() {
* @return {callback} callback(err, data)
*/
Usergrid.Entity.prototype.save = function(callback) {
- var self = this, type = this.get("type"), method = "POST", entityId = this.get("uuid"), data = {}, entityData = this.get(), /*password = this.get('password'),
- oldpassword = this.get('oldpassword'),
- newpassword = this.get('newpassword'),*/
- options = {
+ var self = this, type = this.get("type"), method = "POST", entityId = this.get("uuid"), data = {}, entityData = this.get(), password = this.get("password"), oldpassword = this.get("oldpassword"), newpassword = this.get("newpassword"), options = {
method: method,
endpoint: type
};
- console.log("SAVE DATA #1", entityId, entityData);
//update the entity
if (entityId) {
options.method = "PUT";
@@ -1369,16 +1391,55 @@ Usergrid.Entity.prototype.save = function(callback) {
}).forEach(function(key) {
data[key] = entityData[key];
});
- console.log("SAVE DATA #2", data);
options.body = data;
//save the entity first
this._client.request(options, function(err, response) {
- console.log("SAVE DATA #3", response);
var entity = response.getEntity();
if (entity) {
self.set(entity);
+ self.set("type", /^\//.test(response.path) ? response.path.substring(1) : response.path);
+ }
+ // doCallback(callback,[err, self]);
+ /*
+ TODO move user logic to its own entity
+ */
+ //clear out pw info if present
+ self.set("password", null);
+ self.set("oldpassword", null);
+ self.set("newpassword", null);
+ if (err && self._client.logging) {
+ console.log("could not save entity");
+ doCallback(callback, [ err, response, self ]);
+ } else if (/^users?/.test(self.get("type")) && oldpassword && newpassword) {
+ //if this is a user, update the password if it has been specified;
+ //Note: we have a ticket in to change PUT calls to /users to accept the password change
+ // once that is done, we will remove this call and merge it all into one
+ var options = {
+ method: "PUT",
+ endpoint: type + "/" + self.get("uuid") + "/password",
+ body: {
+ uuid: self.get("uuid"),
+ username: self.get("username"),
+ password: password,
+ oldpassword: oldpassword,
+ newpassword: newpassword
+ }
+ };
+ self._client.request(options, function(err, data) {
+ if (err && self._client.logging) {
+ console.log("could not update user");
+ }
+ //remove old and new password fields so they don't end up as part of the entity object
+ self.set({
+ password: null,
+ oldpassword: null,
+ newpassword: null
+ });
+ doCallback(callback, [ err, data, self ]);
+ });
+ } else {
+ doCallback(callback, [ err, response, self ]);
}
- doCallback(callback, [ err, self ]);
});
};
@@ -1392,17 +1453,7 @@ Usergrid.Entity.prototype.save = function(callback) {
*/
Usergrid.Entity.prototype.fetch = function(callback) {
var endpoint, self = this;
- //Check for an entity type, then if a uuid is available, use that, otherwise, use the name
- //try {
endpoint = this.getEndpoint();
- /*} catch (e) {
- if (self._client.logging) {
- console.log(e);
- }
- return callback(true, {
- error: e
- }, self);
- }*/
var options = {
method: "GET",
endpoint: endpoint
@@ -1412,7 +1463,6 @@ Usergrid.Entity.prototype.fetch = function(callback) {
if (entity) {
self.set(entity);
}
- console.log("AFTER FETCH", err, self.get(), entity, response);
doCallback(callback, [ err, entity, self ]);
});
};
[32/50] [abbrv] git commit: Fixed concurrent calls. Removed
concurrent helper, it's interfering more than helping.
Posted by sn...@apache.org.
Fixed concurrent calls. Removed concurrent helper, it's interfering more than helping.
Tests need fixed. Bug in zip found
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/fc355560
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/fc355560
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/fc355560
Branch: refs/heads/optimistic-tx-semantics
Commit: fc3555609ce9bb89111e05eee2c313ebda0e9f8b
Parents: d312b31
Author: Todd Nine <tn...@apigee.com>
Authored: Wed Feb 12 20:20:59 2014 -0700
Committer: Todd Nine <tn...@apigee.com>
Committed: Wed Feb 12 20:20:59 2014 -0700
----------------------------------------------------------------------
.../collection/guice/CollectionModule.java | 14 +-
.../impl/EntityCollectionManagerImpl.java | 78 +++++++--
.../collection/mvcc/stage/write/WriteFig.java | 42 -----
.../mvcc/stage/write/WriteUniqueVerify.java | 158 +++++++++++--------
.../persistence/collection/rx/Concurrent.java | 80 ----------
.../mvcc/stage/write/WriteUniqueVerifyTest.java | 68 ++++++--
.../collection/rx/ConcurrentTest.java | 149 -----------------
7 files changed, 218 insertions(+), 371 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
index 95bc760..e0744c3 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
@@ -17,19 +17,18 @@
*/
package org.apache.usergrid.persistence.collection.guice;
-import java.io.IOException;
-import org.safehaus.guicyfig.Env;
import org.safehaus.guicyfig.GuicyFigModule;
import org.apache.usergrid.persistence.collection.EntityCollectionManager;
import org.apache.usergrid.persistence.collection.EntityCollectionManagerFactory;
import org.apache.usergrid.persistence.collection.EntityCollectionManagerSync;
import org.apache.usergrid.persistence.collection.astyanax.CassandraFig;
-import org.apache.usergrid.persistence.collection.cassandra.AvailablePortFinder;
import org.apache.usergrid.persistence.collection.impl.EntityCollectionManagerImpl;
import org.apache.usergrid.persistence.collection.impl.EntityCollectionManagerSyncImpl;
import org.apache.usergrid.persistence.collection.migration.MigrationManagerFig;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategy;
+import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategyImpl;
import org.apache.usergrid.persistence.collection.rx.CassandraThreadScheduler;
import org.apache.usergrid.persistence.collection.rx.RxFig;
import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
@@ -37,13 +36,7 @@ import org.apache.usergrid.persistence.collection.serialization.impl.Serializati
import org.apache.usergrid.persistence.collection.service.impl.ServiceModule;
import com.google.inject.AbstractModule;
-import com.google.inject.Guice;
-import com.google.inject.Injector;
import com.google.inject.assistedinject.FactoryModuleBuilder;
-import com.netflix.config.ConfigurationManager;
-import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategy;
-import org.apache.usergrid.persistence.collection.mvcc.stage.write.UniqueValueSerializationStrategyImpl;
-import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteFig;
import rx.Scheduler;
@@ -63,8 +56,7 @@ public class CollectionModule extends AbstractModule {
RxFig.class,
MigrationManagerFig.class,
CassandraFig.class,
- SerializationFig.class,
- WriteFig.class ) );
+ SerializationFig.class ) );
install( new SerializationModule() );
install( new ServiceModule() );
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
index 5698080..bc456dc 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
@@ -24,11 +24,8 @@ import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.cassandra.thrift.Cassandra;
-
import org.apache.usergrid.persistence.collection.CollectionScope;
import org.apache.usergrid.persistence.collection.EntityCollectionManager;
-import org.apache.usergrid.persistence.collection.hystrix.CassandraCommand;
import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
import org.apache.usergrid.persistence.collection.mvcc.entity.ValidationUtils;
import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
@@ -51,6 +48,8 @@ import com.google.inject.assistedinject.Assisted;
import rx.Observable;
import rx.Scheduler;
+import rx.util.functions.Func1;
+import rx.util.functions.Func2;
import rx.util.functions.FuncN;
@@ -86,8 +85,8 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
@Inject
- public EntityCollectionManagerImpl( final UUIDService uuidService, final WriteStart writeStart, final Scheduler scheduler,
- final WriteUniqueVerify writeVerifyUnique,
+ public EntityCollectionManagerImpl( final UUIDService uuidService, final WriteStart writeStart,
+ final Scheduler scheduler, final WriteUniqueVerify writeVerifyUnique,
final WriteOptimisticVerify writeOptimisticVerify,
final WriteCommit writeCommit, final Load load, final DeleteStart deleteStart,
final DeleteCommit deleteCommit,
@@ -146,11 +145,60 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
//create our observable and start the write
CollectionIoEvent<Entity> writeData = new CollectionIoEvent<Entity>( collectionScope, entity );
- Observable<CollectionIoEvent<MvccEntity>> observable = Observable.from( writeData ).subscribeOn( scheduler ).map( writeStart );
+ Observable<CollectionIoEvent<MvccEntity>> observable =
+ Observable.from( writeData ).subscribeOn( scheduler ).map( writeStart ).flatMap(
+ new Func1<CollectionIoEvent<MvccEntity>, Observable<CollectionIoEvent<MvccEntity>>>() {
+
+
+ @Override
+ public Observable<CollectionIoEvent<MvccEntity>> call(
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent ) {
+
+ //do the unique and optimistic steps in parallel
+
+ /**
+ *unique function. Since there can be more than 1 unique value in this entity
+ * the unique verification step itself is multiple parallel executions.
+ * This is why we use "flatMap" instead of "map", which allows the
+ * WriteVerifyUnique stage to execute multiple verification steps in parallel and
+ * zip the results
+ */
+
+
+ Observable<CollectionIoEvent<MvccEntity>> unique =
+ Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
+ .flatMap( writeVerifyUnique);
- //execute all validation stages concurrently. Needs refactored when this is done. https://github.com/Netflix/RxJava/issues/627
- observable = Concurrent.concurrent(observable, scheduler, new WaitZip( ), writeVerifyUnique, writeOptimisticVerify);
+ //optimistic verification
+ Observable<CollectionIoEvent<MvccEntity>> optimistic =
+ Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
+ .map( writeOptimisticVerify );
+
+
+ //zip the results
+ /**
+ * TODO: Should the zip only return errors here, and if errors are present, we throw during the zip phase? I couldn't find "
+ */
+
+ return Observable.zip( unique, optimistic, new Func2<CollectionIoEvent<MvccEntity>,
+ CollectionIoEvent<MvccEntity>, CollectionIoEvent<MvccEntity>>() {
+ @Override
+ public CollectionIoEvent<MvccEntity> call(
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent,
+ final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent2 ) {
+
+ return mvccEntityCollectionIoEvent;
+ }
+ } );
+ }
+ } );
+
+
+// //execute all validation stages concurrently. Needs refactored when this is done. https://github
+// // .com/Netflix/RxJava/issues/627
+// observable =
+// Concurrent.concurrent( observable, scheduler, new WaitZip(), writeVerifyUnique, writeOptimisticVerify );
//return the commit result.
return observable.map( writeCommit );
@@ -166,7 +214,8 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
Preconditions.checkNotNull( entityId.getType(), "Entity type is required in this stage" );
- return Observable.from(new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler ).map( deleteStart ).map( deleteCommit );
+ return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
+ .map( deleteStart ).map( deleteCommit );
}
@@ -177,16 +226,15 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
Preconditions.checkNotNull( entityId.getUuid(), "Entity id uuid required in the load stage" );
Preconditions.checkNotNull( entityId.getType(), "Entity id type required in the load stage" );
- return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler ).map( load );
+ return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
+ .map( load );
}
/**
* Class that validates all results are equal then proceeds
- * @param <R>
*/
- private static class WaitZip<R> implements FuncN<R>{
-
+ private static class WaitZip<R> implements FuncN<R> {
private WaitZip() {
@@ -196,8 +244,8 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
@Override
public R call( final Object... args ) {
- for(int i = 0; i < args.length-1; i ++){
- assert args[i] == args[i+1];
+ for ( int i = 0; i < args.length - 1; i++ ) {
+ assert args[i] == args[i + 1];
}
return ( R ) args[0];
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteFig.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteFig.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteFig.java
deleted file mode 100644
index d2282a8..0000000
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteFig.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. The ASF licenses this file to You
- * under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License. For additional information regarding
- * copyright in this work, please see the NOTICE file in the top level
- * directory of this distribution.
- */
-package org.apache.usergrid.persistence.collection.mvcc.stage.write;
-
-import org.safehaus.guicyfig.Default;
-import org.safehaus.guicyfig.GuicyFig;
-import org.safehaus.guicyfig.Key;
-
-/**
- * Configuration for Write stage classes.
- */
-public interface WriteFig extends GuicyFig {
-
- /**
- * Max number of threads the uniqueness verification pool can allocate. Can be dynamically changed after starting
- */
- @Key( "collection.stage.write.verification.threads" )
- @Default( "20" )
- int getMaxThreadCount();
-
- /**
- * Time to Live for Unique Values before commit.
- */
- @Key( "collection.stage.write.verification.ttl.seconds" )
- @Default( "10" )
- int getUniqueValueTimeToLive();
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
index ad65820..370fd0a 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
@@ -17,66 +17,65 @@
*/
package org.apache.usergrid.persistence.collection.mvcc.stage.write;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.usergrid.persistence.collection.exception.CollectionRuntimeException;
import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
import org.apache.usergrid.persistence.collection.mvcc.entity.ValidationUtils;
import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
+import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
+import org.apache.usergrid.persistence.model.entity.Entity;
+import org.apache.usergrid.persistence.model.field.Field;
+import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import org.apache.usergrid.persistence.collection.exception.CollectionRuntimeException;
-import org.apache.usergrid.persistence.model.entity.Entity;
-import org.apache.usergrid.persistence.model.field.Field;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import rx.Observable;
+import rx.Scheduler;
import rx.util.functions.Func1;
+import rx.util.functions.FuncN;
+
/**
* This phase execute all unique value verification on the MvccEntity.
*/
@Singleton
-public class WriteUniqueVerify
- implements Func1<CollectionIoEvent<MvccEntity>, CollectionIoEvent<MvccEntity>> {
+public class WriteUniqueVerify implements Func1<CollectionIoEvent<MvccEntity>, Observable<? extends CollectionIoEvent<MvccEntity>>> {
private static final Logger LOG = LoggerFactory.getLogger( WriteUniqueVerify.class );
private final UniqueValueSerializationStrategy uniqueValueStrat;
- //TODO Dave: we don't want to use our own thread pool. Use the Concurrent class to create new observables
- private final ExecutorService threadPool;
- private final int MAX_THREAD_COUNT;
+ private final Scheduler scheduler;
- private final int UNIQUE_VALUE_TTL;
+ protected final SerializationFig serializationFig;
- @Inject
- public WriteUniqueVerify( WriteFig writeFig,
- UniqueValueSerializationStrategy uniqueValueSerializiationStrategy ) {
- this.uniqueValueStrat = uniqueValueSerializiationStrategy;
+ @Inject
+ public WriteUniqueVerify( final UniqueValueSerializationStrategy uniqueValueSerializiationStrategy,
+ final Scheduler scheduler, final SerializationFig serializationFig ) {
- if ( writeFig == null) {
- MAX_THREAD_COUNT = 100;
- UNIQUE_VALUE_TTL = 30;
- } else {
- MAX_THREAD_COUNT = writeFig.getMaxThreadCount();
- UNIQUE_VALUE_TTL = writeFig.getUniqueValueTimeToLive();
- }
+ Preconditions.checkNotNull( uniqueValueSerializiationStrategy, "uniqueValueSerializationStrategy is required" );
+ Preconditions.checkNotNull( scheduler, "scheduler is required" );
+ Preconditions.checkNotNull( serializationFig, "serializationFig is required" );
- this.threadPool = Executors.newFixedThreadPool( MAX_THREAD_COUNT );
+ this.uniqueValueStrat = uniqueValueSerializiationStrategy;
+ this.scheduler = scheduler;
+ this.serializationFig = serializationFig;
}
+
@Override
- public CollectionIoEvent<MvccEntity> call( final CollectionIoEvent<MvccEntity> ioevent ) {
+ public Observable<? extends CollectionIoEvent<MvccEntity>> call(final CollectionIoEvent<MvccEntity> ioevent ) {
ValidationUtils.verifyMvccEntityWithEntity( ioevent.getEvent() );
@@ -88,90 +87,121 @@ public class WriteUniqueVerify
// We want to use concurrent to fork all validations this way they're wrapped by timeouts and
// Hystrix thread pools for JMX operations. See the WriteCommand in the EntityCollectionManagerImpl
// I think it still needs added to the Concurrent utility class
- final List<Future<FieldUniquenessResult>> results =
- new ArrayList<Future<FieldUniquenessResult>>();
- for ( final Field field : entity.getFields() ) {
- if ( field.isUnique() ) {
+ final List<Observable<FieldUniquenessResult>> fields =
+ new ArrayList<Observable<FieldUniquenessResult>>();
+
- results.add( threadPool.submit( new Callable<FieldUniquenessResult>() {
- public FieldUniquenessResult call() throws Exception {
+ /**
+ * Construct all the functions for verifying we're unique
+ */
+ for ( final Field field : entity.getFields() ) {
+
+ //if it's unique, create a function to validate it and add it to the list of concurrent validations
+ if ( !field.isUnique() ) {
- // use write-first then read strategy
- UniqueValue written = new UniqueValueImpl( ioevent.getEntityCollection(),
- field, entity.getId(), entity.getVersion() );
+ Observable<FieldUniquenessResult> result = Observable.from( field ).subscribeOn( scheduler ).map(new Func1<Field, FieldUniquenessResult>() {
+ @Override
+ public FieldUniquenessResult call(Field field ) {
+
+ // use write-first then read strategy
+ UniqueValue written = new UniqueValueImpl( ioevent.getEntityCollection(), field, entity.getId(),
+ entity.getVersion() );
// use TTL in case something goes wrong before entity is finally committed
- MutationBatch mb = uniqueValueStrat.write( written, UNIQUE_VALUE_TTL );
+ MutationBatch mb = uniqueValueStrat.write( written, serializationFig.getTimeout() );
try {
mb.execute();
- } catch ( ConnectionException ex ) {
- throw new CollectionRuntimeException(
- "Error writing unique value " + field.toString(), ex );
+ }
+ catch ( ConnectionException ex ) {
+ throw new CollectionRuntimeException( "Error writing unique value " + field.toString(),
+ ex );
}
// does the database value match what we wrote?
UniqueValue loaded;
try {
- loaded = uniqueValueStrat.load(
- ioevent.getEntityCollection(), field );
-
- } catch ( ConnectionException ex ) {
+ loaded = uniqueValueStrat.load( ioevent.getEntityCollection(), field );
+ }
+ catch ( ConnectionException ex ) {
throw new CollectionRuntimeException( ex );
}
- return new FieldUniquenessResult( field, loaded.equals( written ));
+ return new FieldUniquenessResult( field, loaded.equals( written ) );
}
+ } );
- } ) );
-
+ fields.add(result);
}
}
- for ( Future<FieldUniquenessResult> result : results ) {
- try {
- if ( !result.get().isUnique() ) {
- Field field = result.get().getField();
- throw new CollectionRuntimeException( "Duplicate field value "
- + field.getName() + " = " + field.getValue().toString());
+ //short circuit. If we zip up nothing, we block forever.
+ if(fields.size() == 0){
+ return Observable.from(ioevent ).subscribeOn( scheduler );
+ }
+
+ /**
+ * Zip the results up
+ */
+ final FuncN<CollectionIoEvent<MvccEntity>> zipFunction = new FuncN<CollectionIoEvent<MvccEntity>>() {
+ @Override
+ public CollectionIoEvent<MvccEntity> call( final Object... args ) {
+
+
+
+ for ( Object resultObj : args ) {
+
+ FieldUniquenessResult result = ( FieldUniquenessResult ) resultObj;
+
+ if ( !result.isUnique() ) {
+ Field field = result.getField();
+ throw new CollectionRuntimeException(
+ "Duplicate field value " + field.getName() + " = " + field.getValue().toString() );
+ }
}
- } catch ( InterruptedException ex ) {
- LOG.error( "Error verifing uniqueness", ex );
- } catch ( ExecutionException ex ) {
- LOG.error( "Error verifing uniqueness", ex );
+
+ //return the original event
+ return ioevent;
}
- }
+ };
+
+
+ return Observable.zip( fields, zipFunction );
- return ioevent;
}
+
static class FieldUniquenessResult {
private Field field;
private Boolean unique;
+
public FieldUniquenessResult( Field f, Boolean u ) {
this.field = f;
this.unique = u;
}
+
public Boolean isUnique() {
return unique;
}
+
public void setUnique( Boolean isUnique ) {
this.unique = isUnique;
}
+
public Field getField() {
return field;
}
+
public void setField( Field field ) {
this.field = field;
}
-
}
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/rx/Concurrent.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/rx/Concurrent.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/rx/Concurrent.java
deleted file mode 100644
index 868c73b..0000000
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/rx/Concurrent.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.usergrid.persistence.collection.rx;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.usergrid.persistence.collection.hystrix.CassandraCommand;
-
-import com.netflix.hystrix.HystrixCommand;
-
-import rx.Observable;
-import rx.Scheduler;
-import rx.concurrency.Schedulers;
-import rx.operators.OperationMerge;
-import rx.util.functions.Func1;
-import rx.util.functions.FuncN;
-
-
-/**
- * A utility class that encapsulates possible combinations of functions.
- * These functions are executed in parallel, then "zipped" into a single response.
- * This is useful when you want to perform operations on a single initial observable,
- * then combine the result of multiple parallel operations on that object into a single observable to continue the sequence
- */
-public class Concurrent {
-
-
- /**
- * Create an instance of concurrent execution. All functions specified
- * in the list are invoked in parallel. The results are then "zipped"
- * into a single observable which is returned with the specified function
- *
- * @param observable The observable we're invoking many concurrent operations on
- * @param scheduler The scheduler to use when invoking the parallel operations
- * @param zipFunction The zip function to aggregate the results. And return the observable
- * @param concurrent The concurrent operations we're invoking
- * @return The observable emitted from the zipped function of type Z
- */
- public static <T, R, Z> Observable<Z> concurrent(
- final Observable<T> observable, final Scheduler scheduler, final FuncN<Z> zipFunction, final Func1<T, R>... concurrent ){
-
- return observable.mapMany( new Func1<T, Observable<Z>>() {
- @Override
- public Observable<Z> call( final T input ) {
-
- List<Observable<R>> observables = new ArrayList<Observable<R>>(concurrent.length);
-
- //Create multiple observables for each function. They simply emit the input value.
- //this is the "fork" step of the concurrent processing
- for( Func1<T, R> funct: concurrent){
- final Observable<R> observable = Observable.from( input ).subscribeOn( scheduler ).map( funct );
-
- observables.add( observable );
- }
-
- return Observable.zip( observables, zipFunction );
- }
- } );
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
index d247127..da16a21 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerifyTest.java
@@ -18,29 +18,39 @@
package org.apache.usergrid.persistence.collection.mvcc.stage.write;
+import org.jukito.JukitoRunner;
import org.jukito.UseModules;
import org.junit.ClassRule;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.apache.usergrid.persistence.collection.CollectionScope;
import org.apache.usergrid.persistence.collection.cassandra.CassandraRule;
+import org.apache.usergrid.persistence.collection.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
import org.apache.usergrid.persistence.collection.mvcc.stage.AbstractMvccEntityStageTest;
import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
+import org.apache.usergrid.persistence.collection.serialization.SerializationFig;
import org.apache.usergrid.persistence.model.entity.Entity;
import com.google.inject.Inject;
+import rx.Scheduler;
+
import static org.apache.usergrid.persistence.collection.mvcc.stage.TestEntityGenerator.fromEntity;
import static org.apache.usergrid.persistence.collection.mvcc.stage.TestEntityGenerator.generateEntity;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
-/**
- * @author tnine
+/**
+ * TODO: Update the test to correctly test for detecting more than 1 duplicate and exception handling correctly
+ *
+ * @author tnine
*/
+@RunWith( JukitoRunner.class )
@UseModules( TestCollectionModule.class )
public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
@@ -50,24 +60,41 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
@Inject
private UniqueValueSerializationStrategy uniqueValueSerializiationStrategy;
- /** Standard flow */
- @Test
+
+ @Inject
+ @Rule
+ public MigrationManagerRule migrationManagerRule;
+
+
+ @Inject
+ private Scheduler scheduler;
+
+ @Inject
+ private SerializationFig fig;
+
+
+ /**
+ * Standard flow
+ */
+ @Test( timeout = 5000 )
public void testStartStage() throws Exception {
final CollectionScope collectionScope = mock( CollectionScope.class );
+
// set up the mock to return the entity from the start phase
final Entity entity = generateEntity();
final MvccEntity mvccEntity = fromEntity( entity );
// run the stage
- WriteUniqueVerify newStage = new WriteUniqueVerify( null, uniqueValueSerializiationStrategy );
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
- CollectionIoEvent<MvccEntity>
- result = newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) );
+ CollectionIoEvent<MvccEntity> result =
+ newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
+ .last();
- assertSame("Context was correct", collectionScope, result.getEntityCollection()) ;
+ assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
// verify the log entry is correct
MvccEntity entry = result.getEvent();
@@ -80,11 +107,32 @@ public class WriteUniqueVerifyTest extends AbstractMvccEntityStageTest {
assertSame( "Entity correct", entity, entry.getEntity().get() );
}
+
+ @Test
+ public void testNoFields() {
+ final CollectionScope collectionScope = mock( CollectionScope.class );
+
+
+ // set up the mock to return the entity from the start phase
+ final Entity entity = generateEntity();
+
+ final MvccEntity mvccEntity = fromEntity( entity );
+
+ // run the stage
+ WriteUniqueVerify newStage = new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig );
+
+ CollectionIoEvent<MvccEntity> result =
+ newStage.call( new CollectionIoEvent<MvccEntity>( collectionScope, mvccEntity ) ).toBlockingObservable()
+ .last();
+
+ assertSame( "Context was correct", collectionScope, result.getEntityCollection() );
+ }
+
+
@Override
protected void validateStage( final CollectionIoEvent<MvccEntity> event ) {
- new WriteUniqueVerify( null, uniqueValueSerializiationStrategy ).call( event );
+ new WriteUniqueVerify( uniqueValueSerializiationStrategy, scheduler, fig ).call( event );
}
-
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fc355560/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/rx/ConcurrentTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/rx/ConcurrentTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/rx/ConcurrentTest.java
deleted file mode 100644
index eafe3aa..0000000
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/rx/ConcurrentTest.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package org.apache.usergrid.persistence.collection.rx;
-
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.usergrid.persistence.collection.hystrix.CassandraCommand;
-
-import com.google.common.collect.HashMultiset;
-import com.google.common.collect.Multiset;
-import com.netflix.config.ConfigurationManager;
-
-import rx.Observable;
-import rx.Scheduler;
-import rx.concurrency.Schedulers;
-import rx.util.functions.Func1;
-import rx.util.functions.FuncN;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-
-/**
- *
- *
- */
-public class ConcurrentTest {
-
- private static final Logger logger = LoggerFactory.getLogger( ConcurrentTest.class );
-
-
-
- @Test( timeout = 5000 )
- public void concurrent() {
- //use the I/O scheduler so we always have enough threads
- final Scheduler scheduler = Schedulers.threadPoolForIO();
-
- final String source = "test";
- Observable<String> observable = Observable.from( source );
-
- //we could theoretically use the same instance over and over
-
- final int size = 5;
-
-
- final CountDownLatch latch = new CountDownLatch( size );
-
- TestConcurrent[] concurrentFunctions = new TestConcurrent[size];
-
- for ( int i = 0; i < size; i++ ) {
- concurrentFunctions[i] = new TestConcurrent( latch, i );
- }
-
- Zip zip = new Zip();
-
-
- //concurrent inherits thread pool from it's observable, set it's thread pool
- Observable<Integer> result = Concurrent.concurrent( observable, scheduler, zip, concurrentFunctions );
-
- assertEquals( "No invocation yet", 0, set.size() );
-
-
- //now invoke it
- Integer response = result.toBlockingObservable().single();
-
-
- assertEquals( "Same value emitted", size - 1, response.intValue() );
-
- //verify each function executed in it's own thread
-
- assertEquals( size + " threads invoked", size, set.size() );
-
- //print them out just for giggles
- for ( Multiset.Entry<String> entry : set.entrySet() ) {
- System.out.println( entry.getElement() );
- assertEquals( "1 Thread per invocation", 1, entry.getCount() );
- }
- }
-
-
- private Multiset<String> set = HashMultiset.create();
-
-
- public class Zip implements FuncN<Integer> {
-
-
- @Override
- public Integer call( final Object... args ) {
-
- //validate our arguments come in order
- for ( int i = 0; i < args.length; i++ ) {
-
- assertEquals( i, args[i] );
- }
-
- return ( Integer ) args[args.length - 1];
- }
- }
-
-
- /**
- * Simple function that just adds data to our multiset for later evaluation
- */
- public class TestConcurrent implements Func1<String, Integer> {
-
- private final CountDownLatch latch;
- private final int index;
-
-
- public TestConcurrent( final CountDownLatch latch, int index ) {
- this.latch = latch;
- this.index = index;
- }
-
-
- @Override
- public Integer call( final String s ) {
- final String threadName = Thread.currentThread().getName();
-
- logger.info( "Function executing on thread {}", threadName );
-
- set.add( threadName );
-
- //we want to make sure each thread blocks until they all have passed the latch
- //this way we can ensure they're all running concurrently
- try {
- latch.countDown();
-
-
- boolean waited = latch.await( 5, TimeUnit.SECONDS );
-
- //validate everything ran concurrently
- assertTrue( "Latch released", waited );
- }
- catch ( InterruptedException e ) {
- logger.error( "Runner interrupted", e );
- }
-
- return index;
- }
- }
-}
[36/50] [abbrv] git commit: Merge branch 'master' into two-dot-o
Posted by sn...@apache.org.
Merge branch 'master' into two-dot-o
Conflicts:
.gitignore
stack/query-validator/pom.xml
stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidationTest.java
stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidatorRunner.java
stack/query-validator/src/test/resources/log4j.properties
stack/rest/src/main/java/org/usergrid/rest/applications/ApplicationResource.java
stack/rest/src/test/java/org/usergrid/rest/ITSetup.java
stack/rest/src/test/java/org/usergrid/rest/TomcatResource.java
stack/services/src/main/java/org/usergrid/management/cassandra/ManagementServiceImpl.java
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/fb5f8d6c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/fb5f8d6c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/fb5f8d6c
Branch: refs/heads/optimistic-tx-semantics
Commit: fb5f8d6c27fd7926cf4a7722dbd06f3cad8dc99e
Parents: 8a08118 ad8d78f
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 08:12:01 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 08:12:01 2014 -0500
----------------------------------------------------------------------
.gitignore | 2 -
sdks/android/doc/allclasses-frame.html | 110 +-
sdks/android/doc/allclasses-noframe.html | 110 +-
sdks/android/doc/constant-values.html | 859 +-
sdks/android/doc/deprecated-list.html | 237 +-
sdks/android/doc/help-doc.html | 419 +-
sdks/android/doc/index-all.html | 371 +
sdks/android/doc/index-files/index-1.html | 209 -
sdks/android/doc/index-files/index-10.html | 151 -
sdks/android/doc/index-files/index-11.html | 154 -
sdks/android/doc/index-files/index-12.html | 151 -
sdks/android/doc/index-files/index-13.html | 217 -
sdks/android/doc/index-files/index-14.html | 268 -
sdks/android/doc/index-files/index-15.html | 204 -
sdks/android/doc/index-files/index-16.html | 151 -
sdks/android/doc/index-files/index-17.html | 466 -
sdks/android/doc/index-files/index-18.html | 184 -
sdks/android/doc/index-files/index-19.html | 157 -
sdks/android/doc/index-files/index-2.html | 193 -
sdks/android/doc/index-files/index-20.html | 239 -
sdks/android/doc/index-files/index-21.html | 154 -
sdks/android/doc/index-files/index-3.html | 161 -
sdks/android/doc/index-files/index-4.html | 166 -
sdks/android/doc/index-files/index-5.html | 151 -
sdks/android/doc/index-files/index-6.html | 547 -
sdks/android/doc/index-files/index-7.html | 145 -
sdks/android/doc/index-files/index-8.html | 160 -
sdks/android/doc/index-files/index-9.html | 145 -
sdks/android/doc/index.html | 89 +-
.../apache/usergrid/android/client/Client.html | 989 +
.../client/callbacks/ApiResponseCallback.html | 224 +
.../client/callbacks/ClientAsyncTask.html | 338 +
.../client/callbacks/ClientCallback.html | 227 +
.../callbacks/DeviceRegistrationCallback.html | 220 +
.../callbacks/GroupsRetrievedCallback.html | 220 +
.../client/callbacks/QueryResultsCallback.html | 220 +
.../class-use/ApiResponseCallback.html | 282 +
.../callbacks/class-use/ClientAsyncTask.html | 117 +
.../callbacks/class-use/ClientCallback.html | 180 +
.../class-use/DeviceRegistrationCallback.html | 171 +
.../class-use/GroupsRetrievedCallback.html | 160 +
.../class-use/QueryResultsCallback.html | 219 +
.../android/client/callbacks/package-frame.html | 28 +
.../client/callbacks/package-summary.html | 166 +
.../android/client/callbacks/package-tree.html | 145 +
.../android/client/callbacks/package-use.html | 178 +
.../android/client/class-use/Client.html | 117 +
.../usergrid/android/client/package-frame.html | 20 +
.../android/client/package-summary.html | 137 +
.../usergrid/android/client/package-tree.html | 134 +
.../usergrid/android/client/package-use.html | 117 +
.../android/client/utils/DeviceUuidFactory.html | 352 +
.../android/client/utils/ObjectUtils.html | 258 +
.../utils/class-use/DeviceUuidFactory.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../android/client/utils/package-frame.html | 21 +
.../android/client/utils/package-summary.html | 142 +
.../android/client/utils/package-tree.html | 131 +
.../android/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/android/doc/overview-frame.html | 71 +-
sdks/android/doc/overview-summary.html | 280 +-
sdks/android/doc/overview-tree.html | 301 +-
sdks/android/doc/package-list | 8 +-
sdks/android/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/android/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/android/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/android/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/android/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/android/doc/stylesheet.css | 501 +-
.../0.0.6/usergrid-java-client-0.0.6.jar | Bin 0 -> 46389 bytes
.../0.0.6/usergrid-java-client-0.0.6.jar.sha1 | 1 +
.../0.0.6/usergrid-java-client-0.0.6.pom | 95 +
.../0.0.6/usergrid-java-client-0.0.6.pom.sha1 | 1 +
.../maven-metadata-local.xml | 12 +
sdks/android/pom.xml | 31 +-
.../apache/usergrid/android/client/Client.java | 590 +
.../client/callbacks/ApiResponseCallback.java | 10 +
.../client/callbacks/ClientAsyncTask.java | 38 +
.../client/callbacks/ClientCallback.java | 9 +
.../callbacks/DeviceRegistrationCallback.java | 9 +
.../callbacks/GroupsRetrievedCallback.java | 13 +
.../client/callbacks/QueryResultsCallback.java | 9 +
.../android/client/utils/DeviceUuidFactory.java | 154 +
.../android/client/utils/ObjectUtils.java | 20 +
.../org/usergrid/android/client/Client.java | 590 -
.../client/callbacks/ApiResponseCallback.java | 10 -
.../client/callbacks/ClientAsyncTask.java | 38 -
.../client/callbacks/ClientCallback.java | 9 -
.../callbacks/DeviceRegistrationCallback.java | 9 -
.../callbacks/GroupsRetrievedCallback.java | 13 -
.../client/callbacks/QueryResultsCallback.java | 9 -
.../android/client/utils/DeviceUuidFactory.java | 154 -
.../android/client/utils/ObjectUtils.java | 20 -
sdks/java/doc/allclasses-frame.html | 123 +-
sdks/java/doc/allclasses-noframe.html | 123 +-
sdks/java/doc/constant-values.html | 1437 +-
sdks/java/doc/deprecated-list.html | 237 +-
sdks/java/doc/help-doc.html | 419 +-
sdks/java/doc/index-all.html | 1299 +
sdks/java/doc/index-files/index-1.html | 209 -
sdks/java/doc/index-files/index-10.html | 151 -
sdks/java/doc/index-files/index-11.html | 154 -
sdks/java/doc/index-files/index-12.html | 151 -
sdks/java/doc/index-files/index-13.html | 217 -
sdks/java/doc/index-files/index-14.html | 268 -
sdks/java/doc/index-files/index-15.html | 204 -
sdks/java/doc/index-files/index-16.html | 151 -
sdks/java/doc/index-files/index-17.html | 466 -
sdks/java/doc/index-files/index-18.html | 184 -
sdks/java/doc/index-files/index-19.html | 157 -
sdks/java/doc/index-files/index-2.html | 193 -
sdks/java/doc/index-files/index-20.html | 239 -
sdks/java/doc/index-files/index-21.html | 154 -
sdks/java/doc/index-files/index-3.html | 161 -
sdks/java/doc/index-files/index-4.html | 166 -
sdks/java/doc/index-files/index-5.html | 151 -
sdks/java/doc/index-files/index-6.html | 547 -
sdks/java/doc/index-files/index-7.html | 145 -
sdks/java/doc/index-files/index-8.html | 160 -
sdks/java/doc/index-files/index-9.html | 145 -
sdks/java/doc/index.html | 89 +-
.../usergrid/java/client/Client.Query.html | 238 +
.../java/client/Client.QueuePosition.html | 381 +
.../org/apache/usergrid/java/client/Client.html | 1652 +
.../java/client/class-use/Client.Query.html | 246 +
.../client/class-use/Client.QueuePosition.html | 192 +
.../usergrid/java/client/class-use/Client.html | 175 +
.../entities/Activity.ActivityCollection.html | 408 +
.../entities/Activity.ActivityObject.html | 720 +
.../client/entities/Activity.MediaLink.html | 434 +
.../usergrid/java/client/entities/Activity.html | 1449 +
.../usergrid/java/client/entities/Device.html | 387 +
.../usergrid/java/client/entities/Entity.html | 599 +
.../usergrid/java/client/entities/Group.html | 427 +
.../usergrid/java/client/entities/Message.html | 641 +
.../usergrid/java/client/entities/User.html | 707 +
.../class-use/Activity.ActivityCollection.html | 117 +
.../class-use/Activity.ActivityObject.html | 231 +
.../entities/class-use/Activity.MediaLink.html | 191 +
.../client/entities/class-use/Activity.html | 203 +
.../java/client/entities/class-use/Device.html | 169 +
.../java/client/entities/class-use/Entity.html | 415 +
.../java/client/entities/class-use/Group.html | 159 +
.../java/client/entities/class-use/Message.html | 183 +
.../java/client/entities/class-use/User.html | 248 +
.../java/client/entities/package-frame.html | 28 +
.../java/client/entities/package-summary.html | 169 +
.../java/client/entities/package-tree.html | 141 +
.../java/client/entities/package-use.html | 219 +
.../java/client/exception/ClientException.html | 263 +
.../exception/class-use/ClientException.html | 117 +
.../java/client/exception/package-frame.html | 20 +
.../java/client/exception/package-summary.html | 137 +
.../java/client/exception/package-tree.html | 142 +
.../java/client/exception/package-use.html | 117 +
.../usergrid/java/client/package-frame.html | 28 +
.../usergrid/java/client/package-summary.html | 167 +
.../usergrid/java/client/package-tree.html | 146 +
.../usergrid/java/client/package-use.html | 158 +
.../java/client/response/AggregateCounter.html | 316 +
.../client/response/AggregateCounterSet.html | 444 +
.../java/client/response/ApiResponse.html | 1148 +
.../client/response/ClientCredentialsInfo.html | 316 +
.../java/client/response/QueueInfo.html | 297 +
.../response/class-use/AggregateCounter.html | 191 +
.../response/class-use/AggregateCounterSet.html | 170 +
.../client/response/class-use/ApiResponse.html | 365 +
.../class-use/ClientCredentialsInfo.html | 170 +
.../client/response/class-use/QueueInfo.html | 187 +
.../java/client/response/package-frame.html | 24 +
.../java/client/response/package-summary.html | 151 +
.../java/client/response/package-tree.html | 134 +
.../java/client/response/package-use.html | 178 +
.../usergrid/java/client/utils/JsonUtils.html | 480 +
.../usergrid/java/client/utils/MapUtils.html | 260 +
.../usergrid/java/client/utils/ObjectUtils.html | 258 +
.../usergrid/java/client/utils/UrlUtils.html | 314 +
.../java/client/utils/class-use/JsonUtils.html | 117 +
.../java/client/utils/class-use/MapUtils.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../java/client/utils/class-use/UrlUtils.html | 117 +
.../java/client/utils/package-frame.html | 23 +
.../java/client/utils/package-summary.html | 147 +
.../java/client/utils/package-tree.html | 133 +
.../usergrid/java/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/java/doc/overview-frame.html | 73 +-
sdks/java/doc/overview-summary.html | 288 +-
sdks/java/doc/overview-tree.html | 331 +-
sdks/java/doc/package-list | 10 +-
sdks/java/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/java/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/java/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/java/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/java/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/java/doc/serialized-form.html | 134 +
sdks/java/doc/stylesheet.css | 501 +-
sdks/java/pom.xml | 182 +-
.../org/apache/usergrid/java/client/Client.java | 1276 +
.../usergrid/java/client/entities/Activity.java | 627 +
.../usergrid/java/client/entities/Device.java | 52 +
.../usergrid/java/client/entities/Entity.java | 175 +
.../usergrid/java/client/entities/Group.java | 63 +
.../usergrid/java/client/entities/Message.java | 132 +
.../usergrid/java/client/entities/User.java | 142 +
.../java/client/exception/ClientException.java | 40 +
.../java/client/response/AggregateCounter.java | 36 +
.../client/response/AggregateCounterSet.java | 95 +
.../java/client/response/ApiResponse.java | 405 +
.../client/response/ClientCredentialsInfo.java | 42 +
.../java/client/response/QueueInfo.java | 28 +
.../usergrid/java/client/utils/JsonUtils.java | 166 +
.../usergrid/java/client/utils/MapUtils.java | 23 +
.../usergrid/java/client/utils/ObjectUtils.java | 20 +
.../usergrid/java/client/utils/UrlUtils.java | 108 +
.../java/org/usergrid/java/client/Client.java | 1276 -
.../usergrid/java/client/entities/Activity.java | 627 -
.../usergrid/java/client/entities/Device.java | 52 -
.../usergrid/java/client/entities/Entity.java | 175 -
.../usergrid/java/client/entities/Group.java | 63 -
.../usergrid/java/client/entities/Message.java | 132 -
.../org/usergrid/java/client/entities/User.java | 142 -
.../java/client/exception/ClientException.java | 40 -
.../java/client/response/AggregateCounter.java | 36 -
.../client/response/AggregateCounterSet.java | 95 -
.../java/client/response/ApiResponse.java | 405 -
.../client/response/ClientCredentialsInfo.java | 42 -
.../java/client/response/QueueInfo.java | 28 -
.../usergrid/java/client/utils/JsonUtils.java | 166 -
.../usergrid/java/client/utils/MapUtils.java | 23 -
.../usergrid/java/client/utils/ObjectUtils.java | 20 -
.../usergrid/java/client/utils/UrlUtils.java | 108 -
.../lib/vendor/Apigee/Usergrid/Collection.php | 18 +-
sdks/php/lib/vendor/Apigee/Usergrid/Entity.php | 90 +-
stack/build-tools/pom.xml | 4 +-
.../src/main/resources/usergrid/checkstyle.xml | 2 +-
stack/config/pom.xml | 4 +-
stack/config/src/main/resources/log4j.xml | 14 +-
.../main/resources/usergrid-default.properties | 2 +-
.../config/src/test/resources/log4j.properties | 14 +-
stack/config/src/test/resources/log4j.xml | 4 +-
stack/core/pom.xml | 14 +-
.../persistence/query/tree/QueryFilter.g | 311 +
.../persistence/query/tree/QueryFilter.g | 311 -
.../java/org/apache/usergrid/batch/AppArgs.java | 57 +
.../java/org/apache/usergrid/batch/Job.java | 20 +
.../org/apache/usergrid/batch/JobExecution.java | 91 +
.../apache/usergrid/batch/JobExecutionImpl.java | 202 +
.../org/apache/usergrid/batch/JobFactory.java | 19 +
.../usergrid/batch/JobNotFoundException.java | 23 +
.../org/apache/usergrid/batch/JobRuntime.java | 40 +
.../usergrid/batch/JobRuntimeException.java | 49 +
.../usergrid/batch/UsergridJobFactory.java | 37 +
.../apache/usergrid/batch/job/OnlyOnceJob.java | 85 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../usergrid/batch/repository/JobAccessor.java | 36 +
.../batch/repository/JobDescriptor.java | 80 +
.../usergrid/batch/repository/package-info.java | 18 +
.../org/apache/usergrid/batch/service/App.java | 70 +
.../usergrid/batch/service/JobListener.java | 50 +
.../batch/service/JobRuntimeService.java | 49 +
.../batch/service/JobSchedulerService.java | 315 +
.../batch/service/SchedulerService.java | 54 +
.../batch/service/SchedulerServiceImpl.java | 428 +
.../usergrid/batch/service/package-info.java | 18 +
.../hazelcast/HazelcastLifecycleMonitor.java | 78 +
.../apache/usergrid/count/AbstractBatcher.java | 175 +
.../apache/usergrid/count/BatchSubmitter.java | 30 +
.../java/org/apache/usergrid/count/Batcher.java | 35 +
.../usergrid/count/CassandraCounterStore.java | 100 +
.../usergrid/count/CassandraSubmitter.java | 77 +
.../apache/usergrid/count/CountProducer.java | 25 +
.../CounterProcessingUnavailableException.java | 38 +
.../org/apache/usergrid/count/CounterStore.java | 30 +
.../apache/usergrid/count/SimpleBatcher.java | 40 +
.../usergrid/count/Slf4JBatchSubmitter.java | 77 +
.../org/apache/usergrid/count/common/Count.java | 139 +
.../usergrid/count/common/CountSerDeUtils.java | 51 +
.../common/CountTransportSerDeException.java | 38 +
.../org/apache/usergrid/count/package-info.java | 2 +
.../usergrid/exception/JsonReadException.java | 27 +
.../usergrid/exception/JsonWriteException.java | 27 +
.../exception/NotImplementedException.java | 58 +
.../java/org/apache/usergrid/locking/Lock.java | 44 +
.../org/apache/usergrid/locking/LockHelper.java | 51 +
.../apache/usergrid/locking/LockManager.java | 40 +
.../usergrid/locking/LockPathBuilder.java | 68 +
.../locking/cassandra/HectorLockImpl.java | 85 +
.../cassandra/HectorLockManagerImpl.java | 141 +
.../locking/exception/UGLockException.java | 49 +
.../usergrid/locking/noop/NoOpLockImpl.java | 61 +
.../locking/noop/NoOpLockManagerImpl.java | 40 +
.../locking/singlenode/SingleNodeLockImpl.java | 70 +
.../singlenode/SingleNodeLockManagerImpl.java | 93 +
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 +
.../locking/zookeeper/ZookeeperLockImpl.java | 87 +
.../org/apache/usergrid/mq/CounterQuery.java | 313 +
.../java/org/apache/usergrid/mq/Message.java | 512 +
.../main/java/org/apache/usergrid/mq/Query.java | 1857 +
.../apache/usergrid/mq/QueryFilterLexer.java | 1842 +
.../apache/usergrid/mq/QueryFilterParser.java | 1102 +
.../org/apache/usergrid/mq/QueryProcessor.java | 562 +
.../main/java/org/apache/usergrid/mq/Queue.java | 291 +
.../org/apache/usergrid/mq/QueueManager.java | 130 +
.../apache/usergrid/mq/QueueManagerFactory.java | 41 +
.../org/apache/usergrid/mq/QueuePosition.java | 59 +
.../java/org/apache/usergrid/mq/QueueQuery.java | 306 +
.../org/apache/usergrid/mq/QueueResults.java | 128 +
.../java/org/apache/usergrid/mq/QueueSet.java | 192 +
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 +
.../mq/cassandra/MessageIndexUpdate.java | 120 +
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 +
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 +
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 +
.../apache/usergrid/mq/cassandra/QueuesCF.java | 156 +
.../mq/cassandra/io/AbstractSearch.java | 358 +
.../mq/cassandra/io/ConsumerTransaction.java | 471 +
.../usergrid/mq/cassandra/io/EndSearch.java | 69 +
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 +
.../mq/cassandra/io/NoTransactionSearch.java | 132 +
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 +
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 +
.../usergrid/mq/cassandra/io/StartSearch.java | 68 +
.../usergrid/persistence/AbstractEntity.java | 341 +
.../usergrid/persistence/AggregateCounter.java | 48 +
.../persistence/AggregateCounterSet.java | 116 +
.../persistence/AssociatedEntityRef.java | 21 +
.../usergrid/persistence/CollectionRef.java | 26 +
.../persistence/ConnectedEntityRef.java | 22 +
.../usergrid/persistence/ConnectionRef.java | 34 +
.../usergrid/persistence/CounterQuery.java | 312 +
.../usergrid/persistence/CounterResolution.java | 84 +
.../usergrid/persistence/CredentialsInfo.java | 176 +
.../usergrid/persistence/DynamicEntity.java | 111 +
.../org/apache/usergrid/persistence/Entity.java | 102 +
.../usergrid/persistence/EntityFactory.java | 131 +
.../usergrid/persistence/EntityManager.java | 620 +
.../persistence/EntityManagerFactory.java | 108 +
.../persistence/EntityPropertyComparator.java | 55 +
.../apache/usergrid/persistence/EntityRef.java | 37 +
.../usergrid/persistence/EntityUtils.java | 53 +
.../apache/usergrid/persistence/Identifier.java | 226 +
.../persistence/IndexBucketLocator.java | 75 +
.../persistence/MultiQueryIterator.java | 106 +
.../persistence/PagingResultsIterator.java | 109 +
.../apache/usergrid/persistence/PathQuery.java | 115 +
.../org/apache/usergrid/persistence/Query.java | 1310 +
.../apache/usergrid/persistence/QueryUtils.java | 34 +
.../usergrid/persistence/RelationManager.java | 113 +
.../apache/usergrid/persistence/Results.java | 1294 +
.../apache/usergrid/persistence/RoleRef.java | 31 +
.../org/apache/usergrid/persistence/Schema.java | 1788 +
.../persistence/SimpleCollectionRef.java | 84 +
.../usergrid/persistence/SimpleEntityRef.java | 149 +
.../usergrid/persistence/SimpleRoleRef.java | 125 +
.../usergrid/persistence/TypedEntity.java | 37 +
.../org/apache/usergrid/persistence/Update.java | 75 +
.../annotations/EntityCollection.java | 43 +
.../annotations/EntityDictionary.java | 38 +
.../persistence/annotations/EntityProperty.java | 54 +
.../persistence/cassandra/ApplicationCF.java | 160 +
.../usergrid/persistence/cassandra/CFEnum.java | 37 +
.../cassandra/CassandraPersistenceUtils.java | 486 +
.../persistence/cassandra/CassandraService.java | 1138 +
.../cassandra/ConnectedEntityRefImpl.java | 61 +
.../cassandra/ConnectionRefImpl.java | 628 +
.../persistence/cassandra/CounterUtils.java | 400 +
.../persistence/cassandra/CursorCache.java | 121 +
.../cassandra/EntityManagerFactoryImpl.java | 411 +
.../cassandra/EntityManagerImpl.java | 2858 +
.../cassandra/EntityValueSerializer.java | 52 +
.../persistence/cassandra/GeoIndexManager.java | 323 +
.../persistence/cassandra/IndexUpdate.java | 450 +
.../persistence/cassandra/QueryProcessor.java | 720 +
.../cassandra/RelationManagerImpl.java | 2334 +
.../usergrid/persistence/cassandra/Setup.java | 206 +
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 +
.../cassandra/index/ConnectedIndexScanner.java | 281 +
.../cassandra/index/IndexBucketScanner.java | 239 +
.../index/IndexMultiBucketSetLoader.java | 138 +
.../cassandra/index/IndexScanner.java | 39 +
.../cassandra/index/NoOpIndexScanner.java | 94 +
.../cassandra/util/Slf4jTraceTagReporter.java | 47 +
.../cassandra/util/TaggedOpTimer.java | 38 +
.../persistence/cassandra/util/TimedOpTag.java | 101 +
.../cassandra/util/TraceParticipant.java | 20 +
.../persistence/cassandra/util/TraceTag.java | 77 +
.../cassandra/util/TraceTagAspect.java | 41 +
.../cassandra/util/TraceTagManager.java | 156 +
.../cassandra/util/TraceTagReporter.java | 10 +
.../usergrid/persistence/entities/Activity.java | 685 +
.../persistence/entities/Application.java | 609 +
.../usergrid/persistence/entities/Asset.java | 93 +
.../usergrid/persistence/entities/Device.java | 105 +
.../usergrid/persistence/entities/Event.java | 155 +
.../usergrid/persistence/entities/Folder.java | 93 +
.../usergrid/persistence/entities/Group.java | 168 +
.../usergrid/persistence/entities/JobData.java | 54 +
.../usergrid/persistence/entities/JobStat.java | 175 +
.../usergrid/persistence/entities/Message.java | 77 +
.../usergrid/persistence/entities/Role.java | 153 +
.../usergrid/persistence/entities/User.java | 348 +
.../ApplicationAlreadyExistsException.java | 37 +
.../DuplicateUniquePropertyExistsException.java | 52 +
.../exceptions/EntityNotFoundException.java | 45 +
.../exceptions/LockingException.java | 65 +
.../exceptions/NoFullTextIndexException.java | 50 +
.../exceptions/NoIndexException.java | 50 +
.../exceptions/PersistenceException.java | 45 +
.../PropertyTypeConversionException.java | 71 +
.../exceptions/QueryIterationException.java | 13 +
.../exceptions/QueryParseException.java | 63 +
.../exceptions/QueryTokenException.java | 52 +
.../persistence/exceptions/QueueException.java | 61 +
.../RequiredPropertyNotFoundException.java | 41 +
.../TransactionNotFoundException.java | 45 +
.../UnexpectedEntityTypeException.java | 45 +
.../persistence/geo/CollectionGeoSearch.java | 52 +
.../persistence/geo/ConnectionGeoSearch.java | 51 +
.../persistence/geo/EntityLocationRef.java | 211 +
.../EntityLocationRefDistanceComparator.java | 77 +
.../persistence/geo/GeoIndexSearcher.java | 368 +
.../persistence/geo/GeocellManager.java | 179 +
.../usergrid/persistence/geo/GeocellUtils.java | 539 +
.../geo/comparator/DoubleTupleComparator.java | 23 +
.../persistence/geo/model/BoundingBox.java | 71 +
.../persistence/geo/model/CostFunction.java | 33 +
.../geo/model/DefaultCostFunction.java | 34 +
.../usergrid/persistence/geo/model/Point.java | 58 +
.../usergrid/persistence/geo/model/Tuple.java | 24 +
.../usergrid/persistence/query/ir/AllNode.java | 54 +
.../usergrid/persistence/query/ir/AndNode.java | 43 +
.../persistence/query/ir/BooleanNode.java | 48 +
.../query/ir/EmailIdentifierNode.java | 31 +
.../query/ir/NameIdentifierNode.java | 28 +
.../persistence/query/ir/NodeVisitor.java | 78 +
.../usergrid/persistence/query/ir/NotNode.java | 62 +
.../usergrid/persistence/query/ir/OrNode.java | 52 +
.../persistence/query/ir/OrderByNode.java | 92 +
.../persistence/query/ir/QueryNode.java | 28 +
.../persistence/query/ir/QuerySlice.java | 344 +
.../persistence/query/ir/SearchVisitor.java | 254 +
.../persistence/query/ir/SliceNode.java | 167 +
.../query/ir/UuidIdentifierNode.java | 32 +
.../persistence/query/ir/WithinNode.java | 96 +
.../query/ir/result/AbstractScanColumn.java | 70 +
.../result/CollectionResultsLoaderFactory.java | 23 +
.../ir/result/ConnectionIndexSliceParser.java | 86 +
.../query/ir/result/ConnectionRefLoader.java | 65 +
.../result/ConnectionResultsLoaderFactory.java | 32 +
.../ir/result/ConnectionTypesIterator.java | 179 +
.../query/ir/result/EmptyIterator.java | 47 +
.../query/ir/result/EntityRefLoader.java | 50 +
.../query/ir/result/EntityResultsLoader.java | 46 +
.../query/ir/result/GeoIterator.java | 355 +
.../persistence/query/ir/result/IDLoader.java | 24 +
.../query/ir/result/IntersectionIterator.java | 169 +
.../query/ir/result/MergeIterator.java | 149 +
.../query/ir/result/MultiIterator.java | 54 +
.../query/ir/result/OrderByIterator.java | 252 +
.../query/ir/result/ResultIterator.java | 43 +
.../query/ir/result/ResultsLoader.java | 29 +
.../query/ir/result/ResultsLoaderFactory.java | 21 +
.../persistence/query/ir/result/ScanColumn.java | 16 +
.../query/ir/result/ScanColumnTransformer.java | 23 +
.../ir/result/SecondaryIndexSliceParser.java | 60 +
.../query/ir/result/SliceIterator.java | 241 +
.../query/ir/result/SliceParser.java | 31 +
.../query/ir/result/StaticIdIterator.java | 66 +
.../query/ir/result/SubtractionIterator.java | 108 +
.../query/ir/result/UUIDIndexSliceParser.java | 50 +
.../query/ir/result/UnionIterator.java | 267 +
.../usergrid/persistence/query/tree/.gitignore | 2 +
.../persistence/query/tree/AndOperand.java | 48 +
.../persistence/query/tree/BooleanLiteral.java | 48 +
.../persistence/query/tree/BooleanOperand.java | 48 +
.../persistence/query/tree/ContainsOperand.java | 69 +
.../query/tree/ContainsProperty.java | 57 +
.../usergrid/persistence/query/tree/Equal.java | 52 +
.../persistence/query/tree/EqualityOperand.java | 88 +
.../persistence/query/tree/FloatLiteral.java | 57 +
.../persistence/query/tree/GreaterThan.java | 52 +
.../query/tree/GreaterThanEqual.java | 56 +
.../persistence/query/tree/LessThan.java | 52 +
.../persistence/query/tree/LessThanEqual.java | 54 +
.../persistence/query/tree/Literal.java | 38 +
.../persistence/query/tree/LiteralFactory.java | 58 +
.../persistence/query/tree/LongLiteral.java | 64 +
.../persistence/query/tree/NotOperand.java | 45 +
.../persistence/query/tree/NumericLiteral.java | 24 +
.../persistence/query/tree/Operand.java | 47 +
.../persistence/query/tree/OrOperand.java | 53 +
.../persistence/query/tree/Property.java | 62 +
.../persistence/query/tree/QueryVisitor.java | 90 +
.../persistence/query/tree/StringLiteral.java | 82 +
.../persistence/query/tree/UUIDLiteral.java | 49 +
.../persistence/query/tree/WithinOperand.java | 111 +
.../persistence/query/tree/WithinProperty.java | 54 +
.../persistence/schema/CollectionInfo.java | 207 +
.../persistence/schema/DictionaryInfo.java | 117 +
.../usergrid/persistence/schema/EntityInfo.java | 299 +
.../persistence/schema/PropertyInfo.java | 218 +
.../usergrid/system/UsergridSystemMonitor.java | 95 +
.../org/apache/usergrid/utils/AESUtils.java | 84 +
.../java/org/apache/usergrid/utils/BCrypt.java | 627 +
.../org/apache/usergrid/utils/ClassUtils.java | 58 +
.../org/apache/usergrid/utils/CodecUtils.java | 45 +
.../apache/usergrid/utils/CompositeUtils.java | 54 +
.../apache/usergrid/utils/ConversionUtils.java | 765 +
.../org/apache/usergrid/utils/DateUtils.java | 88 +
.../org/apache/usergrid/utils/HttpUtils.java | 51 +
.../org/apache/usergrid/utils/IndexUtils.java | 218 +
.../apache/usergrid/utils/InflectionUtils.java | 51 +
.../org/apache/usergrid/utils/Inflector.java | 553 +
.../org/apache/usergrid/utils/JsonUtils.java | 329 +
.../org/apache/usergrid/utils/ListUtils.java | 230 +
.../org/apache/usergrid/utils/MailUtils.java | 154 +
.../org/apache/usergrid/utils/MapUtils.java | 377 +
.../org/apache/usergrid/utils/NumberUtils.java | 35 +
.../apache/usergrid/utils/PasswordUtils.java | 28 +
.../org/apache/usergrid/utils/StringUtils.java | 172 +
.../org/apache/usergrid/utils/TimeUtils.java | 88 +
.../org/apache/usergrid/utils/UUIDUtils.java | 412 +
.../java/org/apache/usergrid/utils/Version.java | 428 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../main/java/org/usergrid/batch/AppArgs.java | 57 -
.../src/main/java/org/usergrid/batch/Job.java | 20 -
.../java/org/usergrid/batch/JobExecution.java | 91 -
.../org/usergrid/batch/JobExecutionImpl.java | 202 -
.../java/org/usergrid/batch/JobFactory.java | 19 -
.../usergrid/batch/JobNotFoundException.java | 23 -
.../java/org/usergrid/batch/JobRuntime.java | 40 -
.../org/usergrid/batch/JobRuntimeException.java | 49 -
.../org/usergrid/batch/UsergridJobFactory.java | 37 -
.../org/usergrid/batch/job/OnlyOnceJob.java | 85 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../usergrid/batch/repository/JobAccessor.java | 36 -
.../batch/repository/JobDescriptor.java | 80 -
.../usergrid/batch/repository/package-info.java | 18 -
.../java/org/usergrid/batch/service/App.java | 70 -
.../org/usergrid/batch/service/JobListener.java | 50 -
.../batch/service/JobRuntimeService.java | 49 -
.../batch/service/JobSchedulerService.java | 315 -
.../batch/service/SchedulerService.java | 54 -
.../batch/service/SchedulerServiceImpl.java | 428 -
.../usergrid/batch/service/package-info.java | 18 -
.../hazelcast/HazelcastLifecycleMonitor.java | 78 -
.../org/usergrid/count/AbstractBatcher.java | 175 -
.../java/org/usergrid/count/BatchSubmitter.java | 30 -
.../main/java/org/usergrid/count/Batcher.java | 35 -
.../usergrid/count/CassandraCounterStore.java | 100 -
.../org/usergrid/count/CassandraSubmitter.java | 77 -
.../java/org/usergrid/count/CountProducer.java | 25 -
.../CounterProcessingUnavailableException.java | 38 -
.../java/org/usergrid/count/CounterStore.java | 30 -
.../java/org/usergrid/count/SimpleBatcher.java | 40 -
.../org/usergrid/count/Slf4JBatchSubmitter.java | 77 -
.../java/org/usergrid/count/common/Count.java | 139 -
.../usergrid/count/common/CountSerDeUtils.java | 51 -
.../common/CountTransportSerDeException.java | 38 -
.../java/org/usergrid/count/package-info.java | 0
.../usergrid/exception/JsonReadException.java | 27 -
.../usergrid/exception/JsonWriteException.java | 27 -
.../exception/NotImplementedException.java | 58 -
.../main/java/org/usergrid/locking/Lock.java | 44 -
.../java/org/usergrid/locking/LockHelper.java | 51 -
.../java/org/usergrid/locking/LockManager.java | 40 -
.../org/usergrid/locking/LockPathBuilder.java | 68 -
.../locking/cassandra/HectorLockImpl.java | 85 -
.../cassandra/HectorLockManagerImpl.java | 141 -
.../locking/exception/UGLockException.java | 49 -
.../org/usergrid/locking/noop/NoOpLockImpl.java | 61 -
.../locking/noop/NoOpLockManagerImpl.java | 40 -
.../locking/singlenode/SingleNodeLockImpl.java | 70 -
.../singlenode/SingleNodeLockManagerImpl.java | 93 -
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 -
.../locking/zookeeper/ZookeeperLockImpl.java | 87 -
.../main/java/org/usergrid/mq/CounterQuery.java | 314 -
.../src/main/java/org/usergrid/mq/Message.java | 512 -
.../src/main/java/org/usergrid/mq/Query.java | 1857 -
.../java/org/usergrid/mq/QueryFilterLexer.java | 1842 -
.../java/org/usergrid/mq/QueryFilterParser.java | 1102 -
.../java/org/usergrid/mq/QueryProcessor.java | 562 -
.../src/main/java/org/usergrid/mq/Queue.java | 291 -
.../main/java/org/usergrid/mq/QueueManager.java | 130 -
.../org/usergrid/mq/QueueManagerFactory.java | 41 -
.../java/org/usergrid/mq/QueuePosition.java | 59 -
.../main/java/org/usergrid/mq/QueueQuery.java | 306 -
.../main/java/org/usergrid/mq/QueueResults.java | 128 -
.../src/main/java/org/usergrid/mq/QueueSet.java | 192 -
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 -
.../mq/cassandra/MessageIndexUpdate.java | 120 -
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 -
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 -
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 -
.../org/usergrid/mq/cassandra/QueuesCF.java | 156 -
.../mq/cassandra/io/AbstractSearch.java | 358 -
.../mq/cassandra/io/ConsumerTransaction.java | 471 -
.../org/usergrid/mq/cassandra/io/EndSearch.java | 69 -
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 -
.../mq/cassandra/io/NoTransactionSearch.java | 132 -
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 -
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 -
.../usergrid/mq/cassandra/io/StartSearch.java | 68 -
.../usergrid/persistence/AbstractEntity.java | 342 -
.../usergrid/persistence/AggregateCounter.java | 48 -
.../persistence/AggregateCounterSet.java | 116 -
.../persistence/AssociatedEntityRef.java | 21 -
.../org/usergrid/persistence/CollectionRef.java | 26 -
.../persistence/ConnectedEntityRef.java | 22 -
.../org/usergrid/persistence/ConnectionRef.java | 34 -
.../org/usergrid/persistence/CounterQuery.java | 313 -
.../usergrid/persistence/CounterResolution.java | 84 -
.../usergrid/persistence/CredentialsInfo.java | 176 -
.../org/usergrid/persistence/DynamicEntity.java | 111 -
.../java/org/usergrid/persistence/Entity.java | 103 -
.../org/usergrid/persistence/EntityFactory.java | 131 -
.../org/usergrid/persistence/EntityManager.java | 620 -
.../persistence/EntityManagerFactory.java | 108 -
.../persistence/EntityPropertyComparator.java | 55 -
.../org/usergrid/persistence/EntityRef.java | 37 -
.../org/usergrid/persistence/EntityUtils.java | 53 -
.../org/usergrid/persistence/Identifier.java | 226 -
.../persistence/IndexBucketLocator.java | 75 -
.../persistence/MultiQueryIterator.java | 106 -
.../persistence/PagingResultsIterator.java | 109 -
.../org/usergrid/persistence/PathQuery.java | 115 -
.../java/org/usergrid/persistence/Query.java | 1310 -
.../org/usergrid/persistence/QueryUtils.java | 34 -
.../usergrid/persistence/RelationManager.java | 113 -
.../java/org/usergrid/persistence/Results.java | 1294 -
.../java/org/usergrid/persistence/RoleRef.java | 31 -
.../java/org/usergrid/persistence/Schema.java | 1788 -
.../persistence/SimpleCollectionRef.java | 84 -
.../usergrid/persistence/SimpleEntityRef.java | 149 -
.../org/usergrid/persistence/SimpleRoleRef.java | 125 -
.../org/usergrid/persistence/TypedEntity.java | 37 -
.../java/org/usergrid/persistence/Update.java | 75 -
.../annotations/EntityCollection.java | 43 -
.../annotations/EntityDictionary.java | 38 -
.../persistence/annotations/EntityProperty.java | 54 -
.../persistence/cassandra/ApplicationCF.java | 160 -
.../usergrid/persistence/cassandra/CFEnum.java | 37 -
.../cassandra/CassandraPersistenceUtils.java | 486 -
.../persistence/cassandra/CassandraService.java | 1138 -
.../cassandra/ConnectedEntityRefImpl.java | 61 -
.../cassandra/ConnectionRefImpl.java | 628 -
.../persistence/cassandra/CounterUtils.java | 400 -
.../persistence/cassandra/CursorCache.java | 121 -
.../cassandra/EntityManagerFactoryImpl.java | 411 -
.../cassandra/EntityManagerImpl.java | 2858 -
.../cassandra/EntityValueSerializer.java | 52 -
.../persistence/cassandra/GeoIndexManager.java | 323 -
.../persistence/cassandra/IndexUpdate.java | 450 -
.../persistence/cassandra/QueryProcessor.java | 720 -
.../cassandra/RelationManagerImpl.java | 2334 -
.../usergrid/persistence/cassandra/Setup.java | 206 -
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 -
.../cassandra/index/ConnectedIndexScanner.java | 281 -
.../cassandra/index/IndexBucketScanner.java | 239 -
.../index/IndexMultiBucketSetLoader.java | 138 -
.../cassandra/index/IndexScanner.java | 39 -
.../cassandra/index/NoOpIndexScanner.java | 94 -
.../cassandra/util/Slf4jTraceTagReporter.java | 47 -
.../cassandra/util/TaggedOpTimer.java | 38 -
.../persistence/cassandra/util/TimedOpTag.java | 101 -
.../cassandra/util/TraceParticipant.java | 20 -
.../persistence/cassandra/util/TraceTag.java | 77 -
.../cassandra/util/TraceTagAspect.java | 41 -
.../cassandra/util/TraceTagManager.java | 156 -
.../cassandra/util/TraceTagReporter.java | 10 -
.../usergrid/persistence/entities/Activity.java | 685 -
.../persistence/entities/Application.java | 609 -
.../usergrid/persistence/entities/Asset.java | 93 -
.../usergrid/persistence/entities/Device.java | 105 -
.../usergrid/persistence/entities/Event.java | 155 -
.../usergrid/persistence/entities/Folder.java | 93 -
.../usergrid/persistence/entities/Group.java | 168 -
.../usergrid/persistence/entities/JobData.java | 54 -
.../usergrid/persistence/entities/JobStat.java | 175 -
.../usergrid/persistence/entities/Message.java | 77 -
.../org/usergrid/persistence/entities/Role.java | 153 -
.../org/usergrid/persistence/entities/User.java | 348 -
.../ApplicationAlreadyExistsException.java | 37 -
.../DuplicateUniquePropertyExistsException.java | 52 -
.../exceptions/EntityNotFoundException.java | 45 -
.../exceptions/LockingException.java | 65 -
.../exceptions/NoFullTextIndexException.java | 50 -
.../exceptions/NoIndexException.java | 50 -
.../exceptions/PersistenceException.java | 45 -
.../PropertyTypeConversionException.java | 71 -
.../exceptions/QueryIterationException.java | 13 -
.../exceptions/QueryParseException.java | 63 -
.../exceptions/QueryTokenException.java | 52 -
.../persistence/exceptions/QueueException.java | 61 -
.../RequiredPropertyNotFoundException.java | 41 -
.../TransactionNotFoundException.java | 45 -
.../UnexpectedEntityTypeException.java | 45 -
.../persistence/geo/CollectionGeoSearch.java | 52 -
.../persistence/geo/ConnectionGeoSearch.java | 51 -
.../persistence/geo/EntityLocationRef.java | 211 -
.../EntityLocationRefDistanceComparator.java | 77 -
.../persistence/geo/GeoIndexSearcher.java | 368 -
.../persistence/geo/GeocellManager.java | 179 -
.../usergrid/persistence/geo/GeocellUtils.java | 539 -
.../geo/comparator/DoubleTupleComparator.java | 23 -
.../persistence/geo/model/BoundingBox.java | 71 -
.../persistence/geo/model/CostFunction.java | 33 -
.../geo/model/DefaultCostFunction.java | 34 -
.../usergrid/persistence/geo/model/Point.java | 58 -
.../usergrid/persistence/geo/model/Tuple.java | 24 -
.../usergrid/persistence/query/ir/AllNode.java | 54 -
.../usergrid/persistence/query/ir/AndNode.java | 43 -
.../persistence/query/ir/BooleanNode.java | 48 -
.../query/ir/EmailIdentifierNode.java | 31 -
.../query/ir/NameIdentifierNode.java | 28 -
.../persistence/query/ir/NodeVisitor.java | 78 -
.../usergrid/persistence/query/ir/NotNode.java | 62 -
.../usergrid/persistence/query/ir/OrNode.java | 52 -
.../persistence/query/ir/OrderByNode.java | 92 -
.../persistence/query/ir/QueryNode.java | 28 -
.../persistence/query/ir/QuerySlice.java | 344 -
.../persistence/query/ir/SearchVisitor.java | 254 -
.../persistence/query/ir/SliceNode.java | 168 -
.../query/ir/UuidIdentifierNode.java | 32 -
.../persistence/query/ir/WithinNode.java | 96 -
.../query/ir/result/AbstractScanColumn.java | 70 -
.../result/CollectionResultsLoaderFactory.java | 23 -
.../ir/result/ConnectionIndexSliceParser.java | 86 -
.../query/ir/result/ConnectionRefLoader.java | 65 -
.../result/ConnectionResultsLoaderFactory.java | 32 -
.../ir/result/ConnectionTypesIterator.java | 179 -
.../query/ir/result/EmptyIterator.java | 47 -
.../query/ir/result/EntityRefLoader.java | 50 -
.../query/ir/result/EntityResultsLoader.java | 46 -
.../query/ir/result/GeoIterator.java | 355 -
.../persistence/query/ir/result/IDLoader.java | 24 -
.../query/ir/result/IntersectionIterator.java | 169 -
.../query/ir/result/MergeIterator.java | 149 -
.../query/ir/result/MultiIterator.java | 54 -
.../query/ir/result/OrderByIterator.java | 252 -
.../query/ir/result/ResultIterator.java | 43 -
.../query/ir/result/ResultsLoader.java | 29 -
.../query/ir/result/ResultsLoaderFactory.java | 21 -
.../persistence/query/ir/result/ScanColumn.java | 16 -
.../query/ir/result/ScanColumnTransformer.java | 23 -
.../ir/result/SecondaryIndexSliceParser.java | 60 -
.../query/ir/result/SliceIterator.java | 241 -
.../query/ir/result/SliceParser.java | 31 -
.../query/ir/result/StaticIdIterator.java | 66 -
.../query/ir/result/SubtractionIterator.java | 108 -
.../query/ir/result/UUIDIndexSliceParser.java | 50 -
.../query/ir/result/UnionIterator.java | 267 -
.../usergrid/persistence/query/tree/.gitignore | 2 -
.../persistence/query/tree/AndOperand.java | 48 -
.../persistence/query/tree/BooleanLiteral.java | 48 -
.../persistence/query/tree/BooleanOperand.java | 48 -
.../persistence/query/tree/ContainsOperand.java | 69 -
.../query/tree/ContainsProperty.java | 57 -
.../usergrid/persistence/query/tree/Equal.java | 52 -
.../persistence/query/tree/EqualityOperand.java | 88 -
.../persistence/query/tree/FloatLiteral.java | 57 -
.../persistence/query/tree/GreaterThan.java | 52 -
.../query/tree/GreaterThanEqual.java | 56 -
.../persistence/query/tree/LessThan.java | 52 -
.../persistence/query/tree/LessThanEqual.java | 54 -
.../persistence/query/tree/Literal.java | 38 -
.../persistence/query/tree/LiteralFactory.java | 58 -
.../persistence/query/tree/LongLiteral.java | 64 -
.../persistence/query/tree/NotOperand.java | 45 -
.../persistence/query/tree/NumericLiteral.java | 24 -
.../persistence/query/tree/Operand.java | 47 -
.../persistence/query/tree/OrOperand.java | 53 -
.../persistence/query/tree/Property.java | 62 -
.../persistence/query/tree/QueryVisitor.java | 90 -
.../persistence/query/tree/StringLiteral.java | 82 -
.../persistence/query/tree/UUIDLiteral.java | 49 -
.../persistence/query/tree/WithinOperand.java | 111 -
.../persistence/query/tree/WithinProperty.java | 54 -
.../persistence/schema/CollectionInfo.java | 207 -
.../persistence/schema/DictionaryInfo.java | 117 -
.../usergrid/persistence/schema/EntityInfo.java | 299 -
.../persistence/schema/PropertyInfo.java | 218 -
.../usergrid/system/UsergridSystemMonitor.java | 95 -
.../main/java/org/usergrid/utils/AESUtils.java | 84 -
.../main/java/org/usergrid/utils/BCrypt.java | 627 -
.../java/org/usergrid/utils/ClassUtils.java | 58 -
.../java/org/usergrid/utils/CodecUtils.java | 45 -
.../java/org/usergrid/utils/CompositeUtils.java | 54 -
.../org/usergrid/utils/ConversionUtils.java | 765 -
.../main/java/org/usergrid/utils/DateUtils.java | 88 -
.../main/java/org/usergrid/utils/HttpUtils.java | 51 -
.../java/org/usergrid/utils/IndexUtils.java | 218 -
.../org/usergrid/utils/InflectionUtils.java | 51 -
.../main/java/org/usergrid/utils/Inflector.java | 553 -
.../main/java/org/usergrid/utils/JsonUtils.java | 329 -
.../main/java/org/usergrid/utils/ListUtils.java | 230 -
.../main/java/org/usergrid/utils/MailUtils.java | 154 -
.../main/java/org/usergrid/utils/MapUtils.java | 377 -
.../java/org/usergrid/utils/NumberUtils.java | 35 -
.../java/org/usergrid/utils/PasswordUtils.java | 28 -
.../java/org/usergrid/utils/StringUtils.java | 172 -
.../main/java/org/usergrid/utils/TimeUtils.java | 88 -
.../main/java/org/usergrid/utils/UUIDUtils.java | 412 -
.../main/java/org/usergrid/utils/Version.java | 428 -
.../java/org/usergrid/utils/package-info.java | 18 -
.../main/resources/usergrid-core-context.xml | 52 +-
.../resources/usergrid-scheduler-context.xml | 8 +-
stack/core/src/test/java/io/baas/Simple.java | 4 +-
.../org/apache/usergrid/AbstractCoreIT.java | 45 +
.../java/org/apache/usergrid/Application.java | 124 +
.../apache/usergrid/ConcurrentCoreITSuite.java | 50 +
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 +
.../usergrid/ConcurrentCoreTestSuite.java | 33 +
.../org/apache/usergrid/CoreApplication.java | 171 +
.../java/org/apache/usergrid/CoreITSetup.java | 43 +
.../org/apache/usergrid/CoreITSetupImpl.java | 145 +
.../java/org/apache/usergrid/CoreITSuite.java | 34 +
.../java/org/apache/usergrid/CoreTestSuite.java | 47 +
.../org/apache/usergrid/batch/AppArgsTest.java | 52 +
.../batch/BulkJobExecutionUnitTest.java | 209 +
.../apache/usergrid/batch/BulkTestUtils.java | 38 +
.../batch/ConcurrentSchedulerITSuite.java | 31 +
.../batch/ConcurrentSchedulerTestSuite.java | 19 +
.../apache/usergrid/batch/SchedulerITSuite.java | 34 +
.../usergrid/batch/SchedulerTestSuite.java | 18 +
.../usergrid/batch/UsergridJobFactoryTest.java | 31 +
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 +
.../usergrid/batch/job/CountdownLatchJob.java | 67 +
.../usergrid/batch/job/DelayExecution.java | 104 +
.../usergrid/batch/job/DelayHeartbeat.java | 106 +
.../batch/job/FailureJobExceuction.java | 74 +
.../usergrid/batch/job/OnlyOnceExceution.java | 116 +
.../job/OnlyOnceUnlockOnFailExceution.java | 126 +
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 +
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 +
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 +
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 +
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 +
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 +
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 +
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 +
.../usergrid/batch/job/TestJobListener.java | 121 +
.../usergrid/batch/job/TestJobListenerTest.java | 144 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../clustering/hazelcast/HazelcastTest.java | 111 +
.../count/BatchCountParallelismTest.java | 122 +
.../usergrid/count/SimpleBatcherTest.java | 50 +
.../count/common/CountSerDeUtilsTest.java | 68 +
.../apache/usergrid/count/common/CountTest.java | 68 +
.../locking/cassandra/HectorLockManagerIT.java | 185 +
.../SingleNodeLockTestSingleNode.java | 168 +
.../zookeeper/AbstractZooKeeperTest.java | 126 +
.../usergrid/locking/zookeeper/ZooPut.java | 113 +
.../zookeeper/ZookeeperLockManagerTest.java | 182 +
.../java/org/apache/usergrid/mq/MessagesIT.java | 278 +
.../org/apache/usergrid/mq/QueuePathsTest.java | 48 +
.../usergrid/persistence/CollectionIT.java | 1637 +
.../usergrid/persistence/CoreSchemaManager.java | 66 +
.../apache/usergrid/persistence/CounterIT.java | 235 +
.../persistence/EntityConnectionsIT.java | 292 +
.../persistence/EntityDictionaryIT.java | 133 +
.../usergrid/persistence/EntityManagerIT.java | 563 +
.../EntityPropertyComparatorTest.java | 206 +
.../apache/usergrid/persistence/EntityTest.java | 100 +
.../org/apache/usergrid/persistence/GeoIT.java | 524 +
.../apache/usergrid/persistence/IndexIT.java | 462 +
.../usergrid/persistence/PathQueryIT.java | 164 +
.../usergrid/persistence/PermissionsIT.java | 191 +
.../apache/usergrid/persistence/QueryTest.java | 311 +
.../usergrid/persistence/QueryUtilsTest.java | 41 +
.../apache/usergrid/persistence/SchemaTest.java | 127 +
.../apache/usergrid/persistence/UtilsTest.java | 38 +
.../cassandra/EntityManagerFactoryImplIT.java | 175 +
.../cassandra/QueryProcessorTest.java | 726 +
.../SimpleIndexBucketLocatorImplTest.java | 176 +
.../cassandra/util/TraceTagUnitTest.java | 38 +
.../persistence/entities/SampleEntity.java | 58 +
...EntityLocationRefDistanceComparatorTest.java | 102 +
.../query/AbstractIteratingQueryIT.java | 1299 +
.../persistence/query/AllInCollectionIT.java | 28 +
.../persistence/query/AllInConnectionIT.java | 28 +
.../query/AllInConnectionNoTypeIT.java | 56 +
.../query/IntersectionUnionPagingIT.java | 167 +
.../query/MultiOrderByCollectionIT.java | 28 +
.../MultiOrderByComplexUnionCollectionIT.java | 28 +
.../MultiOrderByComplexUnionConnectionIT.java | 28 +
.../query/MultiOrderByConnectionIT.java | 31 +
.../query/NotOrderByCollectionIT.java | 28 +
.../query/NotOrderByConnectionIT.java | 28 +
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 +
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 +
...leOrderByBoundRangeScanDescCollectionIT.java | 28 +
...leOrderByBoundRangeScanDescConnectionIT.java | 28 +
...eOrderByComplexIntersectionCollectionIT.java | 28 +
...eOrderByComplexIntersectionConnectionIT.java | 29 +
.../SingleOrderByComplexUnionCollectionIT.java | 28 +
.../SingleOrderByComplexUnionConnectionIT.java | 28 +
.../SingleOrderByIntersectionCollectionIT.java | 30 +
.../SingleOrderByIntersectionConnectionIT.java | 30 +
.../SingleOrderByLessThanLimitCollectionIT.java | 28 +
.../SingleOrderByLessThanLimitConnectionIT.java | 28 +
.../SingleOrderByMaxLimitCollectionIT.java | 29 +
.../SingleOrderByMaxLimitConnectionIT.java | 29 +
...SingleOrderByNoIntersectionCollectionIT.java | 28 +
...SingleOrderByNoIntersectionConnectionIT.java | 28 +
.../query/SingleOrderByNotCollectionIT.java | 28 +
.../query/SingleOrderByNotConnectionIT.java | 28 +
...OrderBySameRangeScanGreaterCollectionIT.java | 28 +
...OrderBySameRangeScanGreaterConnectionIT.java | 28 +
...meRangeScanGreaterThanEqualCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessConnectionIT.java | 28 +
...ySameRangeScanLessThanEqualCollectionIT.java | 28 +
...ySameRangeScanLessThanEqualConnectionIT.java | 28 +
.../query/ir/result/AbstractScanColumnTest.java | 84 +
.../query/ir/result/InOrderIterator.java | 115 +
.../ir/result/IntersectionIteratorTest.java | 306 +
.../query/ir/result/IteratorHelper.java | 18 +
.../ir/result/SubtractionIteratorTest.java | 180 +
.../query/ir/result/UnionIteratorTest.java | 466 +
.../persistence/query/tree/GrammarTreeTest.java | 592 +
.../persistence/query/tree/LongLiteralTest.java | 61 +
.../query/tree/StringLiteralTest.java | 87 +
.../system/UsergridSystemMonitorIT.java | 51 +
.../usergrid/utils/ConversionUtilsTest.java | 49 +
.../apache/usergrid/utils/IndexUtilsTest.java | 71 +
.../apache/usergrid/utils/JsonUtilsTest.java | 85 +
.../apache/usergrid/utils/ListUtilsTest.java | 53 +
.../apache/usergrid/utils/MailUtilsTest.java | 90 +
.../org/apache/usergrid/utils/MapUtilsTest.java | 41 +
.../apache/usergrid/utils/TestInflector.java | 81 +
.../apache/usergrid/utils/TimeUtilsTest.java | 60 +
.../apache/usergrid/utils/UUIDUtilsTest.java | 371 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../test/java/org/usergrid/AbstractCoreIT.java | 45 -
.../src/test/java/org/usergrid/Application.java | 124 -
.../org/usergrid/ConcurrentCoreITSuite.java | 50 -
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 -
.../org/usergrid/ConcurrentCoreTestSuite.java | 33 -
.../test/java/org/usergrid/CoreApplication.java | 171 -
.../src/test/java/org/usergrid/CoreITSetup.java | 43 -
.../test/java/org/usergrid/CoreITSetupImpl.java | 145 -
.../src/test/java/org/usergrid/CoreITSuite.java | 34 -
.../test/java/org/usergrid/CoreTestSuite.java | 47 -
.../java/org/usergrid/batch/AppArgsTest.java | 52 -
.../batch/BulkJobExecutionUnitTest.java | 209 -
.../java/org/usergrid/batch/BulkTestUtils.java | 38 -
.../batch/ConcurrentSchedulerITSuite.java | 31 -
.../batch/ConcurrentSchedulerTestSuite.java | 19 -
.../org/usergrid/batch/SchedulerITSuite.java | 34 -
.../org/usergrid/batch/SchedulerTestSuite.java | 18 -
.../usergrid/batch/UsergridJobFactoryTest.java | 31 -
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 -
.../usergrid/batch/job/CountdownLatchJob.java | 67 -
.../org/usergrid/batch/job/DelayExecution.java | 104 -
.../org/usergrid/batch/job/DelayHeartbeat.java | 106 -
.../batch/job/FailureJobExceuction.java | 74 -
.../usergrid/batch/job/OnlyOnceExceution.java | 116 -
.../job/OnlyOnceUnlockOnFailExceution.java | 126 -
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 -
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 -
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 -
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 -
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 -
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 -
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 -
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 -
.../org/usergrid/batch/job/TestJobListener.java | 121 -
.../usergrid/batch/job/TestJobListenerTest.java | 144 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../clustering/hazelcast/HazelcastTest.java | 111 -
.../count/BatchCountParallelismTest.java | 122 -
.../org/usergrid/count/SimpleBatcherTest.java | 51 -
.../count/common/CountSerDeUtilsTest.java | 68 -
.../org/usergrid/count/common/CountTest.java | 68 -
.../locking/cassandra/HectorLockManagerIT.java | 185 -
.../SingleNodeLockTestSingleNode.java | 168 -
.../zookeeper/AbstractZooKeeperTest.java | 126 -
.../org/usergrid/locking/zookeeper/ZooPut.java | 113 -
.../zookeeper/ZookeeperLockManagerTest.java | 182 -
.../test/java/org/usergrid/mq/MessagesIT.java | 278 -
.../java/org/usergrid/mq/QueuePathsTest.java | 48 -
.../org/usergrid/persistence/CollectionIT.java | 1637 -
.../usergrid/persistence/CoreSchemaManager.java | 66 -
.../org/usergrid/persistence/CounterIT.java | 235 -
.../persistence/EntityConnectionsIT.java | 292 -
.../persistence/EntityDictionaryIT.java | 133 -
.../usergrid/persistence/EntityManagerIT.java | 563 -
.../EntityPropertyComparatorTest.java | 206 -
.../org/usergrid/persistence/EntityTest.java | 100 -
.../java/org/usergrid/persistence/GeoIT.java | 524 -
.../java/org/usergrid/persistence/IndexIT.java | 462 -
.../org/usergrid/persistence/PathQueryIT.java | 164 -
.../org/usergrid/persistence/PermissionsIT.java | 191 -
.../org/usergrid/persistence/QueryTest.java | 311 -
.../usergrid/persistence/QueryUtilsTest.java | 41 -
.../org/usergrid/persistence/SchemaTest.java | 127 -
.../org/usergrid/persistence/UtilsTest.java | 38 -
.../cassandra/EntityManagerFactoryImplIT.java | 175 -
.../cassandra/QueryProcessorTest.java | 726 -
.../SimpleIndexBucketLocatorImplTest.java | 176 -
.../cassandra/util/TraceTagUnitTest.java | 38 -
.../persistence/entities/SampleEntity.java | 58 -
...EntityLocationRefDistanceComparatorTest.java | 102 -
.../query/AbstractIteratingQueryIT.java | 1299 -
.../persistence/query/AllInCollectionIT.java | 28 -
.../persistence/query/AllInConnectionIT.java | 28 -
.../query/AllInConnectionNoTypeIT.java | 56 -
.../query/IntersectionUnionPagingIT.java | 167 -
.../query/MultiOrderByCollectionIT.java | 28 -
.../MultiOrderByComplexUnionCollectionIT.java | 28 -
.../MultiOrderByComplexUnionConnectionIT.java | 28 -
.../query/MultiOrderByConnectionIT.java | 31 -
.../query/NotOrderByCollectionIT.java | 28 -
.../query/NotOrderByConnectionIT.java | 28 -
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 -
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 -
...leOrderByBoundRangeScanDescCollectionIT.java | 28 -
...leOrderByBoundRangeScanDescConnectionIT.java | 28 -
...eOrderByComplexIntersectionCollectionIT.java | 28 -
...eOrderByComplexIntersectionConnectionIT.java | 29 -
.../SingleOrderByComplexUnionCollectionIT.java | 28 -
.../SingleOrderByComplexUnionConnectionIT.java | 28 -
.../SingleOrderByIntersectionCollectionIT.java | 30 -
.../SingleOrderByIntersectionConnectionIT.java | 30 -
.../SingleOrderByLessThanLimitCollectionIT.java | 28 -
.../SingleOrderByLessThanLimitConnectionIT.java | 28 -
.../SingleOrderByMaxLimitCollectionIT.java | 29 -
.../SingleOrderByMaxLimitConnectionIT.java | 29 -
...SingleOrderByNoIntersectionCollectionIT.java | 28 -
...SingleOrderByNoIntersectionConnectionIT.java | 28 -
.../query/SingleOrderByNotCollectionIT.java | 28 -
.../query/SingleOrderByNotConnectionIT.java | 28 -
...OrderBySameRangeScanGreaterCollectionIT.java | 28 -
...OrderBySameRangeScanGreaterConnectionIT.java | 28 -
...meRangeScanGreaterThanEqualCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessConnectionIT.java | 28 -
...ySameRangeScanLessThanEqualCollectionIT.java | 28 -
...ySameRangeScanLessThanEqualConnectionIT.java | 28 -
.../query/ir/result/AbstractScanColumnTest.java | 84 -
.../query/ir/result/InOrderIterator.java | 115 -
.../ir/result/IntersectionIteratorTest.java | 306 -
.../query/ir/result/IteratorHelper.java | 18 -
.../ir/result/SubtractionIteratorTest.java | 180 -
.../query/ir/result/UnionIteratorTest.java | 466 -
.../persistence/query/tree/GrammarTreeTest.java | 592 -
.../persistence/query/tree/LongLiteralTest.java | 61 -
.../query/tree/StringLiteralTest.java | 87 -
.../system/UsergridSystemMonitorIT.java | 51 -
.../org/usergrid/utils/ConversionUtilsTest.java | 49 -
.../java/org/usergrid/utils/IndexUtilsTest.java | 71 -
.../java/org/usergrid/utils/JsonUtilsTest.java | 85 -
.../java/org/usergrid/utils/ListUtilsTest.java | 53 -
.../java/org/usergrid/utils/MailUtilsTest.java | 90 -
.../java/org/usergrid/utils/MapUtilsTest.java | 41 -
.../java/org/usergrid/utils/TestInflector.java | 81 -
.../java/org/usergrid/utils/TimeUtilsTest.java | 60 -
.../java/org/usergrid/utils/UUIDUtilsTest.java | 371 -
.../java/org/usergrid/utils/package-info.java | 18 -
stack/core/src/test/resources/log4j.properties | 16 +-
.../test/resources/usergrid-test-context.xml | 4 +-
.../impl/EntityCollectionManagerImpl.java | 1 -
stack/launcher/pom.xml | 12 +-
.../java/org/apache/usergrid/launcher/App.java | 288 +
.../apache/usergrid/launcher/AppleUtils.java | 38 +
.../launcher/ClasspathStaticHttpHandler.java | 320 +
.../launcher/CustomJSPTemplateProcessor.java | 137 +
.../usergrid/launcher/EmbeddedServerHelper.java | 193 +
.../org/apache/usergrid/launcher/JarMain.java | 40 +
.../apache/usergrid/launcher/LauncherFrame.java | 461 +
.../usergrid/launcher/LogViewerFrame.java | 104 +
.../org/apache/usergrid/launcher/Server.java | 618 +
.../apache/usergrid/launcher/package-info.java | 18 +
.../main/java/org/usergrid/launcher/App.java | 288 -
.../java/org/usergrid/launcher/AppleUtils.java | 38 -
.../launcher/ClasspathStaticHttpHandler.java | 320 -
.../launcher/CustomJSPTemplateProcessor.java | 137 -
.../usergrid/launcher/EmbeddedServerHelper.java | 193 -
.../java/org/usergrid/launcher/JarMain.java | 40 -
.../org/usergrid/launcher/LauncherFrame.java | 461 -
.../org/usergrid/launcher/LogViewerFrame.java | 104 -
.../main/java/org/usergrid/launcher/Server.java | 618 -
.../org/usergrid/launcher/package-info.java | 18 -
.../src/main/resources/log4j.properties | 14 +-
.../org/apache/usergrid/launcher/dock_icon.png | Bin 0 -> 11592 bytes
.../org/apache/usergrid/launcher/icon_16.png | Bin 0 -> 3273 bytes
.../org/apache/usergrid/launcher/icon_256.png | Bin 0 -> 12578 bytes
.../org/apache/usergrid/launcher/icon_32.png | Bin 0 -> 3862 bytes
.../org/apache/usergrid/launcher/icon_64.png | Bin 0 -> 5079 bytes
.../org/apache/usergrid/launcher/log_viewer.png | Bin 0 -> 6610 bytes
.../org/apache/usergrid/launcher/start.png | Bin 0 -> 9253 bytes
.../apache/usergrid/launcher/start_active.png | Bin 0 -> 9334 bytes
.../apache/usergrid/launcher/status_green.png | Bin 0 -> 2048 bytes
.../org/apache/usergrid/launcher/status_off.png | Bin 0 -> 1847 bytes
.../org/apache/usergrid/launcher/status_red.png | Bin 0 -> 2047 bytes
.../apache/usergrid/launcher/status_yellow.png | Bin 0 -> 2092 bytes
.../org/apache/usergrid/launcher/stop.png | Bin 0 -> 8858 bytes
.../apache/usergrid/launcher/stop_active.png | Bin 0 -> 8844 bytes
.../apache/usergrid/launcher/web_browser.png | Bin 0 -> 4531 bytes
.../org/usergrid/launcher/dock_icon.png | Bin 11592 -> 0 bytes
.../resources/org/usergrid/launcher/icon_16.png | Bin 3273 -> 0 bytes
.../org/usergrid/launcher/icon_256.png | Bin 12578 -> 0 bytes
.../resources/org/usergrid/launcher/icon_32.png | Bin 3862 -> 0 bytes
.../resources/org/usergrid/launcher/icon_64.png | Bin 5079 -> 0 bytes
.../org/usergrid/launcher/log_viewer.png | Bin 6610 -> 0 bytes
.../resources/org/usergrid/launcher/start.png | Bin 9253 -> 0 bytes
.../org/usergrid/launcher/start_active.png | Bin 9334 -> 0 bytes
.../org/usergrid/launcher/status_green.png | Bin 2048 -> 0 bytes
.../org/usergrid/launcher/status_off.png | Bin 1847 -> 0 bytes
.../org/usergrid/launcher/status_red.png | Bin 2047 -> 0 bytes
.../org/usergrid/launcher/status_yellow.png | Bin 2092 -> 0 bytes
.../resources/org/usergrid/launcher/stop.png | Bin 8858 -> 0 bytes
.../org/usergrid/launcher/stop_active.png | Bin 8844 -> 0 bytes
.../org/usergrid/launcher/web_browser.png | Bin 4531 -> 0 bytes
.../resources/usergrid-standalone-context.xml | 2 +-
.../0.0.3/usergrid-java-client-0.0.3.jar | Bin 0 -> 45750 bytes
.../usergrid-java-client-0.0.3.jar.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.jar.sha1 | 1 +
.../0.0.3/usergrid-java-client-0.0.3.pom | 87 +
.../usergrid-java-client-0.0.3.pom.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.pom.sha1 | 1 +
.../maven-metadata-local.xml | 13 +
stack/mongo-emulator/README.txt | 2 +-
stack/mongo-emulator/pom.xml | 14 +-
.../usergrid/mongo/MongoChannelHandler.java | 144 +
.../usergrid/mongo/MongoMessageDecoder.java | 115 +
.../usergrid/mongo/MongoMessageEncoder.java | 46 +
.../org/apache/usergrid/mongo/MongoQuery.java | 30 +
.../org/apache/usergrid/mongo/MongoServer.java | 171 +
.../mongo/MongoServerPipelineFactory.java | 55 +
.../usergrid/mongo/commands/Buildinfo.java | 43 +
.../usergrid/mongo/commands/Collstats.java | 58 +
.../apache/usergrid/mongo/commands/Count.java | 65 +
.../apache/usergrid/mongo/commands/Dbstats.java | 40 +
.../usergrid/mongo/commands/Getlasterror.java | 48 +
.../usergrid/mongo/commands/ListDatabases.java | 51 +
.../usergrid/mongo/commands/MongoCommand.java | 81 +
.../mongo/commands/ReplSetGetStatus.java | 37 +
.../usergrid/mongo/commands/ServerStatus.java | 62 +
.../usergrid/mongo/commands/Whatsmyuri.java | 41 +
.../apache/usergrid/mongo/protocol/Message.java | 191 +
.../apache/usergrid/mongo/protocol/OpCrud.java | 46 +
.../usergrid/mongo/protocol/OpDelete.java | 196 +
.../usergrid/mongo/protocol/OpGetMore.java | 112 +
.../usergrid/mongo/protocol/OpInsert.java | 180 +
.../usergrid/mongo/protocol/OpKillCursors.java | 115 +
.../apache/usergrid/mongo/protocol/OpMsg.java | 77 +
.../apache/usergrid/mongo/protocol/OpQuery.java | 447 +
.../apache/usergrid/mongo/protocol/OpReply.java | 189 +
.../usergrid/mongo/protocol/OpUpdate.java | 206 +
.../usergrid/mongo/query/MongoQueryParser.java | 291 +
.../mongo/testproxy/MongoMessageFrame.java | 55 +
.../testproxy/MongoProxyInboundHandler.java | 197 +
.../testproxy/MongoProxyPipelineFactory.java | 53 +
.../mongo/testproxy/MongoProxyServer.java | 55 +
.../testproxy/MongoProxyServerHandler.java | 58 +
.../apache/usergrid/mongo/utils/BSONUtils.java | 50 +
.../org/usergrid/mongo/MongoChannelHandler.java | 144 -
.../org/usergrid/mongo/MongoMessageDecoder.java | 115 -
.../org/usergrid/mongo/MongoMessageEncoder.java | 46 -
.../java/org/usergrid/mongo/MongoQuery.java | 30 -
.../java/org/usergrid/mongo/MongoServer.java | 171 -
.../mongo/MongoServerPipelineFactory.java | 55 -
.../org/usergrid/mongo/commands/Buildinfo.java | 43 -
.../org/usergrid/mongo/commands/Collstats.java | 58 -
.../java/org/usergrid/mongo/commands/Count.java | 65 -
.../org/usergrid/mongo/commands/Dbstats.java | 40 -
.../usergrid/mongo/commands/Getlasterror.java | 48 -
.../usergrid/mongo/commands/ListDatabases.java | 51 -
.../usergrid/mongo/commands/MongoCommand.java | 81 -
.../mongo/commands/ReplSetGetStatus.java | 37 -
.../usergrid/mongo/commands/ServerStatus.java | 63 -
.../org/usergrid/mongo/commands/Whatsmyuri.java | 41 -
.../org/usergrid/mongo/protocol/Message.java | 191 -
.../org/usergrid/mongo/protocol/OpCrud.java | 46 -
.../org/usergrid/mongo/protocol/OpDelete.java | 196 -
.../org/usergrid/mongo/protocol/OpGetMore.java | 112 -
.../org/usergrid/mongo/protocol/OpInsert.java | 180 -
.../usergrid/mongo/protocol/OpKillCursors.java | 115 -
.../java/org/usergrid/mongo/protocol/OpMsg.java | 77 -
.../org/usergrid/mongo/protocol/OpQuery.java | 447 -
.../org/usergrid/mongo/protocol/OpReply.java | 189 -
.../org/usergrid/mongo/protocol/OpUpdate.java | 206 -
.../usergrid/mongo/query/MongoQueryParser.java | 291 -
.../mongo/testproxy/MongoMessageFrame.java | 55 -
.../testproxy/MongoProxyInboundHandler.java | 197 -
.../testproxy/MongoProxyPipelineFactory.java | 53 -
.../mongo/testproxy/MongoProxyServer.java | 55 -
.../testproxy/MongoProxyServerHandler.java | 58 -
.../org/usergrid/mongo/utils/BSONUtils.java | 50 -
.../usergrid/mongo/AbstractMongoTest.java | 62 +
.../apache/usergrid/mongo/BasicMongoTest.java | 340 +
.../usergrid/mongo/DatabaseInitializer.java | 145 +
.../apache/usergrid/mongo/MongoQueryTest.java | 503 +
.../org/usergrid/mongo/AbstractMongoTest.java | 61 -
.../java/org/usergrid/mongo/BasicMongoTest.java | 340 -
.../org/usergrid/mongo/DatabaseInitializer.java | 145 -
.../java/org/usergrid/mongo/MongoQueryTest.java | 503 -
.../test/resources/usergrid-test-context.xml | 4 +-
stack/pom.xml | 41 +-
stack/query-validator/pom.xml | 45 +-
.../query/validator/ApiServerRunner.java | 59 +-
.../usergrid/query/validator/QueryEntity.java | 6 +-
.../usergrid/query/validator/QueryRequest.java | 4 +-
.../usergrid/query/validator/QueryResponse.java | 6 +-
.../usergrid/query/validator/QueryRunner.java | 4 +-
.../validator/QueryValidationConfiguration.java | 8 +-
.../query/validator/QueryValidator.java | 6 +-
.../usergrid/query/validator/SqliteRunner.java | 13 +-
.../usergrid-query-validator-context.xml | 6 +-
.../query/validator/QueryValidationTest.java | 339 +
.../query/validator/QueryValidatorRunner.java | 209 +
.../src/test/resources/log4j.properties | 18 +-
.../test/resources/usergrid-test-context.xml | 6 +-
stack/rest/pom.xml | 20 +-
.../usergrid/rest/AbstractContextResource.java | 164 +
.../org/apache/usergrid/rest/ApiResponse.java | 636 +
.../rest/JacksonCustomMapperProvider.java | 65 +
.../org/apache/usergrid/rest/RootResource.java | 397 +
.../rest/ServerEnvironmentProperties.java | 47 +
.../apache/usergrid/rest/SwaggerServlet.java | 171 +
.../apache/usergrid/rest/SystemResource.java | 110 +
.../usergrid/rest/TextToJsonSwapWriter.java | 119 +
.../rest/applications/ApplicationResource.java | 610 +
.../rest/applications/AuthResource.java | 251 +
.../rest/applications/ServiceResource.java | 662 +
.../applications/assets/AssetsResource.java | 190 +
.../applications/events/EventsResource.java | 69 +
.../rest/applications/queues/QueueResource.java | 204 +
.../queues/QueueSubscriberResource.java | 158 +
.../queues/QueueSubscriptionResource.java | 160 +
.../queues/QueueTransactionsResource.java | 99 +
.../users/AbstractUserExtensionResource.java | 47 +
.../rest/applications/users/UserResource.java | 580 +
.../rest/applications/users/UsersResource.java | 264 +
.../exceptions/AbstractExceptionMapper.java | 106 +
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 +
.../AuthorizationExceptionMapper.java | 36 +
...cateUniquePropertyExistsExceptionMapper.java | 35 +
.../EntityNotFoundExceptionMapper.java | 34 +
...orbiddenServiceOperationExceptionMapper.java | 35 +
.../IllegalArgumentExceptionMapper.java | 32 +
.../exceptions/JsonReadExceptionMapper.java | 35 +
.../exceptions/JsonWriteExceptionMapper.java | 35 +
.../exceptions/ManagementExceptionMapper.java | 38 +
.../usergrid/rest/exceptions/NoOpException.java | 50 +
.../rest/exceptions/NoOpExceptionMapper.java | 32 +
.../NotImplementedExceptionMapper.java | 32 +
.../exceptions/OAuthProblemExceptionMapper.java | 51 +
...rganizationApplicationNotFoundException.java | 39 +
...ationApplicationNotFoundExceptionMapper.java | 16 +
.../exceptions/PersistenceExceptionMapper.java | 27 +
.../exceptions/QueryParseExceptionMapper.java | 34 +
.../exceptions/QueryTokenExceptionMapper.java | 36 +
.../RecentlyUsedPasswordExceptionMapper.java | 21 +
.../rest/exceptions/RedirectionException.java | 27 +
.../exceptions/RedirectionExceptionMapper.java | 30 +
...RequiredPropertyNotFoundExceptionMapper.java | 35 +
.../rest/exceptions/SecurityException.java | 88 +
.../exceptions/SecurityExceptionMapper.java | 45 +
.../rest/exceptions/ServiceExceptionMapper.java | 28 +
.../ServiceResourceNotFoundExceptionMapper.java | 41 +
.../rest/exceptions/ThrowableMapper.java | 26 +
.../TransactionNotFoundExceptionMapper.java | 34 +
.../rest/filters/ContentTypeFilter.java | 323 +
.../rest/filters/JSONPCallbackFilter.java | 66 +
.../usergrid/rest/filters/MeteringFilter.java | 343 +
.../usergrid/rest/filters/TracingFilter.java | 74 +
.../rest/management/ManagementResource.java | 478 +
.../management/metrics/MetricsResource.java | 39 +
.../organizations/OrganizationResource.java | 254 +
.../organizations/OrganizationsResource.java | 192 +
.../applications/ApplicationResource.java | 195 +
.../applications/ApplicationsResource.java | 158 +
.../organizations/users/UsersResource.java | 341 +
.../rest/management/users/UserResource.java | 423 +
.../rest/management/users/UsersResource.java | 211 +
.../organizations/OrganizationsResource.java | 206 +
.../organizations/OrganizationResource.java | 159 +
.../rest/security/CrossOriginRequestFilter.java | 38 +
.../security/SecuredResourceFilterFactory.java | 325 +
.../annotations/RequireAdminUserAccess.java | 31 +
.../annotations/RequireApplicationAccess.java | 34 +
.../annotations/RequireOrganizationAccess.java | 34 +
.../annotations/RequireSystemAccess.java | 31 +
.../security/shiro/RestSecurityManager.java | 60 +
.../ShiroAuthenticationExceptionMapper.java | 59 +
.../shiro/filters/BasicAuthSecurityFilter.java | 111 +
.../ClientCredentialsSecurityFilter.java | 69 +
.../OAuth2AccessTokenSecurityFilter.java | 211 +
.../security/shiro/filters/SecurityFilter.java | 136 +
.../session/HttpRequestSessionManager.java | 87 +
.../session/HttpServletRequestSession.java | 132 +
.../usergrid/rest/test/PropertiesResource.java | 87 +
.../apache/usergrid/rest/utils/CORSUtils.java | 173 +
.../apache/usergrid/rest/utils/JSONPUtils.java | 103 +
.../usergrid/rest/utils/PathingUtils.java | 35 +
.../usergrid/rest/AbstractContextResource.java | 164 -
.../java/org/usergrid/rest/ApiResponse.java | 636 -
.../rest/JacksonCustomMapperProvider.java | 65 -
.../java/org/usergrid/rest/RootResource.java | 397 -
.../rest/ServerEnvironmentProperties.java | 47 -
.../java/org/usergrid/rest/SwaggerServlet.java | 171 -
.../java/org/usergrid/rest/SystemResource.java | 110 -
.../org/usergrid/rest/TextToJsonSwapWriter.java | 119 -
.../rest/applications/ApplicationResource.java | 610 -
.../rest/applications/AuthResource.java | 251 -
.../rest/applications/ServiceResource.java | 662 -
.../applications/assets/AssetsResource.java | 190 -
.../applications/events/EventsResource.java | 69 -
.../rest/applications/queues/QueueResource.java | 204 -
.../queues/QueueSubscriberResource.java | 158 -
.../queues/QueueSubscriptionResource.java | 160 -
.../queues/QueueTransactionsResource.java | 99 -
.../users/AbstractUserExtensionResource.java | 47 -
.../rest/applications/users/UserResource.java | 580 -
.../rest/applications/users/UsersResource.java | 264 -
.../exceptions/AbstractExceptionMapper.java | 106 -
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 -
.../AuthorizationExceptionMapper.java | 36 -
...cateUniquePropertyExistsExceptionMapper.java | 35 -
.../EntityNotFoundExceptionMapper.java | 34 -
...orbiddenServiceOperationExceptionMapper.java | 35 -
.../IllegalArgumentExceptionMapper.java | 32 -
.../exceptions/JsonReadExceptionMapper.java | 35 -
.../exceptions/JsonWriteExceptionMapper.java | 35 -
.../exceptions/ManagementExceptionMapper.java | 38 -
.../usergrid/rest/exceptions/NoOpException.java | 50 -
.../rest/exceptions/NoOpExceptionMapper.java | 32 -
.../NotImplementedExceptionMapper.java | 32 -
.../exceptions/OAuthProblemExceptionMapper.java | 51 -
...rganizationApplicationNotFoundException.java | 39 -
...ationApplicationNotFoundExceptionMapper.java | 16 -
.../exceptions/PersistenceExceptionMapper.java | 27 -
.../exceptions/QueryParseExceptionMapper.java | 34 -
.../exceptions/QueryTokenExceptionMapper.java | 36 -
.../RecentlyUsedPasswordExceptionMapper.java | 21 -
.../rest/exceptions/RedirectionException.java | 27 -
.../exceptions/RedirectionExceptionMapper.java | 30 -
...RequiredPropertyNotFoundExceptionMapper.java | 35 -
.../rest/exceptions/SecurityException.java | 88 -
.../exceptions/SecurityExceptionMapper.java | 45 -
.../rest/exceptions/ServiceExceptionMapper.java | 28 -
.../ServiceResourceNotFoundExceptionMapper.java | 41 -
.../rest/exceptions/ThrowableMapper.java | 26 -
.../TransactionNotFoundExceptionMapper.java | 34 -
.../rest/filters/ContentTypeFilter.java | 323 -
.../rest/filters/JSONPCallbackFilter.java | 66 -
.../usergrid/rest/filters/MeteringFilter.java | 343 -
.../usergrid/rest/filters/TracingFilter.java | 74 -
.../rest/management/ManagementResource.java | 478 -
.../management/metrics/MetricsResource.java | 39 -
.../organizations/OrganizationResource.java | 254 -
.../organizations/OrganizationsResource.java | 192 -
.../applications/ApplicationResource.java | 195 -
.../applications/ApplicationsResource.java | 158 -
.../organizations/users/UsersResource.java | 341 -
.../rest/management/users/UserResource.java | 423 -
.../rest/management/users/UsersResource.java | 211 -
.../organizations/OrganizationsResource.java | 206 -
.../organizations/OrganizationResource.java | 159 -
.../rest/security/CrossOriginRequestFilter.java | 38 -
.../security/SecuredResourceFilterFactory.java | 325 -
.../annotations/RequireAdminUserAccess.java | 31 -
.../annotations/RequireApplicationAccess.java | 34 -
.../annotations/RequireOrganizationAccess.java | 34 -
.../annotations/RequireSystemAccess.java | 31 -
.../security/shiro/RestSecurityManager.java | 60 -
.../ShiroAuthenticationExceptionMapper.java | 59 -
.../shiro/filters/BasicAuthSecurityFilter.java | 111 -
.../ClientCredentialsSecurityFilter.java | 69 -
.../OAuth2AccessTokenSecurityFilter.java | 211 -
.../security/shiro/filters/SecurityFilter.java | 136 -
.../session/HttpRequestSessionManager.java | 87 -
.../session/HttpServletRequestSession.java | 132 -
.../usergrid/rest/test/PropertiesResource.java | 87 -
.../java/org/usergrid/rest/utils/CORSUtils.java | 173 -
.../org/usergrid/rest/utils/JSONPUtils.java | 103 -
.../org/usergrid/rest/utils/PathingUtils.java | 35 -
.../main/resources/usergrid-rest-context.xml | 12 +-
.../apache/usergrid/rest/TestResource/error.jsp | 17 +
.../apache/usergrid/rest/TestResource/test.jsp | 13 +
.../ApplicationResource/authorize_form.jsp | 43 +
.../applications/ApplicationResource/error.jsp | 17 +
.../users/UserResource/activate.jsp | 16 +
.../applications/users/UserResource/confirm.jsp | 17 +
.../applications/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../applications/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 37 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../ManagementResource/authorize_form.jsp | 43 +
.../management/ManagementResource/error.jsp | 17 +
.../OrganizationResource/activate.jsp | 16 +
.../OrganizationResource/confirm.jsp | 17 +
.../OrganizationResource/error.jsp | 17 +
.../management/users/UserResource/activate.jsp | 16 +
.../management/users/UserResource/confirm.jsp | 17 +
.../management/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../management/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 34 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../org/usergrid/rest/TestResource/error.jsp | 17 -
.../jsp/org/usergrid/rest/TestResource/test.jsp | 13 -
.../ApplicationResource/authorize_form.jsp | 43 -
.../applications/ApplicationResource/error.jsp | 17 -
.../users/UserResource/activate.jsp | 16 -
.../applications/users/UserResource/confirm.jsp | 17 -
.../applications/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../applications/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 37 -
.../UsersResource/resetpw_email_success.jsp | 19 -
.../ManagementResource/authorize_form.jsp | 43 -
.../management/ManagementResource/error.jsp | 17 -
.../OrganizationResource/activate.jsp | 16 -
.../OrganizationResource/confirm.jsp | 17 -
.../OrganizationResource/error.jsp | 17 -
.../management/users/UserResource/activate.jsp | 16 -
.../management/users/UserResource/confirm.jsp | 17 -
.../management/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../management/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 34 -
.../UsersResource/resetpw_email_success.jsp | 19 -
stack/rest/src/main/webapp/WEB-INF/web.xml | 169 +-
.../apache/usergrid/rest/AbstractRestIT.java | 355 +
.../java/org/apache/usergrid/rest/BasicIT.java | 310 +
.../usergrid/rest/ConcurrentRestITSuite.java | 47 +
.../usergrid/rest/DatabaseInitializer.java | 145 +
.../java/org/apache/usergrid/rest/ITSetup.java | 166 +
.../org/apache/usergrid/rest/RestITSuite.java | 55 +
.../apache/usergrid/rest/TestContextSetup.java | 58 +
.../apache/usergrid/rest/TomcatResource.java | 69 +
.../ApplicationRequestCounterIT.java | 93 +
.../applications/ApplicationResourceIT.java | 531 +
.../rest/applications/DevicesResourceIT.java | 62 +
.../applications/assets/AssetResourceIT.java | 260 +
.../collection/BadGrammarQueryTest.java | 60 +
.../collection/BrowserCompatibilityTest.java | 86 +
.../collection/PagingResourceIT.java | 218 +
.../collection/activities/AndOrQueryTest.java | 176 +
.../collection/activities/OrderByTest.java | 149 +
.../activities/PagingEntitiesTest.java | 119 +
.../collection/activities/PutTest.java | 64 +
.../collection/groups/GeoPagingTest.java | 124 +
.../collection/groups/UpdateGroupIT.java | 108 +
.../applications/events/EventsResourceIT.java | 109 +
.../queues/AbstractQueueResourceIT.java | 468 +
.../queues/QueueResourceLong1IT.java | 130 +
.../queues/QueueResourceLong2IT.java | 82 +
.../queues/QueueResourceLong3IT.java | 184 +
.../queues/QueueResourceShortIT.java | 415 +
.../applications/users/ActivityResourceIT.java | 180 +
.../users/CollectionsResourceIT.java | 199 +
.../users/ConnectionResourceTest.java | 236 +
.../applications/users/GroupResourceIT.java | 270 +
.../applications/users/OwnershipResourceIT.java | 344 +
.../users/PermissionsResourceIT.java | 699 +
.../applications/users/RetrieveUsersTest.java | 66 +
.../rest/applications/users/UserResourceIT.java | 1286 +
.../users/extensions/TestResource.java | 50 +
.../rest/applications/utils/TestUtils.java | 46 +
.../rest/applications/utils/UserRepo.java | 65 +
.../rest/filters/ContentTypeResourceIT.java | 310 +
.../rest/management/ManagementResourceIT.java | 531 +
.../rest/management/RegistrationIT.java | 351 +
.../organizations/AdminEmailEncodingIT.java | 101 +
.../organizations/OrganizationResourceIT.java | 71 +
.../organizations/OrganizationsResourceIT.java | 257 +
.../rest/management/users/MUUserResourceIT.java | 602 +
.../UsersOrganizationsResourceIT.java | 56 +
.../rest/test/PropertiesResourceIT.java | 75 +
.../rest/test/resource/CollectionResource.java | 26 +
.../usergrid/rest/test/resource/Connection.java | 51 +
.../rest/test/resource/CustomCollection.java | 31 +
.../rest/test/resource/EntityResource.java | 104 +
.../apache/usergrid/rest/test/resource/Me.java | 35 +
.../rest/test/resource/NamedResource.java | 185 +
.../rest/test/resource/ResultsParser.java | 22 +
.../rest/test/resource/RootResource.java | 64 +
.../rest/test/resource/SetResource.java | 82 +
.../rest/test/resource/TestContext.java | 170 +
.../rest/test/resource/ValueResource.java | 307 +
.../rest/test/resource/app/Application.java | 72 +
.../usergrid/rest/test/resource/app/Device.java | 48 +
.../usergrid/rest/test/resource/app/User.java | 54 +
.../rest/test/resource/app/UsersCollection.java | 62 +
.../resource/app/queue/DevicesCollection.java | 36 +
.../rest/test/resource/app/queue/Queue.java | 183 +
.../resource/app/queue/QueuesCollection.java | 35 +
.../app/queue/SubscribersCollection.java | 59 +
.../test/resource/app/queue/Transaction.java | 76 +
.../app/queue/TransactionsCollection.java | 35 +
.../rest/test/resource/mgmt/Application.java | 48 +
.../resource/mgmt/ApplicationsCollection.java | 51 +
.../rest/test/resource/mgmt/Management.java | 93 +
.../rest/test/resource/mgmt/Organization.java | 59 +
.../resource/mgmt/OrganizationsCollection.java | 54 +
.../rest/test/security/TestAdminUser.java | 53 +
.../rest/test/security/TestAppUser.java | 53 +
.../usergrid/rest/test/security/TestUser.java | 126 +
.../java/org/usergrid/rest/AbstractRestIT.java | 355 -
.../test/java/org/usergrid/rest/BasicIT.java | 310 -
.../usergrid/rest/ConcurrentRestITSuite.java | 47 -
.../org/usergrid/rest/DatabaseInitializer.java | 145 -
.../test/java/org/usergrid/rest/ITSetup.java | 171 -
.../java/org/usergrid/rest/RestITSuite.java | 55 -
.../org/usergrid/rest/TestContextSetup.java | 58 -
.../java/org/usergrid/rest/TomcatResource.java | 69 -
.../ApplicationRequestCounterIT.java | 93 -
.../applications/ApplicationResourceIT.java | 531 -
.../rest/applications/DevicesResourceIT.java | 62 -
.../applications/assets/AssetResourceIT.java | 260 -
.../collection/BadGrammarQueryTest.java | 60 -
.../collection/BrowserCompatibilityTest.java | 86 -
.../collection/PagingResourceIT.java | 218 -
.../collection/activities/AndOrQueryTest.java | 176 -
.../collection/activities/OrderByTest.java | 149 -
.../activities/PagingEntitiesTest.java | 119 -
.../collection/activities/PutTest.java | 64 -
.../collection/groups/GeoPagingTest.java | 124 -
.../collection/groups/UpdateGroupIT.java | 108 -
.../applications/events/EventsResourceIT.java | 109 -
.../queues/AbstractQueueResourceIT.java | 468 -
.../queues/QueueResourceLong1IT.java | 130 -
.../queues/QueueResourceLong2IT.java | 82 -
.../queues/QueueResourceLong3IT.java | 184 -
.../queues/QueueResourceShortIT.java | 415 -
.../applications/users/ActivityResourceIT.java | 180 -
.../users/CollectionsResourceIT.java | 199 -
.../users/ConnectionResourceTest.java | 236 -
.../applications/users/GroupResourceIT.java | 270 -
.../applications/users/OwnershipResourceIT.java | 344 -
.../users/PermissionsResourceIT.java | 699 -
.../applications/users/RetrieveUsersTest.java | 66 -
.../rest/applications/users/UserResourceIT.java | 1286 -
.../users/extensions/TestResource.java | 50 -
.../rest/applications/utils/TestUtils.java | 46 -
.../rest/applications/utils/UserRepo.java | 65 -
.../rest/filters/ContentTypeResourceIT.java | 310 -
.../rest/management/ManagementResourceIT.java | 531 -
.../rest/management/RegistrationIT.java | 351 -
.../organizations/AdminEmailEncodingIT.java | 101 -
.../organizations/OrganizationResourceIT.java | 70 -
.../organizations/OrganizationsResourceIT.java | 256 -
.../rest/management/users/MUUserResourceIT.java | 602 -
.../UsersOrganizationsResourceIT.java | 56 -
.../rest/test/PropertiesResourceIT.java | 75 -
.../rest/test/resource/CollectionResource.java | 26 -
.../usergrid/rest/test/resource/Connection.java | 51 -
.../rest/test/resource/CustomCollection.java | 31 -
.../rest/test/resource/EntityResource.java | 104 -
.../org/usergrid/rest/test/resource/Me.java | 35 -
.../rest/test/resource/NamedResource.java | 185 -
.../rest/test/resource/ResultsParser.java | 22 -
.../rest/test/resource/RootResource.java | 64 -
.../rest/test/resource/SetResource.java | 82 -
.../rest/test/resource/TestContext.java | 170 -
.../rest/test/resource/ValueResource.java | 307 -
.../rest/test/resource/app/Application.java | 72 -
.../usergrid/rest/test/resource/app/Device.java | 48 -
.../usergrid/rest/test/resource/app/User.java | 54 -
.../rest/test/resource/app/UsersCollection.java | 62 -
.../resource/app/queue/DevicesCollection.java | 36 -
.../rest/test/resource/app/queue/Queue.java | 183 -
.../resource/app/queue/QueuesCollection.java | 35 -
.../app/queue/SubscribersCollection.java | 59 -
.../test/resource/app/queue/Transaction.java | 76 -
.../app/queue/TransactionsCollection.java | 35 -
.../rest/test/resource/mgmt/Application.java | 48 -
.../resource/mgmt/ApplicationsCollection.java | 51 -
.../rest/test/resource/mgmt/Management.java | 93 -
.../rest/test/resource/mgmt/Organization.java | 59 -
.../resource/mgmt/OrganizationsCollection.java | 54 -
.../rest/test/security/TestAdminUser.java | 53 -
.../rest/test/security/TestAppUser.java | 53 -
.../usergrid/rest/test/security/TestUser.java | 126 -
stack/rest/src/test/resources/log4j.properties | 16 +-
.../test/resources/usergrid-test-context.xml | 12 +-
stack/services/groupstest.out | 64570 -----------------
stack/services/pom.xml | 14 +-
.../management/AccountCreationProps.java | 128 +
.../usergrid/management/ActivationState.java | 8 +
.../usergrid/management/ApplicationCreator.java | 14 +
.../usergrid/management/ApplicationInfo.java | 134 +
.../usergrid/management/ManagementService.java | 319 +
.../usergrid/management/OrganizationInfo.java | 185 +
.../management/OrganizationOwnerInfo.java | 53 +
.../management/OrganizationProfile.java | 87 +
.../apache/usergrid/management/UserInfo.java | 149 +
.../cassandra/AccountCreationPropsImpl.java | 157 +
.../cassandra/ApplicationCreatorImpl.java | 77 +
.../cassandra/ManagementServiceImpl.java | 2923 +
.../ApplicationCreationException.java | 26 +
.../exceptions/DisabledAdminUserException.java | 42 +
.../exceptions/DisabledAppUserException.java | 42 +
.../exceptions/IncorrectPasswordException.java | 42 +
.../exceptions/ManagementException.java | 42 +
.../RecentlyUsedPasswordException.java | 27 +
.../UnableToLeaveOrganizationException.java | 42 +
.../UnactivatedAdminUserException.java | 42 +
.../exceptions/UnactivatedAppUserException.java | 42 +
.../UnactivatedOrganizationException.java | 42 +
.../UnconfirmedAdminUserException.java | 42 +
.../usergrid/management/utils/AccountUtils.java | 41 +
.../usergrid/security/AuthPrincipalInfo.java | 71 +
.../usergrid/security/AuthPrincipalType.java | 115 +
.../security/crypto/EncryptionService.java | 70 +
.../security/crypto/EncryptionServiceImpl.java | 208 +
.../security/crypto/command/BcryptCommand.java | 92 +
.../crypto/command/EncryptionCommand.java | 49 +
.../security/crypto/command/Md5HashCommand.java | 61 +
.../crypto/command/PlainTextCommand.java | 64 +
.../crypto/command/SaltedHasherCommand.java | 67 +
.../crypto/command/Sha1HashCommand.java | 73 +
.../usergrid/security/oauth/AccessInfo.java | 187 +
.../security/oauth/ClientCredentialsInfo.java | 93 +
.../usergrid/security/oauth/OAuthProxy.java | 43 +
.../security/oauth/OAuthProxyFactory.java | 31 +
.../security/providers/AbstractProvider.java | 61 +
.../security/providers/FacebookProvider.java | 183 +
.../security/providers/FoursquareProvider.java | 159 +
.../providers/PingIdentityProvider.java | 143 +
.../security/providers/SignInAsProvider.java | 19 +
.../providers/SignInProviderFactory.java | 51 +
.../security/salt/NoOpSaltProvider.java | 36 +
.../security/salt/PropertiesSaltProvider.java | 53 +
.../usergrid/security/salt/SaltProvider.java | 31 +
.../security/shiro/CustomPermission.java | 225 +
.../shiro/CustomPermissionResolver.java | 29 +
.../shiro/PrincipalCredentialsToken.java | 139 +
.../apache/usergrid/security/shiro/Realm.java | 540 +
.../AbstractAccessTokenCredentials.java | 33 +
.../credentials/AbstractClientCredentials.java | 28 +
.../AbstractPasswordCredentials.java | 33 +
.../credentials/AccessTokenCredentials.java | 22 +
.../shiro/credentials/AdminUserAccessToken.java | 24 +
.../shiro/credentials/AdminUserCredentials.java | 21 +
.../shiro/credentials/AdminUserPassword.java | 24 +
.../credentials/ApplicationAccessToken.java | 24 +
.../ApplicationClientCredentials.java | 24 +
.../credentials/ApplicationCredentials.java | 21 +
.../shiro/credentials/ApplicationGuest.java | 24 +
.../credentials/ApplicationUserAccessToken.java | 24 +
.../credentials/ApplicationUserCredentials.java | 21 +
.../credentials/ApplicationUserPassword.java | 24 +
.../shiro/credentials/ClientCredentials.java | 24 +
.../credentials/OrganizationAccessToken.java | 24 +
.../OrganizationClientCredentials.java | 24 +
.../credentials/OrganizationCredentials.java | 21 +
.../shiro/credentials/PasswordCredentials.java | 22 +
.../shiro/credentials/PrincipalCredentials.java | 21 +
.../shiro/principals/AdminUserPrincipal.java | 29 +
.../principals/ApplicationGuestPrincipal.java | 48 +
.../shiro/principals/ApplicationPrincipal.java | 48 +
.../principals/ApplicationUserPrincipal.java | 35 +
.../shiro/principals/OrganizationPrincipal.java | 48 +
.../shiro/principals/PrincipalIdentifier.java | 51 +
.../shiro/principals/UserPrincipal.java | 69 +
.../security/shiro/utils/SubjectUtils.java | 449 +
.../usergrid/security/tokens/TokenCategory.java | 83 +
.../usergrid/security/tokens/TokenInfo.java | 125 +
.../usergrid/security/tokens/TokenService.java | 39 +
.../tokens/cassandra/TokenServiceImpl.java | 627 +
.../tokens/exceptions/BadTokenException.java | 32 +
.../exceptions/ExpiredTokenException.java | 32 +
.../exceptions/InvalidTokenException.java | 32 +
.../tokens/exceptions/TokenException.java | 35 +
.../services/AbstractCollectionService.java | 571 +
.../services/AbstractConnectionsService.java | 520 +
.../AbstractPathBasedColllectionService.java | 148 +
.../usergrid/services/AbstractService.java | 1306 +
.../org/apache/usergrid/services/Service.java | 49 +
.../apache/usergrid/services/ServiceAction.java | 21 +
.../ServiceCollectionEventListener.java | 22 +
.../usergrid/services/ServiceContext.java | 448 +
.../services/ServiceExecutionEvent.java | 79 +
.../services/ServiceExecutionEventListener.java | 22 +
.../apache/usergrid/services/ServiceInfo.java | 438 +
.../usergrid/services/ServiceManager.java | 431 +
.../services/ServiceManagerFactory.java | 131 +
.../usergrid/services/ServiceParameter.java | 452 +
.../usergrid/services/ServicePayload.java | 199 +
.../usergrid/services/ServiceRequest.java | 372 +
.../usergrid/services/ServiceResults.java | 304 +
.../apache/usergrid/services/ServiceUtils.java | 21 +
.../services/activities/ActivitiesService.java | 33 +
.../applications/ApplicationsService.java | 215 +
.../usergrid/services/assets/AssetsService.java | 57 +
.../services/assets/data/AssetMimeHandler.java | 90 +
.../services/assets/data/AssetUtils.java | 107 +
.../services/assets/data/BinaryStore.java | 27 +
.../assets/data/LocalFileBinaryStore.java | 85 +
.../services/assets/data/S3BinaryStore.java | 202 +
.../services/devices/DevicesService.java | 51 +
.../services/devices/users/UsersService.java | 32 +
.../ForbiddenServiceOperationException.java | 41 +
.../services/exceptions/ServiceException.java | 45 +
.../exceptions/ServiceInvocationException.java | 83 +
.../ServiceResourceNotFoundException.java | 39 +
.../UndefinedServiceEntityTypeException.java | 45 +
.../UnsupportedServiceOperationException.java | 39 +
.../generic/GenericCollectionService.java | 27 +
.../generic/GenericConnectionsService.java | 27 +
.../services/generic/RootCollectionService.java | 27 +
.../usergrid/services/groups/GroupsService.java | 224 +
.../groups/activities/ActivitiesService.java | 74 +
.../services/groups/roles/RolesService.java | 32 +
.../services/groups/users/UsersService.java | 32 +
.../users/activities/ActivitiesService.java | 84 +
.../groups/users/devices/DevicesService.java | 32 +
.../services/messages/MessagesService.java | 33 +
.../usergrid/services/roles/RolesService.java | 236 +
.../services/roles/groups/GroupsService.java | 32 +
.../services/roles/users/UsersService.java | 84 +
.../usergrid/services/users/UsersService.java | 287 +
.../users/activities/ActivitiesService.java | 142 +
.../services/users/devices/DevicesService.java | 32 +
.../users/following/FollowingService.java | 47 +
.../services/users/groups/GroupsService.java | 32 +
.../services/users/roles/RolesService.java | 84 +
.../org/apache/usergrid/utils/PythonUtils.java | 102 +
.../management/AccountCreationProps.java | 119 -
.../usergrid/management/ActivationState.java | 8 -
.../usergrid/management/ApplicationCreator.java | 14 -
.../usergrid/management/ApplicationInfo.java | 134 -
.../usergrid/management/ManagementService.java | 319 -
.../usergrid/management/OrganizationInfo.java | 185 -
.../management/OrganizationOwnerInfo.java | 53 -
.../management/OrganizationProfile.java | 87 -
.../java/org/usergrid/management/UserInfo.java | 149 -
.../cassandra/AccountCreationPropsImpl.java | 112 -
.../cassandra/ApplicationCreatorImpl.java | 77 -
.../cassandra/ManagementServiceImpl.java | 2923 -
.../ApplicationCreationException.java | 26 -
.../exceptions/DisabledAdminUserException.java | 42 -
.../exceptions/DisabledAppUserException.java | 42 -
.../exceptions/IncorrectPasswordException.java | 42 -
.../exceptions/ManagementException.java | 42 -
.../RecentlyUsedPasswordException.java | 27 -
.../UnableToLeaveOrganizationException.java | 42 -
.../UnactivatedAdminUserException.java | 42 -
.../exceptions/UnactivatedAppUserException.java | 42 -
.../UnactivatedOrganizationException.java | 42 -
.../UnconfirmedAdminUserException.java | 42 -
.../usergrid/management/utils/AccountUtils.java | 42 -
.../usergrid/security/AuthPrincipalInfo.java | 71 -
.../usergrid/security/AuthPrincipalType.java | 115 -
.../security/crypto/EncryptionService.java | 70 -
.../security/crypto/EncryptionServiceImpl.java | 208 -
.../security/crypto/command/BcryptCommand.java | 92 -
.../crypto/command/EncryptionCommand.java | 49 -
.../security/crypto/command/Md5HashCommand.java | 61 -
.../crypto/command/PlainTextCommand.java | 64 -
.../crypto/command/SaltedHasherCommand.java | 67 -
.../crypto/command/Sha1HashCommand.java | 73 -
.../org/usergrid/security/oauth/AccessInfo.java | 187 -
.../security/oauth/ClientCredentialsInfo.java | 93 -
.../org/usergrid/security/oauth/OAuthProxy.java | 43 -
.../security/oauth/OAuthProxyFactory.java | 31 -
.../security/providers/AbstractProvider.java | 61 -
.../security/providers/FacebookProvider.java | 183 -
.../security/providers/FoursquareProvider.java | 159 -
.../providers/PingIdentityProvider.java | 143 -
.../security/providers/SignInAsProvider.java | 19 -
.../providers/SignInProviderFactory.java | 51 -
.../security/salt/NoOpSaltProvider.java | 36 -
.../security/salt/PropertiesSaltProvider.java | 53 -
.../usergrid/security/salt/SaltProvider.java | 31 -
.../security/shiro/CustomPermission.java | 225 -
.../shiro/CustomPermissionResolver.java | 29 -
.../shiro/PrincipalCredentialsToken.java | 139 -
.../java/org/usergrid/security/shiro/Realm.java | 540 -
.../AbstractAccessTokenCredentials.java | 33 -
.../credentials/AbstractClientCredentials.java | 28 -
.../AbstractPasswordCredentials.java | 33 -
.../credentials/AccessTokenCredentials.java | 22 -
.../shiro/credentials/AdminUserAccessToken.java | 24 -
.../shiro/credentials/AdminUserCredentials.java | 21 -
.../shiro/credentials/AdminUserPassword.java | 24 -
.../credentials/ApplicationAccessToken.java | 24 -
.../ApplicationClientCredentials.java | 24 -
.../credentials/ApplicationCredentials.java | 21 -
.../shiro/credentials/ApplicationGuest.java | 24 -
.../credentials/ApplicationUserAccessToken.java | 24 -
.../credentials/ApplicationUserCredentials.java | 21 -
.../credentials/ApplicationUserPassword.java | 24 -
.../shiro/credentials/ClientCredentials.java | 24 -
.../credentials/OrganizationAccessToken.java | 24 -
.../OrganizationClientCredentials.java | 24 -
.../credentials/OrganizationCredentials.java | 21 -
.../shiro/credentials/PasswordCredentials.java | 22 -
.../shiro/credentials/PrincipalCredentials.java | 21 -
.../shiro/principals/AdminUserPrincipal.java | 29 -
.../principals/ApplicationGuestPrincipal.java | 48 -
.../shiro/principals/ApplicationPrincipal.java | 48 -
.../principals/ApplicationUserPrincipal.java | 35 -
.../shiro/principals/OrganizationPrincipal.java | 48 -
.../shiro/principals/PrincipalIdentifier.java | 51 -
.../shiro/principals/UserPrincipal.java | 69 -
.../security/shiro/utils/SubjectUtils.java | 449 -
.../usergrid/security/tokens/TokenCategory.java | 83 -
.../org/usergrid/security/tokens/TokenInfo.java | 125 -
.../usergrid/security/tokens/TokenService.java | 39 -
.../tokens/cassandra/TokenServiceImpl.java | 627 -
.../tokens/exceptions/BadTokenException.java | 32 -
.../exceptions/ExpiredTokenException.java | 32 -
.../exceptions/InvalidTokenException.java | 32 -
.../tokens/exceptions/TokenException.java | 35 -
.../services/AbstractCollectionService.java | 571 -
.../services/AbstractConnectionsService.java | 521 -
.../AbstractPathBasedColllectionService.java | 149 -
.../org/usergrid/services/AbstractService.java | 1306 -
.../java/org/usergrid/services/Service.java | 49 -
.../org/usergrid/services/ServiceAction.java | 21 -
.../ServiceCollectionEventListener.java | 22 -
.../org/usergrid/services/ServiceContext.java | 449 -
.../services/ServiceExecutionEvent.java | 79 -
.../services/ServiceExecutionEventListener.java | 22 -
.../java/org/usergrid/services/ServiceInfo.java | 438 -
.../org/usergrid/services/ServiceManager.java | 431 -
.../services/ServiceManagerFactory.java | 131 -
.../org/usergrid/services/ServiceParameter.java | 452 -
.../org/usergrid/services/ServicePayload.java | 199 -
.../org/usergrid/services/ServiceRequest.java | 372 -
.../org/usergrid/services/ServiceResults.java | 304 -
.../org/usergrid/services/ServiceUtils.java | 21 -
.../services/activities/ActivitiesService.java | 33 -
.../applications/ApplicationsService.java | 215 -
.../usergrid/services/assets/AssetsService.java | 57 -
.../services/assets/data/AssetMimeHandler.java | 90 -
.../services/assets/data/AssetUtils.java | 107 -
.../services/assets/data/BinaryStore.java | 27 -
.../assets/data/LocalFileBinaryStore.java | 85 -
.../services/assets/data/S3BinaryStore.java | 202 -
.../services/devices/DevicesService.java | 51 -
.../services/devices/users/UsersService.java | 32 -
.../ForbiddenServiceOperationException.java | 41 -
.../services/exceptions/ServiceException.java | 45 -
.../exceptions/ServiceInvocationException.java | 83 -
.../ServiceResourceNotFoundException.java | 39 -
.../UndefinedServiceEntityTypeException.java | 45 -
.../UnsupportedServiceOperationException.java | 39 -
.../generic/GenericCollectionService.java | 27 -
.../generic/GenericConnectionsService.java | 27 -
.../services/generic/RootCollectionService.java | 27 -
.../usergrid/services/groups/GroupsService.java | 224 -
.../groups/activities/ActivitiesService.java | 74 -
.../services/groups/roles/RolesService.java | 32 -
.../services/groups/users/UsersService.java | 32 -
.../users/activities/ActivitiesService.java | 84 -
.../groups/users/devices/DevicesService.java | 32 -
.../services/messages/MessagesService.java | 33 -
.../usergrid/services/roles/RolesService.java | 236 -
.../services/roles/groups/GroupsService.java | 32 -
.../services/roles/users/UsersService.java | 84 -
.../usergrid/services/users/UsersService.java | 287 -
.../users/activities/ActivitiesService.java | 142 -
.../services/users/devices/DevicesService.java | 32 -
.../users/following/FollowingService.java | 47 -
.../services/users/groups/GroupsService.java | 32 -
.../services/users/roles/RolesService.java | 84 -
.../java/org/usergrid/utils/PythonUtils.java | 102 -
.../pyusergrid/services/pytest/PytestService.py | 4 +-
.../python/pyusergrid/services/pytest/test.py | 2 +-
stack/services/src/main/python/test/test.py | 2 +-
.../resources/usergrid-services-context.xml | 18 +-
.../test/java/baas/io/simple/SimpleService.java | 2 +-
.../usergrid/ConcurrentServiceITSuite.java | 43 +
.../org/apache/usergrid/ServiceApplication.java | 188 +
.../org/apache/usergrid/ServiceITSetup.java | 44 +
.../org/apache/usergrid/ServiceITSetupImpl.java | 129 +
.../org/apache/usergrid/ServiceITSuite.java | 41 +
.../apache/usergrid/management/EmailFlowIT.java | 419 +
.../management/ManagementTestHelper.java | 40 +
.../usergrid/management/MockImapClient.java | 83 +
.../usergrid/management/OrganizationIT.java | 229 +
.../org/apache/usergrid/management/RoleIT.java | 97 +
.../cassandra/ApplicationCreatorIT.java | 66 +
.../cassandra/ManagementServiceIT.java | 729 +
.../cassandra/ManagementTestHelperImpl.java | 85 +
.../org/apache/usergrid/python/JythonTest.java | 38 +
.../usergrid/security/CustomResolverTest.java | 169 +
.../crypto/EncryptionServiceImplTest.java | 170 +
.../crypto/command/BcryptCommandTest.java | 165 +
.../crypto/command/Md5HashCommandTest.java | 71 +
.../crypto/command/Sha1HashCommandTest.java | 67 +
.../security/providers/FacebookProviderIT.java | 81 +
.../providers/PingIdentityProviderIT.java | 63 +
.../security/tokens/TokenServiceIT.java | 440 +
.../usergrid/services/AbstractServiceIT.java | 38 +
.../usergrid/services/ActivitiesServiceIT.java | 111 +
.../services/ApplicationsServiceIT.java | 35 +
.../usergrid/services/CollectionServiceIT.java | 290 +
.../usergrid/services/ConnectionsServiceIT.java | 82 +
.../usergrid/services/GroupServiceIT.java | 80 +
.../usergrid/services/RolesServiceIT.java | 279 +
.../usergrid/services/ServiceFactoryIT.java | 57 +
.../usergrid/services/ServiceInfoTest.java | 108 +
.../usergrid/services/ServiceInvocationIT.java | 145 +
.../usergrid/services/ServiceRequestIT.java | 78 +
.../usergrid/services/UsersServiceIT.java | 52 +
.../services/assets/data/AssetUtilsTest.java | 44 +
.../org/usergrid/ConcurrentServiceITSuite.java | 43 -
.../java/org/usergrid/ServiceApplication.java | 188 -
.../test/java/org/usergrid/ServiceITSetup.java | 44 -
.../java/org/usergrid/ServiceITSetupImpl.java | 129 -
.../test/java/org/usergrid/ServiceITSuite.java | 41 -
.../org/usergrid/management/EmailFlowIT.java | 419 -
.../management/ManagementTestHelper.java | 40 -
.../org/usergrid/management/MockImapClient.java | 83 -
.../org/usergrid/management/OrganizationIT.java | 229 -
.../java/org/usergrid/management/RoleIT.java | 97 -
.../cassandra/ApplicationCreatorIT.java | 66 -
.../cassandra/ManagementServiceIT.java | 729 -
.../cassandra/ManagementTestHelperImpl.java | 85 -
.../java/org/usergrid/python/JythonTest.java | 38 -
.../usergrid/security/CustomResolverTest.java | 169 -
.../crypto/EncryptionServiceImplTest.java | 170 -
.../crypto/command/BcryptCommandTest.java | 165 -
.../crypto/command/Md5HashCommandTest.java | 71 -
.../crypto/command/Sha1HashCommandTest.java | 67 -
.../security/providers/FacebookProviderIT.java | 81 -
.../providers/PingIdentityProviderIT.java | 63 -
.../security/tokens/TokenServiceIT.java | 440 -
.../usergrid/services/AbstractServiceIT.java | 38 -
.../usergrid/services/ActivitiesServiceIT.java | 111 -
.../services/ApplicationsServiceIT.java | 35 -
.../usergrid/services/CollectionServiceIT.java | 290 -
.../usergrid/services/ConnectionsServiceIT.java | 82 -
.../org/usergrid/services/GroupServiceIT.java | 80 -
.../org/usergrid/services/RolesServiceIT.java | 279 -
.../org/usergrid/services/ServiceFactoryIT.java | 57 -
.../org/usergrid/services/ServiceInfoTest.java | 108 -
.../usergrid/services/ServiceInvocationIT.java | 145 -
.../org/usergrid/services/ServiceRequestIT.java | 78 -
.../org/usergrid/services/UsersServiceIT.java | 52 -
.../services/assets/data/AssetUtilsTest.java | 44 -
.../src/test/resources/log4j.properties | 14 +-
.../test/resources/usergrid-test-context.xml | 8 +-
stack/test-utils/pom.xml | 8 +-
.../apache/usergrid/NoExitSecurityManager.java | 64 +
.../usergrid/cassandra/AvailablePortFinder.java | 211 +
.../usergrid/cassandra/CassandraResource.java | 505 +
.../usergrid/cassandra/ClearShiroSubject.java | 31 +
.../apache/usergrid/cassandra/Concurrent.java | 15 +
.../cassandra/ConcurrentJunitRunner.java | 75 +
.../usergrid/cassandra/ConcurrentSuite.java | 101 +
.../apache/usergrid/cassandra/DataControl.java | 17 +
.../apache/usergrid/cassandra/DataLoader.java | 9 +
.../usergrid/cassandra/SchemaManager.java | 18 +
.../org/usergrid/NoExitSecurityManager.java | 64 -
.../usergrid/cassandra/AvailablePortFinder.java | 211 -
.../usergrid/cassandra/CassandraResource.java | 505 -
.../usergrid/cassandra/ClearShiroSubject.java | 31 -
.../java/org/usergrid/cassandra/Concurrent.java | 15 -
.../cassandra/ConcurrentJunitRunner.java | 75 -
.../org/usergrid/cassandra/ConcurrentSuite.java | 101 -
.../org/usergrid/cassandra/DataControl.java | 17 -
.../java/org/usergrid/cassandra/DataLoader.java | 9 -
.../org/usergrid/cassandra/SchemaManager.java | 18 -
.../cassandra/AnotherCassandraResourceIT.java | 68 +
.../cassandra/CassandraResourceITSuite.java | 25 +
.../cassandra/CassandraResourceTest.java | 104 +
.../usergrid/cassandra/FakeSchemaManager.java | 32 +
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 +
.../YetAnotherCassandraResourceIT.java | 70 +
.../cassandra/AnotherCassandraResourceIT.java | 68 -
.../cassandra/CassandraResourceITSuite.java | 25 -
.../cassandra/CassandraResourceTest.java | 104 -
.../usergrid/cassandra/FakeSchemaManager.java | 32 -
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 -
.../YetAnotherCassandraResourceIT.java | 70 -
.../test/resources/usergrid-test-context.xml | 6 +-
stack/tools/README.md | 4 +-
stack/tools/pom.xml | 16 +-
.../java/org/apache/usergrid/tools/ApiDoc.java | 114 +
.../org/apache/usergrid/tools/AppAudit.java | 231 +
.../org/apache/usergrid/tools/AppNameFix.java | 109 +
.../java/org/apache/usergrid/tools/Cli.java | 269 +
.../java/org/apache/usergrid/tools/Command.java | 99 +
.../org/apache/usergrid/tools/CredExport.java | 122 +
.../apache/usergrid/tools/DupAdminRepair.java | 310 +
.../org/apache/usergrid/tools/DupOrgRepair.java | 266 +
.../apache/usergrid/tools/EntityCleanup.java | 176 +
.../usergrid/tools/EntityInsertBenchMark.java | 273 +
.../usergrid/tools/EntityReadBenchMark.java | 360 +
.../org/apache/usergrid/tools/EntityUpdate.java | 191 +
.../java/org/apache/usergrid/tools/Export.java | 431 +
.../usergrid/tools/ExportDataCreator.java | 105 +
.../usergrid/tools/ExportingToolBase.java | 183 +
.../java/org/apache/usergrid/tools/Import.java | 545 +
.../org/apache/usergrid/tools/ImportFB.java | 101 +
.../org/apache/usergrid/tools/IndexRebuild.java | 206 +
.../java/org/apache/usergrid/tools/Metrics.java | 213 +
.../usergrid/tools/OrganizationExport.java | 117 +
.../apache/usergrid/tools/PopulateSample.java | 142 +
.../apache/usergrid/tools/ResetSuperUser.java | 105 +
.../java/org/apache/usergrid/tools/SetupDB.java | 57 +
.../java/org/apache/usergrid/tools/Test.java | 53 +
.../org/apache/usergrid/tools/ToolBase.java | 246 +
.../usergrid/tools/UniqueIndexCleanup.java | 381 +
.../org/apache/usergrid/tools/UserManager.java | 45 +
.../apache/usergrid/tools/WarehouseExport.java | 516 +
.../apache/usergrid/tools/WarehouseUpsert.java | 153 +
.../usergrid/tools/apidoc/swagger/Api.java | 92 +
.../tools/apidoc/swagger/ApiListing.java | 145 +
.../tools/apidoc/swagger/ApiOperation.java | 247 +
.../tools/apidoc/swagger/ApiOperationError.java | 60 +
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 +
.../apidoc/swagger/ApiParamAllowableValues.java | 62 +
.../apache/usergrid/tools/bean/AppScore.java | 82 +
.../apache/usergrid/tools/bean/ExportOrg.java | 69 +
.../apache/usergrid/tools/bean/MetricLine.java | 82 +
.../apache/usergrid/tools/bean/MetricQuery.java | 93 +
.../apache/usergrid/tools/bean/MetricSort.java | 26 +
.../apache/usergrid/tools/bean/OrgScore.java | 93 +
.../main/java/org/usergrid/tools/ApiDoc.java | 114 -
.../main/java/org/usergrid/tools/AppAudit.java | 231 -
.../java/org/usergrid/tools/AppNameFix.java | 109 -
.../src/main/java/org/usergrid/tools/Cli.java | 269 -
.../main/java/org/usergrid/tools/Command.java | 99 -
.../java/org/usergrid/tools/CredExport.java | 122 -
.../java/org/usergrid/tools/DupAdminRepair.java | 310 -
.../java/org/usergrid/tools/DupOrgRepair.java | 266 -
.../java/org/usergrid/tools/EntityCleanup.java | 176 -
.../usergrid/tools/EntityInsertBenchMark.java | 273 -
.../org/usergrid/tools/EntityReadBenchMark.java | 360 -
.../java/org/usergrid/tools/EntityUpdate.java | 191 -
.../main/java/org/usergrid/tools/Export.java | 431 -
.../org/usergrid/tools/ExportDataCreator.java | 105 -
.../org/usergrid/tools/ExportingToolBase.java | 183 -
.../main/java/org/usergrid/tools/Import.java | 545 -
.../main/java/org/usergrid/tools/ImportFB.java | 101 -
.../java/org/usergrid/tools/IndexRebuild.java | 206 -
.../main/java/org/usergrid/tools/Metrics.java | 213 -
.../org/usergrid/tools/OrganizationExport.java | 117 -
.../java/org/usergrid/tools/PopulateSample.java | 142 -
.../java/org/usergrid/tools/ResetSuperUser.java | 105 -
.../main/java/org/usergrid/tools/SetupDB.java | 57 -
.../src/main/java/org/usergrid/tools/Test.java | 53 -
.../main/java/org/usergrid/tools/ToolBase.java | 246 -
.../org/usergrid/tools/UniqueIndexCleanup.java | 381 -
.../java/org/usergrid/tools/UserManager.java | 45 -
.../org/usergrid/tools/WarehouseExport.java | 516 -
.../org/usergrid/tools/WarehouseUpsert.java | 153 -
.../org/usergrid/tools/apidoc/swagger/Api.java | 92 -
.../tools/apidoc/swagger/ApiListing.java | 145 -
.../tools/apidoc/swagger/ApiOperation.java | 247 -
.../tools/apidoc/swagger/ApiOperationError.java | 60 -
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 -
.../apidoc/swagger/ApiParamAllowableValues.java | 62 -
.../java/org/usergrid/tools/bean/AppScore.java | 82 -
.../java/org/usergrid/tools/bean/ExportOrg.java | 69 -
.../org/usergrid/tools/bean/MetricLine.java | 82 -
.../org/usergrid/tools/bean/MetricQuery.java | 93 -
.../org/usergrid/tools/bean/MetricSort.java | 26 -
.../java/org/usergrid/tools/bean/OrgScore.java | 93 -
stack/tools/src/main/resources/log4j.xml | 2 +-
stack/websocket/pom.xml | 12 +-
.../websocket/WebSocketChannelHandler.java | 357 +
.../usergrid/websocket/WebSocketKeyStore.java | 49 +
.../usergrid/websocket/WebSocketServer.java | 195 +
.../websocket/WebSocketServerIndexPage.java | 71 +
.../WebSocketServerPipelineFactory.java | 75 +
.../websocket/WebSocketSslContextFactory.java | 62 +
.../websocket/WebSocketChannelHandler.java | 357 -
.../usergrid/websocket/WebSocketKeyStore.java | 49 -
.../org/usergrid/websocket/WebSocketServer.java | 195 -
.../websocket/WebSocketServerIndexPage.java | 71 -
.../WebSocketServerPipelineFactory.java | 75 -
.../websocket/WebSocketSslContextFactory.java | 62 -
.../usergrid/websocket/ExampleListener.java | 41 +
.../websocket/SimpleMessageProducer.java | 61 +
.../usergrid/websocket/WebSocketServerTest.java | 43 +
.../org/usergrid/websocket/ExampleListener.java | 41 -
.../websocket/SimpleMessageProducer.java | 61 -
.../usergrid/websocket/WebSocketServerTest.java | 42 -
.../test/resources/testApplicationContext.xml | 20 +-
2246 files changed, 167503 insertions(+), 263994 deletions(-)
----------------------------------------------------------------------
[44/50] [abbrv] Fixing merge issues in query validator,
still fighting a compile error in the tests.
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3dc1e9fe/stack/query-validator/src/test/java/org/usergrid/query/validator/users/UserQueryIT.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/usergrid/query/validator/users/UserQueryIT.java b/stack/query-validator/src/test/java/org/usergrid/query/validator/users/UserQueryIT.java
deleted file mode 100644
index fc6fafa..0000000
--- a/stack/query-validator/src/test/java/org/usergrid/query/validator/users/UserQueryIT.java
+++ /dev/null
@@ -1,877 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.usergrid.query.validator.users;
-
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.usergrid.persistence.Entity;
-import org.usergrid.query.validator.AbstractQueryIT;
-import org.usergrid.query.validator.QueryRequest;
-import org.usergrid.query.validator.QueryResponse;
-import org.usergrid.query.validator.QueryResultsMatcher;
-import org.usergrid.utils.StringUtils;
-
-import java.util.List;
-
-/**
- * @author Sungju Jin
- */
-public class UserQueryIT extends AbstractQueryIT {
-
- @BeforeClass
- public static void setDatas() {
- createInitializationDatas("user");
- }
-
- @Test
- public void sexEqualAndNameEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and name = 'judekim' LIMIT 10";
- String api = "SELECT * WHERE sex = 'male' AND name = 'judekim'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameEqualAndSexEqual() {
- String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 10";
- String api = "select * where name = 'judekim' and sex = 'male'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameEqualAndSexEqual_limitL20() {
- String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 20";
- String api = "select * where name = 'judekim' and sex = 'male'";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndNameEqualExtra1() {
- String sqlite = "SELECT * FROM users WHERE sex = 'female' and name = 'curioe' LIMIT 10";
- String api = "select * where sex = 'female' and name = 'curioe'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualOrNameEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'female' or name = 'curioe' LIMIT 10";
- String api = "select * where sex = 'female' or name = 'curioe'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(4);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc_limitL4() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(4);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqual_sortAgeDescExtra1() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String sex = (String)entity.getProperty("sex");
-
- if((StringUtils.equals("male",sex)) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqual_sortAgeDescExtra2() {
- String sqlite = " SELECT * FROM users WHERE sex = 'female' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'female' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal() {
- String sqlite = " SELECT * FROM users WHERE sex = 'male' and age >= 35 LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAgeDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAgeDesc_limitL20() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 20";
- String api = "select * where sex = 'male' and age >= 35 order by age desc";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlSexEqualAndAgeGreaterthanequal_sortNameDesc_limitL20() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 20";
- String api = "select * where sex = 'male' and age >= 35 order by name desc";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- String sex = (String)entity.getProperty("sex");
-
- if(((StringUtils.equals("male",sex) && age >= 35) || StringUtils.equals("female",sex)) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortAgeDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void limitL12() {
- String sqlite = "SELECT * FROM users LIMIT 12";
- String api = null;
- int limit = 12;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc_limitL20() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 20";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void limitL11() {
- String sqlite = "SELECT * FROM users LIMIT 11";
- String api = null;
- int limit = 11;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 10";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_limitL20() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 20";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAddressDesc_limitL100() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY address desc LIMIT 100";
- String api = "select * where sex = 'male' and age >= 35 order by address desc";
- int limit = 100;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlNameEqual() {
- String sqlite = "SELECT * FROM users WHERE name = 'judekim' LIMIT 10";
- String api = "select * where name = 'judekim'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeEqual() {
- String sqlite = "SELECT * FROM users WHERE age = 16 LIMIT 10";
- String api = "select * where age = 16";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlNameEqualAndAgeEqual() {
- String sqlite = "SELECT * FROM users WHERE name = 'askagirl' and age = 16 LIMIT 10";
- String api = "select * where name = 'askagirl' and age = 16";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String name = entity.getName();
- int age = (Integer)entity.getProperty("age");
- if ((StringUtils.equals("askagirl", name) && age == 16) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeLessthan() {
- String sqlite = "SELECT * FROM users WHERE age < 16 LIMIT 10";
- String api = "select * where age < 16";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- if((age < 16) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeLessthanequal() {
- String sqlite = "SELECT * FROM users WHERE age <= 16 LIMIT 20";
- String api = "select * where age <= 16";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- if((age <= 16) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeGreaterthan() {
- String sqlite = "SELECT * FROM users WHERE age > 16 LIMIT 10";
- String api = "select * where age > 16";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- if((age > 16) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeGreaterthanequal() {
- String sqlite = "SELECT * FROM users WHERE age >= 16 LIMIT 10";
- String api = "select * where age >= 16";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- if((age >= 16) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeGreaterthanequalAndAgeLessthan() {
- String sqlite = "SELECT * FROM users WHERE age >= 32 and age < 40 LIMIT 10";
- String api = "select * where age >= 32 and age < 40";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- if((age >= 32 && age < 40) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAgeGreaterthanequalAndAgeLessthanAndSexEqual() {
- String sqlite = "SELECT * FROM users WHERE age >= 32 and age < 40 and sex = 'female' LIMIT 10";
- String api = "select * where age >= 32 and age < 40 and sex = 'female'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- String sex = (String)entity.getProperty("sex");
-
- if((age >= 32 && age < 40 && StringUtils.equals("female",sex)) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAddressFulltext() {
- String sqlite = "SELECT * FROM users WHERE address LIKE '%서울시%' LIMIT 10";
- String api = "select * where address contains '서울시'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String address = (String)entity.getProperty("address");
-
- if((StringUtils.contains(address,"서울시")) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAddressFulltextstartswith() {
- String sqlite = " SELECT * FROM users WHERE address LIKE 'A%' LIMIT 10";
- String api = "select * where address contains 'A*'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String address = (String)entity.getProperty("address");
-
- if((StringUtils.startsWith(address,"A")) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAddressBeginswith() {
- String sqlite = "SELECT * FROM users WHERE address LIKE 'B%' LIMIT 10";
- String api = "select * where address = 'B*'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String address = (String)entity.getProperty("address");
-
- if((StringUtils.startsWith(address,"B")) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAddressBeginswithAndSexFulltextstartswith() {
- String sqlite = "SELECT * FROM users WHERE address LIKE 'C%' and sex LIKE 'ma%' LIMIT 10";
- String api = "select * where address = 'C*' and sex contains 'ma*'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String address = (String)entity.getProperty("address");
-
- if((StringUtils.startsWith(address,"C")) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlAddressBeginswithAndSexFulltext() {
- String sqlite = "SELECT * FROM users WHERE (address LIKE 'D%' and sex LIKE '%male%') LIMIT 10";
- String api = "select * where address = 'D*' and sex contains 'male'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- String address = (String)entity.getProperty("address");
-
- if((StringUtils.startsWith(address,"D")) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlSexEqualOrAgeGreaterthanequalAndAgeLessthan_limitL20() {
- String sqlite = "SELECT * FROM users WHERE sex = 'female' or age >= 12 and age < 20 LIMIT 20";
- String api = "select * where sex = 'female' or age >= 12 and age < 20";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request, new QueryResultsMatcher() {
- @Override
- public boolean equals(List<Entity> expectedEntities, List<Entity> actuallyEntities) {
- boolean equals = expectedEntities.size() == expectedEntities.size();
- if( !equals )
- return false;
-
- for(Entity entity : actuallyEntities) {
- int age = (Integer)entity.getProperty("age");
- String sex = (String)entity.getProperty("sex");
-
- if(((StringUtils.equals("female",sex) || age >= 12) && age < 20) == false) {
- return false;
- }
- }
- return equals;
- }
- });
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortNameAsc() {
- String sqlite = "SELECT * FROM users ORDER BY name asc LIMIT 10";
- String api = "select * order by name asc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortNameDesc() {
- String sqlite = "SELECT * FROM users ORDER BY name desc LIMIT 10";
- String api = "select * order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortNameAscAgeDesc() {
- String sqlite = "SELECT * FROM users ORDER BY name asc, age desc LIMIT 10";
- String api = "select * order by name asc, age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortNameAscAddressAsc() {
- String sqlite = "SELECT * FROM users ORDER BY name asc, address asc LIMIT 10";
- String api = "select * order by name asc, address asc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortCreatedAsc() {
- String sqlite = "SELECT * FROM users ORDER BY created asc LIMIT 10";
- String api = "select * order by created asc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortCreatedDesc() {
- String sqlite = "SELECT * FROM users ORDER BY created desc LIMIT 10";
- String api = "select * order by created desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortModifiedAsc() {
- String sqlite = "SELECT * FROM users ORDER BY modified asc LIMIT 10";
- String api = "select * order by modified asc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortCreatedDescNameAsc() {
- String sqlite = "SELECT * FROM users ORDER BY created desc, name asc LIMIT 10";
- String api = "select * order by created desc, name asc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sortNameAscCreatedDesc() {
- String sqlite = "SELECT * FROM users ORDER BY name asc, created desc LIMIT 10";
- String api = "select * order by name asc, created desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-}
\ No newline at end of file
[09/50] [abbrv] git commit: Update README.md
Posted by sn...@apache.org.
Update README.md
Adding a how to build and run locally section.
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/bc3dfbad
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/bc3dfbad
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/bc3dfbad
Branch: refs/heads/optimistic-tx-semantics
Commit: bc3dfbad34533f2f6d741554d8af15a578f8d243
Parents: 3d3ebf5
Author: Dave Johnson <da...@rollerweblogger.org>
Authored: Mon Feb 10 17:18:37 2014 -0500
Committer: Dave Johnson <da...@rollerweblogger.org>
Committed: Mon Feb 10 17:18:37 2014 -0500
----------------------------------------------------------------------
README.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/bc3dfbad/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index fdb5e4a..faaf832 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,35 @@ This repository contains all the code for Apache Usergrid, including the server
* the admin portal and the many SDKs. A pure HTML5+JavaScript app allowing you to register developers and let them manage their apps in a multi-tenant cluster. Located under [`/portal`](portal)
* SDKs for [iOS](sdks/ios), [Android](sdks/android), [HTML5/JavaScript](sdks/html5-javascript), [node.js](sdks/nodejs), [Ruby on Rails](ruby-on-rails), [pure Ruby](sdks/ruby), [PHP](sdks/php), (server-side) [Java](sdks/java) and [.Net / Windows](sdks/dotnet), located in their respective subdirectories under [`/sdks`](sdks).
+How to build and run Usergrid locally
+-------------------------------------
+
+It's easy to build and run Usergrid locally. All you need is the Java JDK 1.7 and Maven 3.0.5 installed and on your path. Here's how you do it. First you get the source code like this:
+
+ git clone git@github.com:usergrid/usergrid.git
+
+Next, you change directories into the Java SDK package and build the SDK:
+
+ cd usergrid/sdks/java
+ mvn clean install
+
+Next, you change directory into the stack directory and build the Usergrid WAR and launcher:
+
+ cd ../..
+ cd stack
+ mvn clean install
+
+Finally, you can run Usergrid locally by using the all-in-one launcher, which includes a web server (Grizzly) and the database (Cassandra):
+
+ cd launcher
+ java -jar target/usergrid-launcher-0.0.29-SNAPSHOT.jar
+
+(you might have to substitute 0.0.29-SNAPSHOT with something newer)
+
+You should see the Usergrid launcher UI and from there you can start Usergrid and access the admin console.
+
+If not, subscribe to the [user mailing list](mailto:user-subscribe@usergrid.incubator.apache.org) and we can help you out.
+
Backwards compatibility
-----------------------
[50/50] [abbrv] git commit: Merge branch 'two-dot-o' into
optimistic-tx-semantics
Posted by sn...@apache.org.
Merge branch 'two-dot-o' into optimistic-tx-semantics
Conflicts:
stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/guice/CollectionModule.java
stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/1d06007c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/1d06007c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/1d06007c
Branch: refs/heads/optimistic-tx-semantics
Commit: 1d06007c3c95fe9a07ac94cdf3bee7af30bb4872
Parents: c04f49d 2f786eb
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 14:53:29 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 14:53:29 2014 -0500
----------------------------------------------------------------------
.gitignore | 4 +-
README.md | 29 +
sdks/android/doc/allclasses-frame.html | 110 +-
sdks/android/doc/allclasses-noframe.html | 110 +-
sdks/android/doc/constant-values.html | 859 +-
sdks/android/doc/deprecated-list.html | 237 +-
sdks/android/doc/help-doc.html | 419 +-
sdks/android/doc/index-all.html | 371 +
sdks/android/doc/index-files/index-1.html | 209 -
sdks/android/doc/index-files/index-10.html | 151 -
sdks/android/doc/index-files/index-11.html | 154 -
sdks/android/doc/index-files/index-12.html | 151 -
sdks/android/doc/index-files/index-13.html | 217 -
sdks/android/doc/index-files/index-14.html | 268 -
sdks/android/doc/index-files/index-15.html | 204 -
sdks/android/doc/index-files/index-16.html | 151 -
sdks/android/doc/index-files/index-17.html | 466 -
sdks/android/doc/index-files/index-18.html | 184 -
sdks/android/doc/index-files/index-19.html | 157 -
sdks/android/doc/index-files/index-2.html | 193 -
sdks/android/doc/index-files/index-20.html | 239 -
sdks/android/doc/index-files/index-21.html | 154 -
sdks/android/doc/index-files/index-3.html | 161 -
sdks/android/doc/index-files/index-4.html | 166 -
sdks/android/doc/index-files/index-5.html | 151 -
sdks/android/doc/index-files/index-6.html | 547 -
sdks/android/doc/index-files/index-7.html | 145 -
sdks/android/doc/index-files/index-8.html | 160 -
sdks/android/doc/index-files/index-9.html | 145 -
sdks/android/doc/index.html | 89 +-
.../apache/usergrid/android/client/Client.html | 989 +
.../client/callbacks/ApiResponseCallback.html | 224 +
.../client/callbacks/ClientAsyncTask.html | 338 +
.../client/callbacks/ClientCallback.html | 227 +
.../callbacks/DeviceRegistrationCallback.html | 220 +
.../callbacks/GroupsRetrievedCallback.html | 220 +
.../client/callbacks/QueryResultsCallback.html | 220 +
.../class-use/ApiResponseCallback.html | 282 +
.../callbacks/class-use/ClientAsyncTask.html | 117 +
.../callbacks/class-use/ClientCallback.html | 180 +
.../class-use/DeviceRegistrationCallback.html | 171 +
.../class-use/GroupsRetrievedCallback.html | 160 +
.../class-use/QueryResultsCallback.html | 219 +
.../android/client/callbacks/package-frame.html | 28 +
.../client/callbacks/package-summary.html | 166 +
.../android/client/callbacks/package-tree.html | 145 +
.../android/client/callbacks/package-use.html | 178 +
.../android/client/class-use/Client.html | 117 +
.../usergrid/android/client/package-frame.html | 20 +
.../android/client/package-summary.html | 137 +
.../usergrid/android/client/package-tree.html | 134 +
.../usergrid/android/client/package-use.html | 117 +
.../android/client/utils/DeviceUuidFactory.html | 352 +
.../android/client/utils/ObjectUtils.html | 258 +
.../utils/class-use/DeviceUuidFactory.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../android/client/utils/package-frame.html | 21 +
.../android/client/utils/package-summary.html | 142 +
.../android/client/utils/package-tree.html | 131 +
.../android/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/android/doc/overview-frame.html | 71 +-
sdks/android/doc/overview-summary.html | 280 +-
sdks/android/doc/overview-tree.html | 301 +-
sdks/android/doc/package-list | 8 +-
sdks/android/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/android/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/android/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/android/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/android/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/android/doc/stylesheet.css | 501 +-
.../0.0.6/usergrid-java-client-0.0.6.jar | Bin 0 -> 46389 bytes
.../0.0.6/usergrid-java-client-0.0.6.jar.sha1 | 1 +
.../0.0.6/usergrid-java-client-0.0.6.pom | 95 +
.../0.0.6/usergrid-java-client-0.0.6.pom.sha1 | 1 +
.../maven-metadata-local.xml | 12 +
sdks/android/pom.xml | 31 +-
.../apache/usergrid/android/client/Client.java | 590 +
.../client/callbacks/ApiResponseCallback.java | 10 +
.../client/callbacks/ClientAsyncTask.java | 38 +
.../client/callbacks/ClientCallback.java | 9 +
.../callbacks/DeviceRegistrationCallback.java | 9 +
.../callbacks/GroupsRetrievedCallback.java | 13 +
.../client/callbacks/QueryResultsCallback.java | 9 +
.../android/client/utils/DeviceUuidFactory.java | 154 +
.../android/client/utils/ObjectUtils.java | 20 +
.../org/usergrid/android/client/Client.java | 590 -
.../client/callbacks/ApiResponseCallback.java | 10 -
.../client/callbacks/ClientAsyncTask.java | 38 -
.../client/callbacks/ClientCallback.java | 9 -
.../callbacks/DeviceRegistrationCallback.java | 9 -
.../callbacks/GroupsRetrievedCallback.java | 13 -
.../client/callbacks/QueryResultsCallback.java | 9 -
.../android/client/utils/DeviceUuidFactory.java | 154 -
.../android/client/utils/ObjectUtils.java | 20 -
sdks/html5-javascript/Gruntfile.js | 169 +-
sdks/html5-javascript/lib/Client.js | 865 -
sdks/html5-javascript/lib/Collection.js | 446 -
sdks/html5-javascript/lib/Counter.js | 186 -
sdks/html5-javascript/lib/Entity.js | 646 -
sdks/html5-javascript/lib/Group.js | 233 -
sdks/html5-javascript/lib/Module.js | 34 +
sdks/html5-javascript/lib/Usergrid.js | 283 +-
sdks/html5-javascript/lib/modules/Asset.js | 149 +
sdks/html5-javascript/lib/modules/Client.js | 749 +
sdks/html5-javascript/lib/modules/Collection.js | 459 +
sdks/html5-javascript/lib/modules/Counter.js | 186 +
sdks/html5-javascript/lib/modules/Entity.js | 659 +
sdks/html5-javascript/lib/modules/Error.js | 125 +
sdks/html5-javascript/lib/modules/Folder.js | 167 +
sdks/html5-javascript/lib/modules/Group.js | 233 +
sdks/html5-javascript/lib/modules/util/Ajax.js | 74 +
sdks/html5-javascript/lib/modules/util/Event.js | 33 +
.../html5-javascript/lib/modules/util/Logger.js | 68 +
.../lib/modules/util/Promise.js | 83 +
sdks/html5-javascript/tests/mocha/test.js | 1036 +-
.../tests/resources/js/blanket_mocha.min.js | 2 +-
sdks/html5-javascript/usergrid.js | 2673 +-
sdks/html5-javascript/usergrid.min.js | 5 +-
sdks/java/doc/allclasses-frame.html | 123 +-
sdks/java/doc/allclasses-noframe.html | 123 +-
sdks/java/doc/constant-values.html | 1437 +-
sdks/java/doc/deprecated-list.html | 237 +-
sdks/java/doc/help-doc.html | 419 +-
sdks/java/doc/index-all.html | 1299 +
sdks/java/doc/index-files/index-1.html | 209 -
sdks/java/doc/index-files/index-10.html | 151 -
sdks/java/doc/index-files/index-11.html | 154 -
sdks/java/doc/index-files/index-12.html | 151 -
sdks/java/doc/index-files/index-13.html | 217 -
sdks/java/doc/index-files/index-14.html | 268 -
sdks/java/doc/index-files/index-15.html | 204 -
sdks/java/doc/index-files/index-16.html | 151 -
sdks/java/doc/index-files/index-17.html | 466 -
sdks/java/doc/index-files/index-18.html | 184 -
sdks/java/doc/index-files/index-19.html | 157 -
sdks/java/doc/index-files/index-2.html | 193 -
sdks/java/doc/index-files/index-20.html | 239 -
sdks/java/doc/index-files/index-21.html | 154 -
sdks/java/doc/index-files/index-3.html | 161 -
sdks/java/doc/index-files/index-4.html | 166 -
sdks/java/doc/index-files/index-5.html | 151 -
sdks/java/doc/index-files/index-6.html | 547 -
sdks/java/doc/index-files/index-7.html | 145 -
sdks/java/doc/index-files/index-8.html | 160 -
sdks/java/doc/index-files/index-9.html | 145 -
sdks/java/doc/index.html | 89 +-
.../usergrid/java/client/Client.Query.html | 238 +
.../java/client/Client.QueuePosition.html | 381 +
.../org/apache/usergrid/java/client/Client.html | 1652 +
.../java/client/class-use/Client.Query.html | 246 +
.../client/class-use/Client.QueuePosition.html | 192 +
.../usergrid/java/client/class-use/Client.html | 175 +
.../entities/Activity.ActivityCollection.html | 408 +
.../entities/Activity.ActivityObject.html | 720 +
.../client/entities/Activity.MediaLink.html | 434 +
.../usergrid/java/client/entities/Activity.html | 1449 +
.../usergrid/java/client/entities/Device.html | 387 +
.../usergrid/java/client/entities/Entity.html | 599 +
.../usergrid/java/client/entities/Group.html | 427 +
.../usergrid/java/client/entities/Message.html | 641 +
.../usergrid/java/client/entities/User.html | 707 +
.../class-use/Activity.ActivityCollection.html | 117 +
.../class-use/Activity.ActivityObject.html | 231 +
.../entities/class-use/Activity.MediaLink.html | 191 +
.../client/entities/class-use/Activity.html | 203 +
.../java/client/entities/class-use/Device.html | 169 +
.../java/client/entities/class-use/Entity.html | 415 +
.../java/client/entities/class-use/Group.html | 159 +
.../java/client/entities/class-use/Message.html | 183 +
.../java/client/entities/class-use/User.html | 248 +
.../java/client/entities/package-frame.html | 28 +
.../java/client/entities/package-summary.html | 169 +
.../java/client/entities/package-tree.html | 141 +
.../java/client/entities/package-use.html | 219 +
.../java/client/exception/ClientException.html | 263 +
.../exception/class-use/ClientException.html | 117 +
.../java/client/exception/package-frame.html | 20 +
.../java/client/exception/package-summary.html | 137 +
.../java/client/exception/package-tree.html | 142 +
.../java/client/exception/package-use.html | 117 +
.../usergrid/java/client/package-frame.html | 28 +
.../usergrid/java/client/package-summary.html | 167 +
.../usergrid/java/client/package-tree.html | 146 +
.../usergrid/java/client/package-use.html | 158 +
.../java/client/response/AggregateCounter.html | 316 +
.../client/response/AggregateCounterSet.html | 444 +
.../java/client/response/ApiResponse.html | 1148 +
.../client/response/ClientCredentialsInfo.html | 316 +
.../java/client/response/QueueInfo.html | 297 +
.../response/class-use/AggregateCounter.html | 191 +
.../response/class-use/AggregateCounterSet.html | 170 +
.../client/response/class-use/ApiResponse.html | 365 +
.../class-use/ClientCredentialsInfo.html | 170 +
.../client/response/class-use/QueueInfo.html | 187 +
.../java/client/response/package-frame.html | 24 +
.../java/client/response/package-summary.html | 151 +
.../java/client/response/package-tree.html | 134 +
.../java/client/response/package-use.html | 178 +
.../usergrid/java/client/utils/JsonUtils.html | 480 +
.../usergrid/java/client/utils/MapUtils.html | 260 +
.../usergrid/java/client/utils/ObjectUtils.html | 258 +
.../usergrid/java/client/utils/UrlUtils.html | 314 +
.../java/client/utils/class-use/JsonUtils.html | 117 +
.../java/client/utils/class-use/MapUtils.html | 117 +
.../client/utils/class-use/ObjectUtils.html | 117 +
.../java/client/utils/class-use/UrlUtils.html | 117 +
.../java/client/utils/package-frame.html | 23 +
.../java/client/utils/package-summary.html | 147 +
.../java/client/utils/package-tree.html | 133 +
.../usergrid/java/client/utils/package-use.html | 117 +
.../usergrid/android/client/Client.Query.html | 247 -
.../android/client/Client.QueuePosition.html | 398 -
.../doc/org/usergrid/android/client/Client.html | 2389 -
.../client/callbacks/ApiResponseCallback.html | 221 -
.../client/callbacks/ClientAsyncTask.html | 281 -
.../client/callbacks/ClientCallback.html | 228 -
.../callbacks/DeviceRegistrationCallback.html | 221 -
.../callbacks/GroupsRetrievedCallback.html | 221 -
.../client/callbacks/QueryResultsCallback.html | 221 -
.../class-use/ApiResponseCallback.html | 328 -
.../callbacks/class-use/ClientAsyncTask.html | 144 -
.../callbacks/class-use/ClientCallback.html | 218 -
.../class-use/DeviceRegistrationCallback.html | 182 -
.../class-use/GroupsRetrievedCallback.html | 181 -
.../class-use/QueryResultsCallback.html | 266 -
.../android/client/callbacks/package-frame.html | 51 -
.../client/callbacks/package-summary.html | 187 -
.../android/client/callbacks/package-tree.html | 162 -
.../android/client/callbacks/package-use.html | 207 -
.../android/client/class-use/Client.Query.html | 306 -
.../client/class-use/Client.QueuePosition.html | 222 -
.../android/client/class-use/Client.html | 204 -
.../entities/Activity.ActivityCollection.html | 412 -
.../entities/Activity.ActivityObject.html | 868 -
.../client/entities/Activity.MediaLink.html | 450 -
.../android/client/entities/Activity.html | 1790 -
.../android/client/entities/Device.html | 402 -
.../android/client/entities/Entity.html | 586 -
.../usergrid/android/client/entities/Group.html | 458 -
.../android/client/entities/Message.html | 756 -
.../usergrid/android/client/entities/User.html | 850 -
.../class-use/Activity.ActivityCollection.html | 144 -
.../class-use/Activity.ActivityObject.html | 276 -
.../entities/class-use/Activity.MediaLink.html | 212 -
.../client/entities/class-use/Activity.html | 227 -
.../client/entities/class-use/Device.html | 210 -
.../client/entities/class-use/Entity.html | 635 -
.../client/entities/class-use/Group.html | 209 -
.../client/entities/class-use/Message.html | 212 -
.../android/client/entities/class-use/User.html | 344 -
.../android/client/entities/package-frame.html | 48 -
.../client/entities/package-summary.html | 189 -
.../android/client/entities/package-tree.html | 155 -
.../android/client/entities/package-use.html | 293 -
.../usergrid/android/client/package-frame.html | 54 -
.../android/client/package-summary.html | 185 -
.../usergrid/android/client/package-tree.html | 168 -
.../usergrid/android/client/package-use.html | 201 -
.../client/response/AggregateCounter.html | 333 -
.../client/response/AggregateCounterSet.html | 511 -
.../android/client/response/ApiResponse.html | 1576 -
.../client/response/ClientCredentialsInfo.html | 333 -
.../android/client/response/QueueInfo.html | 309 -
.../response/class-use/AggregateCounter.html | 223 -
.../response/class-use/AggregateCounterSet.html | 196 -
.../client/response/class-use/ApiResponse.html | 434 -
.../class-use/ClientCredentialsInfo.html | 196 -
.../client/response/class-use/QueueInfo.html | 220 -
.../android/client/response/package-frame.html | 40 -
.../client/response/package-summary.html | 173 -
.../android/client/response/package-tree.html | 153 -
.../android/client/response/package-use.html | 226 -
.../android/client/utils/DeviceUuidFactory.html | 285 -
.../android/client/utils/JsonUtils.html | 556 -
.../usergrid/android/client/utils/MapUtils.html | 261 -
.../android/client/utils/ObjectUtils.html | 252 -
.../usergrid/android/client/utils/UrlUtils.html | 332 -
.../utils/class-use/DeviceUuidFactory.html | 144 -
.../client/utils/class-use/JsonUtils.html | 144 -
.../client/utils/class-use/MapUtils.html | 144 -
.../client/utils/class-use/ObjectUtils.html | 144 -
.../client/utils/class-use/UrlUtils.html | 144 -
.../android/client/utils/package-frame.html | 40 -
.../android/client/utils/package-summary.html | 174 -
.../android/client/utils/package-tree.html | 153 -
.../android/client/utils/package-use.html | 144 -
sdks/java/doc/overview-frame.html | 73 +-
sdks/java/doc/overview-summary.html | 288 +-
sdks/java/doc/overview-tree.html | 331 +-
sdks/java/doc/package-list | 10 +-
sdks/java/doc/resources/background.gif | Bin 0 -> 2313 bytes
sdks/java/doc/resources/inherit.gif | Bin 57 -> 0 bytes
sdks/java/doc/resources/tab.gif | Bin 0 -> 291 bytes
sdks/java/doc/resources/titlebar.gif | Bin 0 -> 10701 bytes
sdks/java/doc/resources/titlebar_end.gif | Bin 0 -> 849 bytes
sdks/java/doc/serialized-form.html | 134 +
sdks/java/doc/stylesheet.css | 501 +-
sdks/java/pom.xml | 182 +-
.../org/apache/usergrid/java/client/Client.java | 1276 +
.../usergrid/java/client/entities/Activity.java | 627 +
.../usergrid/java/client/entities/Device.java | 52 +
.../usergrid/java/client/entities/Entity.java | 175 +
.../usergrid/java/client/entities/Group.java | 63 +
.../usergrid/java/client/entities/Message.java | 132 +
.../usergrid/java/client/entities/User.java | 142 +
.../java/client/exception/ClientException.java | 40 +
.../java/client/response/AggregateCounter.java | 36 +
.../client/response/AggregateCounterSet.java | 95 +
.../java/client/response/ApiResponse.java | 405 +
.../client/response/ClientCredentialsInfo.java | 42 +
.../java/client/response/QueueInfo.java | 28 +
.../usergrid/java/client/utils/JsonUtils.java | 166 +
.../usergrid/java/client/utils/MapUtils.java | 23 +
.../usergrid/java/client/utils/ObjectUtils.java | 20 +
.../usergrid/java/client/utils/UrlUtils.java | 108 +
.../java/org/usergrid/java/client/Client.java | 1276 -
.../usergrid/java/client/entities/Activity.java | 627 -
.../usergrid/java/client/entities/Device.java | 52 -
.../usergrid/java/client/entities/Entity.java | 175 -
.../usergrid/java/client/entities/Group.java | 63 -
.../usergrid/java/client/entities/Message.java | 132 -
.../org/usergrid/java/client/entities/User.java | 142 -
.../java/client/exception/ClientException.java | 40 -
.../java/client/response/AggregateCounter.java | 36 -
.../client/response/AggregateCounterSet.java | 95 -
.../java/client/response/ApiResponse.java | 405 -
.../client/response/ClientCredentialsInfo.java | 42 -
.../java/client/response/QueueInfo.java | 28 -
.../usergrid/java/client/utils/JsonUtils.java | 166 -
.../usergrid/java/client/utils/MapUtils.java | 23 -
.../usergrid/java/client/utils/ObjectUtils.java | 20 -
.../usergrid/java/client/utils/UrlUtils.java | 108 -
.../lib/vendor/Apigee/Usergrid/Collection.php | 18 +-
sdks/php/lib/vendor/Apigee/Usergrid/Entity.php | 90 +-
stack/README.md | 4 +-
stack/awscluster/README.md | 84 +
stack/awscluster/assembly.xml | 29 +
stack/awscluster/aws-sample.properties | 2 +
stack/awscluster/cassandra-cf.json | 315 +
stack/awscluster/pom.xml | 139 +
.../src/main/dist/conf/Priam.properties | 21 +
.../src/main/dist/init_instance/create_raid0.sh | 32 +
.../main/dist/init_instance/init_instance.sh | 54 +
.../dist/init_instance/install_cassandra.sh | 56 +
.../dist/init_instance/install_elasticsearch.sh | 24 +
.../dist/init_instance/install_oraclejdk.sh | 31 +
.../src/main/dist/lib/priam-agent-1.2.24.jar | Bin 0 -> 33020 bytes
.../dist/lib/priam-cass-extensions-1.2.24.jar | Bin 0 -> 5478 bytes
.../src/main/dist/webapps/priam-web-1.2.24.war | Bin 0 -> 31272443 bytes
.../src/main/groovy/configure_cassandra.groovy | 113 +
.../main/groovy/configure_elasticsearch.groovy | 47 +
.../src/main/groovy/configure_priam.groovy | 41 +
.../src/main/groovy/registry_clear.groovy | 20 +
.../src/main/groovy/registry_list.groovy | 24 +
.../src/main/groovy/registry_register.groovy | 38 +
.../src/main/groovy/tag_instance.groovy | 28 +
.../src/main/groovy/wait_for_instances.groovy | 44 +
stack/build-tools/pom.xml | 4 +-
.../src/main/resources/usergrid/checkstyle.xml | 2 +-
stack/config/pom.xml | 4 +-
stack/config/src/main/resources/log4j.xml | 14 +-
.../main/resources/usergrid-default.properties | 2 +-
.../config/src/test/resources/log4j.properties | 14 +-
stack/config/src/test/resources/log4j.xml | 4 +-
stack/core/pom.xml | 14 +-
.../persistence/query/tree/QueryFilter.g | 311 +
.../persistence/query/tree/QueryFilter.g | 311 -
.../java/org/apache/usergrid/batch/AppArgs.java | 57 +
.../java/org/apache/usergrid/batch/Job.java | 20 +
.../org/apache/usergrid/batch/JobExecution.java | 91 +
.../apache/usergrid/batch/JobExecutionImpl.java | 202 +
.../org/apache/usergrid/batch/JobFactory.java | 19 +
.../usergrid/batch/JobNotFoundException.java | 23 +
.../org/apache/usergrid/batch/JobRuntime.java | 40 +
.../usergrid/batch/JobRuntimeException.java | 49 +
.../usergrid/batch/UsergridJobFactory.java | 37 +
.../apache/usergrid/batch/job/OnlyOnceJob.java | 85 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../usergrid/batch/repository/JobAccessor.java | 36 +
.../batch/repository/JobDescriptor.java | 80 +
.../usergrid/batch/repository/package-info.java | 18 +
.../org/apache/usergrid/batch/service/App.java | 70 +
.../usergrid/batch/service/JobListener.java | 50 +
.../batch/service/JobRuntimeService.java | 49 +
.../batch/service/JobSchedulerService.java | 315 +
.../batch/service/SchedulerService.java | 54 +
.../batch/service/SchedulerServiceImpl.java | 428 +
.../usergrid/batch/service/package-info.java | 18 +
.../hazelcast/HazelcastLifecycleMonitor.java | 78 +
.../apache/usergrid/count/AbstractBatcher.java | 175 +
.../apache/usergrid/count/BatchSubmitter.java | 30 +
.../java/org/apache/usergrid/count/Batcher.java | 35 +
.../usergrid/count/CassandraCounterStore.java | 100 +
.../usergrid/count/CassandraSubmitter.java | 77 +
.../apache/usergrid/count/CountProducer.java | 25 +
.../CounterProcessingUnavailableException.java | 38 +
.../org/apache/usergrid/count/CounterStore.java | 30 +
.../apache/usergrid/count/SimpleBatcher.java | 40 +
.../usergrid/count/Slf4JBatchSubmitter.java | 77 +
.../org/apache/usergrid/count/common/Count.java | 139 +
.../usergrid/count/common/CountSerDeUtils.java | 51 +
.../common/CountTransportSerDeException.java | 38 +
.../org/apache/usergrid/count/package-info.java | 2 +
.../usergrid/exception/JsonReadException.java | 27 +
.../usergrid/exception/JsonWriteException.java | 27 +
.../exception/NotImplementedException.java | 58 +
.../java/org/apache/usergrid/locking/Lock.java | 44 +
.../org/apache/usergrid/locking/LockHelper.java | 51 +
.../apache/usergrid/locking/LockManager.java | 40 +
.../usergrid/locking/LockPathBuilder.java | 68 +
.../locking/cassandra/HectorLockImpl.java | 85 +
.../cassandra/HectorLockManagerImpl.java | 141 +
.../locking/exception/UGLockException.java | 49 +
.../usergrid/locking/noop/NoOpLockImpl.java | 61 +
.../locking/noop/NoOpLockManagerImpl.java | 40 +
.../locking/singlenode/SingleNodeLockImpl.java | 70 +
.../singlenode/SingleNodeLockManagerImpl.java | 93 +
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 +
.../locking/zookeeper/ZookeeperLockImpl.java | 87 +
.../org/apache/usergrid/mq/CounterQuery.java | 313 +
.../java/org/apache/usergrid/mq/Message.java | 512 +
.../main/java/org/apache/usergrid/mq/Query.java | 1857 +
.../apache/usergrid/mq/QueryFilterLexer.java | 1842 +
.../apache/usergrid/mq/QueryFilterParser.java | 1102 +
.../org/apache/usergrid/mq/QueryProcessor.java | 562 +
.../main/java/org/apache/usergrid/mq/Queue.java | 291 +
.../org/apache/usergrid/mq/QueueManager.java | 130 +
.../apache/usergrid/mq/QueueManagerFactory.java | 41 +
.../org/apache/usergrid/mq/QueuePosition.java | 59 +
.../java/org/apache/usergrid/mq/QueueQuery.java | 306 +
.../org/apache/usergrid/mq/QueueResults.java | 128 +
.../java/org/apache/usergrid/mq/QueueSet.java | 192 +
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 +
.../mq/cassandra/MessageIndexUpdate.java | 120 +
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 +
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 +
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 +
.../apache/usergrid/mq/cassandra/QueuesCF.java | 156 +
.../mq/cassandra/io/AbstractSearch.java | 358 +
.../mq/cassandra/io/ConsumerTransaction.java | 471 +
.../usergrid/mq/cassandra/io/EndSearch.java | 69 +
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 +
.../mq/cassandra/io/NoTransactionSearch.java | 132 +
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 +
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 +
.../usergrid/mq/cassandra/io/StartSearch.java | 68 +
.../usergrid/persistence/AbstractEntity.java | 341 +
.../usergrid/persistence/AggregateCounter.java | 48 +
.../persistence/AggregateCounterSet.java | 116 +
.../persistence/AssociatedEntityRef.java | 21 +
.../usergrid/persistence/CollectionRef.java | 26 +
.../persistence/ConnectedEntityRef.java | 22 +
.../usergrid/persistence/ConnectionRef.java | 34 +
.../usergrid/persistence/CounterQuery.java | 312 +
.../usergrid/persistence/CounterResolution.java | 84 +
.../usergrid/persistence/CredentialsInfo.java | 176 +
.../usergrid/persistence/DynamicEntity.java | 111 +
.../org/apache/usergrid/persistence/Entity.java | 102 +
.../usergrid/persistence/EntityFactory.java | 131 +
.../usergrid/persistence/EntityManager.java | 620 +
.../persistence/EntityManagerFactory.java | 108 +
.../persistence/EntityPropertyComparator.java | 55 +
.../apache/usergrid/persistence/EntityRef.java | 37 +
.../usergrid/persistence/EntityUtils.java | 53 +
.../apache/usergrid/persistence/Identifier.java | 226 +
.../persistence/IndexBucketLocator.java | 75 +
.../persistence/MultiQueryIterator.java | 106 +
.../persistence/PagingResultsIterator.java | 109 +
.../apache/usergrid/persistence/PathQuery.java | 115 +
.../org/apache/usergrid/persistence/Query.java | 1310 +
.../apache/usergrid/persistence/QueryUtils.java | 34 +
.../usergrid/persistence/RelationManager.java | 113 +
.../apache/usergrid/persistence/Results.java | 1294 +
.../apache/usergrid/persistence/RoleRef.java | 31 +
.../org/apache/usergrid/persistence/Schema.java | 1788 +
.../persistence/SimpleCollectionRef.java | 84 +
.../usergrid/persistence/SimpleEntityRef.java | 149 +
.../usergrid/persistence/SimpleRoleRef.java | 125 +
.../usergrid/persistence/TypedEntity.java | 37 +
.../org/apache/usergrid/persistence/Update.java | 75 +
.../annotations/EntityCollection.java | 43 +
.../annotations/EntityDictionary.java | 38 +
.../persistence/annotations/EntityProperty.java | 54 +
.../persistence/cassandra/ApplicationCF.java | 160 +
.../usergrid/persistence/cassandra/CFEnum.java | 37 +
.../cassandra/CassandraPersistenceUtils.java | 486 +
.../persistence/cassandra/CassandraService.java | 1138 +
.../cassandra/ConnectedEntityRefImpl.java | 61 +
.../cassandra/ConnectionRefImpl.java | 628 +
.../persistence/cassandra/CounterUtils.java | 400 +
.../persistence/cassandra/CursorCache.java | 121 +
.../cassandra/EntityManagerFactoryImpl.java | 411 +
.../cassandra/EntityManagerImpl.java | 2858 +
.../cassandra/EntityValueSerializer.java | 52 +
.../persistence/cassandra/GeoIndexManager.java | 323 +
.../persistence/cassandra/IndexUpdate.java | 450 +
.../persistence/cassandra/QueryProcessor.java | 720 +
.../cassandra/RelationManagerImpl.java | 2334 +
.../usergrid/persistence/cassandra/Setup.java | 206 +
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 +
.../cassandra/index/ConnectedIndexScanner.java | 281 +
.../cassandra/index/IndexBucketScanner.java | 239 +
.../index/IndexMultiBucketSetLoader.java | 138 +
.../cassandra/index/IndexScanner.java | 39 +
.../cassandra/index/NoOpIndexScanner.java | 94 +
.../cassandra/util/Slf4jTraceTagReporter.java | 47 +
.../cassandra/util/TaggedOpTimer.java | 38 +
.../persistence/cassandra/util/TimedOpTag.java | 101 +
.../cassandra/util/TraceParticipant.java | 20 +
.../persistence/cassandra/util/TraceTag.java | 77 +
.../cassandra/util/TraceTagAspect.java | 41 +
.../cassandra/util/TraceTagManager.java | 156 +
.../cassandra/util/TraceTagReporter.java | 10 +
.../usergrid/persistence/entities/Activity.java | 685 +
.../persistence/entities/Application.java | 609 +
.../usergrid/persistence/entities/Asset.java | 93 +
.../usergrid/persistence/entities/Device.java | 105 +
.../usergrid/persistence/entities/Event.java | 155 +
.../usergrid/persistence/entities/Folder.java | 93 +
.../usergrid/persistence/entities/Group.java | 168 +
.../usergrid/persistence/entities/JobData.java | 54 +
.../usergrid/persistence/entities/JobStat.java | 175 +
.../usergrid/persistence/entities/Message.java | 77 +
.../usergrid/persistence/entities/Role.java | 153 +
.../usergrid/persistence/entities/User.java | 348 +
.../ApplicationAlreadyExistsException.java | 37 +
.../DuplicateUniquePropertyExistsException.java | 52 +
.../exceptions/EntityNotFoundException.java | 45 +
.../exceptions/LockingException.java | 65 +
.../exceptions/NoFullTextIndexException.java | 50 +
.../exceptions/NoIndexException.java | 50 +
.../exceptions/PersistenceException.java | 45 +
.../PropertyTypeConversionException.java | 71 +
.../exceptions/QueryIterationException.java | 13 +
.../exceptions/QueryParseException.java | 63 +
.../exceptions/QueryTokenException.java | 52 +
.../persistence/exceptions/QueueException.java | 61 +
.../RequiredPropertyNotFoundException.java | 41 +
.../TransactionNotFoundException.java | 45 +
.../UnexpectedEntityTypeException.java | 45 +
.../persistence/geo/CollectionGeoSearch.java | 52 +
.../persistence/geo/ConnectionGeoSearch.java | 51 +
.../persistence/geo/EntityLocationRef.java | 211 +
.../EntityLocationRefDistanceComparator.java | 77 +
.../persistence/geo/GeoIndexSearcher.java | 368 +
.../persistence/geo/GeocellManager.java | 179 +
.../usergrid/persistence/geo/GeocellUtils.java | 539 +
.../geo/comparator/DoubleTupleComparator.java | 23 +
.../persistence/geo/model/BoundingBox.java | 71 +
.../persistence/geo/model/CostFunction.java | 33 +
.../geo/model/DefaultCostFunction.java | 34 +
.../usergrid/persistence/geo/model/Point.java | 58 +
.../usergrid/persistence/geo/model/Tuple.java | 24 +
.../usergrid/persistence/query/ir/AllNode.java | 54 +
.../usergrid/persistence/query/ir/AndNode.java | 43 +
.../persistence/query/ir/BooleanNode.java | 48 +
.../query/ir/EmailIdentifierNode.java | 31 +
.../query/ir/NameIdentifierNode.java | 28 +
.../persistence/query/ir/NodeVisitor.java | 78 +
.../usergrid/persistence/query/ir/NotNode.java | 62 +
.../usergrid/persistence/query/ir/OrNode.java | 52 +
.../persistence/query/ir/OrderByNode.java | 92 +
.../persistence/query/ir/QueryNode.java | 28 +
.../persistence/query/ir/QuerySlice.java | 344 +
.../persistence/query/ir/SearchVisitor.java | 254 +
.../persistence/query/ir/SliceNode.java | 167 +
.../query/ir/UuidIdentifierNode.java | 32 +
.../persistence/query/ir/WithinNode.java | 96 +
.../query/ir/result/AbstractScanColumn.java | 70 +
.../result/CollectionResultsLoaderFactory.java | 23 +
.../ir/result/ConnectionIndexSliceParser.java | 86 +
.../query/ir/result/ConnectionRefLoader.java | 65 +
.../result/ConnectionResultsLoaderFactory.java | 32 +
.../ir/result/ConnectionTypesIterator.java | 179 +
.../query/ir/result/EmptyIterator.java | 47 +
.../query/ir/result/EntityRefLoader.java | 50 +
.../query/ir/result/EntityResultsLoader.java | 46 +
.../query/ir/result/GeoIterator.java | 355 +
.../persistence/query/ir/result/IDLoader.java | 24 +
.../query/ir/result/IntersectionIterator.java | 169 +
.../query/ir/result/MergeIterator.java | 149 +
.../query/ir/result/MultiIterator.java | 54 +
.../query/ir/result/OrderByIterator.java | 252 +
.../query/ir/result/ResultIterator.java | 43 +
.../query/ir/result/ResultsLoader.java | 29 +
.../query/ir/result/ResultsLoaderFactory.java | 21 +
.../persistence/query/ir/result/ScanColumn.java | 16 +
.../query/ir/result/ScanColumnTransformer.java | 23 +
.../ir/result/SecondaryIndexSliceParser.java | 60 +
.../query/ir/result/SliceIterator.java | 241 +
.../query/ir/result/SliceParser.java | 31 +
.../query/ir/result/StaticIdIterator.java | 66 +
.../query/ir/result/SubtractionIterator.java | 108 +
.../query/ir/result/UUIDIndexSliceParser.java | 50 +
.../query/ir/result/UnionIterator.java | 267 +
.../usergrid/persistence/query/tree/.gitignore | 2 +
.../persistence/query/tree/AndOperand.java | 48 +
.../persistence/query/tree/BooleanLiteral.java | 48 +
.../persistence/query/tree/BooleanOperand.java | 48 +
.../persistence/query/tree/ContainsOperand.java | 69 +
.../query/tree/ContainsProperty.java | 57 +
.../usergrid/persistence/query/tree/Equal.java | 52 +
.../persistence/query/tree/EqualityOperand.java | 88 +
.../persistence/query/tree/FloatLiteral.java | 57 +
.../persistence/query/tree/GreaterThan.java | 52 +
.../query/tree/GreaterThanEqual.java | 56 +
.../persistence/query/tree/LessThan.java | 52 +
.../persistence/query/tree/LessThanEqual.java | 54 +
.../persistence/query/tree/Literal.java | 38 +
.../persistence/query/tree/LiteralFactory.java | 58 +
.../persistence/query/tree/LongLiteral.java | 64 +
.../persistence/query/tree/NotOperand.java | 45 +
.../persistence/query/tree/NumericLiteral.java | 24 +
.../persistence/query/tree/Operand.java | 47 +
.../persistence/query/tree/OrOperand.java | 53 +
.../persistence/query/tree/Property.java | 62 +
.../persistence/query/tree/QueryVisitor.java | 90 +
.../persistence/query/tree/StringLiteral.java | 82 +
.../persistence/query/tree/UUIDLiteral.java | 49 +
.../persistence/query/tree/WithinOperand.java | 111 +
.../persistence/query/tree/WithinProperty.java | 54 +
.../persistence/schema/CollectionInfo.java | 207 +
.../persistence/schema/DictionaryInfo.java | 117 +
.../usergrid/persistence/schema/EntityInfo.java | 299 +
.../persistence/schema/PropertyInfo.java | 218 +
.../usergrid/system/UsergridSystemMonitor.java | 95 +
.../org/apache/usergrid/utils/AESUtils.java | 84 +
.../java/org/apache/usergrid/utils/BCrypt.java | 627 +
.../org/apache/usergrid/utils/ClassUtils.java | 58 +
.../org/apache/usergrid/utils/CodecUtils.java | 45 +
.../apache/usergrid/utils/CompositeUtils.java | 54 +
.../apache/usergrid/utils/ConversionUtils.java | 765 +
.../org/apache/usergrid/utils/DateUtils.java | 88 +
.../org/apache/usergrid/utils/HttpUtils.java | 51 +
.../org/apache/usergrid/utils/IndexUtils.java | 218 +
.../apache/usergrid/utils/InflectionUtils.java | 51 +
.../org/apache/usergrid/utils/Inflector.java | 553 +
.../org/apache/usergrid/utils/JsonUtils.java | 329 +
.../org/apache/usergrid/utils/ListUtils.java | 230 +
.../org/apache/usergrid/utils/MailUtils.java | 154 +
.../org/apache/usergrid/utils/MapUtils.java | 377 +
.../org/apache/usergrid/utils/NumberUtils.java | 35 +
.../apache/usergrid/utils/PasswordUtils.java | 28 +
.../org/apache/usergrid/utils/StringUtils.java | 172 +
.../org/apache/usergrid/utils/TimeUtils.java | 88 +
.../org/apache/usergrid/utils/UUIDUtils.java | 412 +
.../java/org/apache/usergrid/utils/Version.java | 428 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../main/java/org/usergrid/batch/AppArgs.java | 57 -
.../src/main/java/org/usergrid/batch/Job.java | 20 -
.../java/org/usergrid/batch/JobExecution.java | 91 -
.../org/usergrid/batch/JobExecutionImpl.java | 202 -
.../java/org/usergrid/batch/JobFactory.java | 19 -
.../usergrid/batch/JobNotFoundException.java | 23 -
.../java/org/usergrid/batch/JobRuntime.java | 40 -
.../org/usergrid/batch/JobRuntimeException.java | 49 -
.../org/usergrid/batch/UsergridJobFactory.java | 37 -
.../org/usergrid/batch/job/OnlyOnceJob.java | 85 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../usergrid/batch/repository/JobAccessor.java | 36 -
.../batch/repository/JobDescriptor.java | 80 -
.../usergrid/batch/repository/package-info.java | 18 -
.../java/org/usergrid/batch/service/App.java | 70 -
.../org/usergrid/batch/service/JobListener.java | 50 -
.../batch/service/JobRuntimeService.java | 49 -
.../batch/service/JobSchedulerService.java | 315 -
.../batch/service/SchedulerService.java | 54 -
.../batch/service/SchedulerServiceImpl.java | 428 -
.../usergrid/batch/service/package-info.java | 18 -
.../hazelcast/HazelcastLifecycleMonitor.java | 78 -
.../org/usergrid/count/AbstractBatcher.java | 175 -
.../java/org/usergrid/count/BatchSubmitter.java | 30 -
.../main/java/org/usergrid/count/Batcher.java | 35 -
.../usergrid/count/CassandraCounterStore.java | 100 -
.../org/usergrid/count/CassandraSubmitter.java | 77 -
.../java/org/usergrid/count/CountProducer.java | 25 -
.../CounterProcessingUnavailableException.java | 38 -
.../java/org/usergrid/count/CounterStore.java | 30 -
.../java/org/usergrid/count/SimpleBatcher.java | 40 -
.../org/usergrid/count/Slf4JBatchSubmitter.java | 77 -
.../java/org/usergrid/count/common/Count.java | 139 -
.../usergrid/count/common/CountSerDeUtils.java | 51 -
.../common/CountTransportSerDeException.java | 38 -
.../java/org/usergrid/count/package-info.java | 0
.../usergrid/exception/JsonReadException.java | 27 -
.../usergrid/exception/JsonWriteException.java | 27 -
.../exception/NotImplementedException.java | 58 -
.../main/java/org/usergrid/locking/Lock.java | 44 -
.../java/org/usergrid/locking/LockHelper.java | 51 -
.../java/org/usergrid/locking/LockManager.java | 40 -
.../org/usergrid/locking/LockPathBuilder.java | 68 -
.../locking/cassandra/HectorLockImpl.java | 85 -
.../cassandra/HectorLockManagerImpl.java | 141 -
.../locking/exception/UGLockException.java | 49 -
.../org/usergrid/locking/noop/NoOpLockImpl.java | 61 -
.../locking/noop/NoOpLockManagerImpl.java | 40 -
.../locking/singlenode/SingleNodeLockImpl.java | 70 -
.../singlenode/SingleNodeLockManagerImpl.java | 93 -
.../zookeeper/ZooKeeperLockManagerImpl.java | 114 -
.../locking/zookeeper/ZookeeperLockImpl.java | 87 -
.../main/java/org/usergrid/mq/CounterQuery.java | 314 -
.../src/main/java/org/usergrid/mq/Message.java | 512 -
.../src/main/java/org/usergrid/mq/Query.java | 1857 -
.../java/org/usergrid/mq/QueryFilterLexer.java | 1842 -
.../java/org/usergrid/mq/QueryFilterParser.java | 1102 -
.../java/org/usergrid/mq/QueryProcessor.java | 562 -
.../src/main/java/org/usergrid/mq/Queue.java | 291 -
.../main/java/org/usergrid/mq/QueueManager.java | 130 -
.../org/usergrid/mq/QueueManagerFactory.java | 41 -
.../java/org/usergrid/mq/QueuePosition.java | 59 -
.../main/java/org/usergrid/mq/QueueQuery.java | 306 -
.../main/java/org/usergrid/mq/QueueResults.java | 128 -
.../src/main/java/org/usergrid/mq/QueueSet.java | 192 -
.../usergrid/mq/cassandra/CassandraMQUtils.java | 278 -
.../mq/cassandra/MessageIndexUpdate.java | 120 -
.../usergrid/mq/cassandra/QueueIndexUpdate.java | 349 -
.../mq/cassandra/QueueManagerFactoryImpl.java | 85 -
.../usergrid/mq/cassandra/QueueManagerImpl.java | 1391 -
.../org/usergrid/mq/cassandra/QueuesCF.java | 156 -
.../mq/cassandra/io/AbstractSearch.java | 358 -
.../mq/cassandra/io/ConsumerTransaction.java | 471 -
.../org/usergrid/mq/cassandra/io/EndSearch.java | 69 -
.../usergrid/mq/cassandra/io/FilterSearch.java | 259 -
.../mq/cassandra/io/NoTransactionSearch.java | 132 -
.../usergrid/mq/cassandra/io/QueueBounds.java | 91 -
.../usergrid/mq/cassandra/io/QueueSearch.java | 29 -
.../usergrid/mq/cassandra/io/StartSearch.java | 68 -
.../usergrid/persistence/AbstractEntity.java | 342 -
.../usergrid/persistence/AggregateCounter.java | 48 -
.../persistence/AggregateCounterSet.java | 116 -
.../persistence/AssociatedEntityRef.java | 21 -
.../org/usergrid/persistence/CollectionRef.java | 26 -
.../persistence/ConnectedEntityRef.java | 22 -
.../org/usergrid/persistence/ConnectionRef.java | 34 -
.../org/usergrid/persistence/CounterQuery.java | 313 -
.../usergrid/persistence/CounterResolution.java | 84 -
.../usergrid/persistence/CredentialsInfo.java | 176 -
.../org/usergrid/persistence/DynamicEntity.java | 111 -
.../java/org/usergrid/persistence/Entity.java | 103 -
.../org/usergrid/persistence/EntityFactory.java | 131 -
.../org/usergrid/persistence/EntityManager.java | 620 -
.../persistence/EntityManagerFactory.java | 108 -
.../persistence/EntityPropertyComparator.java | 55 -
.../org/usergrid/persistence/EntityRef.java | 37 -
.../org/usergrid/persistence/EntityUtils.java | 53 -
.../org/usergrid/persistence/Identifier.java | 226 -
.../persistence/IndexBucketLocator.java | 75 -
.../persistence/MultiQueryIterator.java | 106 -
.../persistence/PagingResultsIterator.java | 109 -
.../org/usergrid/persistence/PathQuery.java | 115 -
.../java/org/usergrid/persistence/Query.java | 1310 -
.../org/usergrid/persistence/QueryUtils.java | 34 -
.../usergrid/persistence/RelationManager.java | 113 -
.../java/org/usergrid/persistence/Results.java | 1294 -
.../java/org/usergrid/persistence/RoleRef.java | 31 -
.../java/org/usergrid/persistence/Schema.java | 1788 -
.../persistence/SimpleCollectionRef.java | 84 -
.../usergrid/persistence/SimpleEntityRef.java | 149 -
.../org/usergrid/persistence/SimpleRoleRef.java | 125 -
.../org/usergrid/persistence/TypedEntity.java | 37 -
.../java/org/usergrid/persistence/Update.java | 75 -
.../annotations/EntityCollection.java | 43 -
.../annotations/EntityDictionary.java | 38 -
.../persistence/annotations/EntityProperty.java | 54 -
.../persistence/cassandra/ApplicationCF.java | 160 -
.../usergrid/persistence/cassandra/CFEnum.java | 37 -
.../cassandra/CassandraPersistenceUtils.java | 486 -
.../persistence/cassandra/CassandraService.java | 1138 -
.../cassandra/ConnectedEntityRefImpl.java | 61 -
.../cassandra/ConnectionRefImpl.java | 628 -
.../persistence/cassandra/CounterUtils.java | 400 -
.../persistence/cassandra/CursorCache.java | 121 -
.../cassandra/EntityManagerFactoryImpl.java | 411 -
.../cassandra/EntityManagerImpl.java | 2858 -
.../cassandra/EntityValueSerializer.java | 52 -
.../persistence/cassandra/GeoIndexManager.java | 323 -
.../persistence/cassandra/IndexUpdate.java | 450 -
.../persistence/cassandra/QueryProcessor.java | 720 -
.../cassandra/RelationManagerImpl.java | 2334 -
.../usergrid/persistence/cassandra/Setup.java | 206 -
.../cassandra/SimpleIndexBucketLocatorImpl.java | 121 -
.../cassandra/index/ConnectedIndexScanner.java | 281 -
.../cassandra/index/IndexBucketScanner.java | 239 -
.../index/IndexMultiBucketSetLoader.java | 138 -
.../cassandra/index/IndexScanner.java | 39 -
.../cassandra/index/NoOpIndexScanner.java | 94 -
.../cassandra/util/Slf4jTraceTagReporter.java | 47 -
.../cassandra/util/TaggedOpTimer.java | 38 -
.../persistence/cassandra/util/TimedOpTag.java | 101 -
.../cassandra/util/TraceParticipant.java | 20 -
.../persistence/cassandra/util/TraceTag.java | 77 -
.../cassandra/util/TraceTagAspect.java | 41 -
.../cassandra/util/TraceTagManager.java | 156 -
.../cassandra/util/TraceTagReporter.java | 10 -
.../usergrid/persistence/entities/Activity.java | 685 -
.../persistence/entities/Application.java | 609 -
.../usergrid/persistence/entities/Asset.java | 93 -
.../usergrid/persistence/entities/Device.java | 105 -
.../usergrid/persistence/entities/Event.java | 155 -
.../usergrid/persistence/entities/Folder.java | 93 -
.../usergrid/persistence/entities/Group.java | 168 -
.../usergrid/persistence/entities/JobData.java | 54 -
.../usergrid/persistence/entities/JobStat.java | 175 -
.../usergrid/persistence/entities/Message.java | 77 -
.../org/usergrid/persistence/entities/Role.java | 153 -
.../org/usergrid/persistence/entities/User.java | 348 -
.../ApplicationAlreadyExistsException.java | 37 -
.../DuplicateUniquePropertyExistsException.java | 52 -
.../exceptions/EntityNotFoundException.java | 45 -
.../exceptions/LockingException.java | 65 -
.../exceptions/NoFullTextIndexException.java | 50 -
.../exceptions/NoIndexException.java | 50 -
.../exceptions/PersistenceException.java | 45 -
.../PropertyTypeConversionException.java | 71 -
.../exceptions/QueryIterationException.java | 13 -
.../exceptions/QueryParseException.java | 63 -
.../exceptions/QueryTokenException.java | 52 -
.../persistence/exceptions/QueueException.java | 61 -
.../RequiredPropertyNotFoundException.java | 41 -
.../TransactionNotFoundException.java | 45 -
.../UnexpectedEntityTypeException.java | 45 -
.../persistence/geo/CollectionGeoSearch.java | 52 -
.../persistence/geo/ConnectionGeoSearch.java | 51 -
.../persistence/geo/EntityLocationRef.java | 211 -
.../EntityLocationRefDistanceComparator.java | 77 -
.../persistence/geo/GeoIndexSearcher.java | 368 -
.../persistence/geo/GeocellManager.java | 179 -
.../usergrid/persistence/geo/GeocellUtils.java | 539 -
.../geo/comparator/DoubleTupleComparator.java | 23 -
.../persistence/geo/model/BoundingBox.java | 71 -
.../persistence/geo/model/CostFunction.java | 33 -
.../geo/model/DefaultCostFunction.java | 34 -
.../usergrid/persistence/geo/model/Point.java | 58 -
.../usergrid/persistence/geo/model/Tuple.java | 24 -
.../usergrid/persistence/query/ir/AllNode.java | 54 -
.../usergrid/persistence/query/ir/AndNode.java | 43 -
.../persistence/query/ir/BooleanNode.java | 48 -
.../query/ir/EmailIdentifierNode.java | 31 -
.../query/ir/NameIdentifierNode.java | 28 -
.../persistence/query/ir/NodeVisitor.java | 78 -
.../usergrid/persistence/query/ir/NotNode.java | 62 -
.../usergrid/persistence/query/ir/OrNode.java | 52 -
.../persistence/query/ir/OrderByNode.java | 92 -
.../persistence/query/ir/QueryNode.java | 28 -
.../persistence/query/ir/QuerySlice.java | 344 -
.../persistence/query/ir/SearchVisitor.java | 254 -
.../persistence/query/ir/SliceNode.java | 168 -
.../query/ir/UuidIdentifierNode.java | 32 -
.../persistence/query/ir/WithinNode.java | 96 -
.../query/ir/result/AbstractScanColumn.java | 70 -
.../result/CollectionResultsLoaderFactory.java | 23 -
.../ir/result/ConnectionIndexSliceParser.java | 86 -
.../query/ir/result/ConnectionRefLoader.java | 65 -
.../result/ConnectionResultsLoaderFactory.java | 32 -
.../ir/result/ConnectionTypesIterator.java | 179 -
.../query/ir/result/EmptyIterator.java | 47 -
.../query/ir/result/EntityRefLoader.java | 50 -
.../query/ir/result/EntityResultsLoader.java | 46 -
.../query/ir/result/GeoIterator.java | 355 -
.../persistence/query/ir/result/IDLoader.java | 24 -
.../query/ir/result/IntersectionIterator.java | 169 -
.../query/ir/result/MergeIterator.java | 149 -
.../query/ir/result/MultiIterator.java | 54 -
.../query/ir/result/OrderByIterator.java | 252 -
.../query/ir/result/ResultIterator.java | 43 -
.../query/ir/result/ResultsLoader.java | 29 -
.../query/ir/result/ResultsLoaderFactory.java | 21 -
.../persistence/query/ir/result/ScanColumn.java | 16 -
.../query/ir/result/ScanColumnTransformer.java | 23 -
.../ir/result/SecondaryIndexSliceParser.java | 60 -
.../query/ir/result/SliceIterator.java | 241 -
.../query/ir/result/SliceParser.java | 31 -
.../query/ir/result/StaticIdIterator.java | 66 -
.../query/ir/result/SubtractionIterator.java | 108 -
.../query/ir/result/UUIDIndexSliceParser.java | 50 -
.../query/ir/result/UnionIterator.java | 267 -
.../usergrid/persistence/query/tree/.gitignore | 2 -
.../persistence/query/tree/AndOperand.java | 48 -
.../persistence/query/tree/BooleanLiteral.java | 48 -
.../persistence/query/tree/BooleanOperand.java | 48 -
.../persistence/query/tree/ContainsOperand.java | 69 -
.../query/tree/ContainsProperty.java | 57 -
.../usergrid/persistence/query/tree/Equal.java | 52 -
.../persistence/query/tree/EqualityOperand.java | 88 -
.../persistence/query/tree/FloatLiteral.java | 57 -
.../persistence/query/tree/GreaterThan.java | 52 -
.../query/tree/GreaterThanEqual.java | 56 -
.../persistence/query/tree/LessThan.java | 52 -
.../persistence/query/tree/LessThanEqual.java | 54 -
.../persistence/query/tree/Literal.java | 38 -
.../persistence/query/tree/LiteralFactory.java | 58 -
.../persistence/query/tree/LongLiteral.java | 64 -
.../persistence/query/tree/NotOperand.java | 45 -
.../persistence/query/tree/NumericLiteral.java | 24 -
.../persistence/query/tree/Operand.java | 47 -
.../persistence/query/tree/OrOperand.java | 53 -
.../persistence/query/tree/Property.java | 62 -
.../persistence/query/tree/QueryVisitor.java | 90 -
.../persistence/query/tree/StringLiteral.java | 82 -
.../persistence/query/tree/UUIDLiteral.java | 49 -
.../persistence/query/tree/WithinOperand.java | 111 -
.../persistence/query/tree/WithinProperty.java | 54 -
.../persistence/schema/CollectionInfo.java | 207 -
.../persistence/schema/DictionaryInfo.java | 117 -
.../usergrid/persistence/schema/EntityInfo.java | 299 -
.../persistence/schema/PropertyInfo.java | 218 -
.../usergrid/system/UsergridSystemMonitor.java | 95 -
.../main/java/org/usergrid/utils/AESUtils.java | 84 -
.../main/java/org/usergrid/utils/BCrypt.java | 627 -
.../java/org/usergrid/utils/ClassUtils.java | 58 -
.../java/org/usergrid/utils/CodecUtils.java | 45 -
.../java/org/usergrid/utils/CompositeUtils.java | 54 -
.../org/usergrid/utils/ConversionUtils.java | 765 -
.../main/java/org/usergrid/utils/DateUtils.java | 88 -
.../main/java/org/usergrid/utils/HttpUtils.java | 51 -
.../java/org/usergrid/utils/IndexUtils.java | 218 -
.../org/usergrid/utils/InflectionUtils.java | 51 -
.../main/java/org/usergrid/utils/Inflector.java | 553 -
.../main/java/org/usergrid/utils/JsonUtils.java | 329 -
.../main/java/org/usergrid/utils/ListUtils.java | 230 -
.../main/java/org/usergrid/utils/MailUtils.java | 154 -
.../main/java/org/usergrid/utils/MapUtils.java | 377 -
.../java/org/usergrid/utils/NumberUtils.java | 35 -
.../java/org/usergrid/utils/PasswordUtils.java | 28 -
.../java/org/usergrid/utils/StringUtils.java | 172 -
.../main/java/org/usergrid/utils/TimeUtils.java | 88 -
.../main/java/org/usergrid/utils/UUIDUtils.java | 412 -
.../main/java/org/usergrid/utils/Version.java | 428 -
.../java/org/usergrid/utils/package-info.java | 18 -
.../main/resources/usergrid-core-context.xml | 52 +-
.../resources/usergrid-scheduler-context.xml | 8 +-
stack/core/src/test/java/io/baas/Simple.java | 4 +-
.../org/apache/usergrid/AbstractCoreIT.java | 45 +
.../java/org/apache/usergrid/Application.java | 124 +
.../apache/usergrid/ConcurrentCoreITSuite.java | 50 +
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 +
.../usergrid/ConcurrentCoreTestSuite.java | 33 +
.../org/apache/usergrid/CoreApplication.java | 171 +
.../java/org/apache/usergrid/CoreITSetup.java | 43 +
.../org/apache/usergrid/CoreITSetupImpl.java | 145 +
.../java/org/apache/usergrid/CoreITSuite.java | 34 +
.../java/org/apache/usergrid/CoreTestSuite.java | 47 +
.../org/apache/usergrid/batch/AppArgsTest.java | 52 +
.../batch/BulkJobExecutionUnitTest.java | 209 +
.../apache/usergrid/batch/BulkTestUtils.java | 38 +
.../batch/ConcurrentSchedulerITSuite.java | 31 +
.../batch/ConcurrentSchedulerTestSuite.java | 19 +
.../apache/usergrid/batch/SchedulerITSuite.java | 34 +
.../usergrid/batch/SchedulerTestSuite.java | 18 +
.../usergrid/batch/UsergridJobFactoryTest.java | 31 +
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 +
.../usergrid/batch/job/CountdownLatchJob.java | 67 +
.../usergrid/batch/job/DelayExecution.java | 104 +
.../usergrid/batch/job/DelayHeartbeat.java | 106 +
.../batch/job/FailureJobExceuction.java | 74 +
.../usergrid/batch/job/OnlyOnceExceution.java | 116 +
.../job/OnlyOnceUnlockOnFailExceution.java | 126 +
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 +
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 +
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 +
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 +
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 +
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 +
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 +
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 +
.../usergrid/batch/job/TestJobListener.java | 121 +
.../usergrid/batch/job/TestJobListenerTest.java | 144 +
.../apache/usergrid/batch/job/package-info.java | 18 +
.../clustering/hazelcast/HazelcastTest.java | 111 +
.../count/BatchCountParallelismTest.java | 122 +
.../usergrid/count/SimpleBatcherTest.java | 50 +
.../count/common/CountSerDeUtilsTest.java | 68 +
.../apache/usergrid/count/common/CountTest.java | 68 +
.../locking/cassandra/HectorLockManagerIT.java | 185 +
.../SingleNodeLockTestSingleNode.java | 168 +
.../zookeeper/AbstractZooKeeperTest.java | 126 +
.../usergrid/locking/zookeeper/ZooPut.java | 113 +
.../zookeeper/ZookeeperLockManagerTest.java | 182 +
.../java/org/apache/usergrid/mq/MessagesIT.java | 278 +
.../org/apache/usergrid/mq/QueuePathsTest.java | 48 +
.../usergrid/persistence/CollectionIT.java | 1637 +
.../usergrid/persistence/CoreSchemaManager.java | 66 +
.../apache/usergrid/persistence/CounterIT.java | 235 +
.../persistence/EntityConnectionsIT.java | 292 +
.../persistence/EntityDictionaryIT.java | 133 +
.../usergrid/persistence/EntityManagerIT.java | 563 +
.../EntityPropertyComparatorTest.java | 206 +
.../apache/usergrid/persistence/EntityTest.java | 100 +
.../org/apache/usergrid/persistence/GeoIT.java | 524 +
.../apache/usergrid/persistence/IndexIT.java | 462 +
.../usergrid/persistence/PathQueryIT.java | 164 +
.../usergrid/persistence/PermissionsIT.java | 191 +
.../apache/usergrid/persistence/QueryTest.java | 311 +
.../usergrid/persistence/QueryUtilsTest.java | 41 +
.../apache/usergrid/persistence/SchemaTest.java | 127 +
.../apache/usergrid/persistence/UtilsTest.java | 38 +
.../cassandra/EntityManagerFactoryImplIT.java | 175 +
.../cassandra/QueryProcessorTest.java | 726 +
.../SimpleIndexBucketLocatorImplTest.java | 176 +
.../cassandra/util/TraceTagUnitTest.java | 38 +
.../persistence/entities/SampleEntity.java | 58 +
...EntityLocationRefDistanceComparatorTest.java | 102 +
.../query/AbstractIteratingQueryIT.java | 1299 +
.../persistence/query/AllInCollectionIT.java | 28 +
.../persistence/query/AllInConnectionIT.java | 28 +
.../query/AllInConnectionNoTypeIT.java | 56 +
.../query/IntersectionUnionPagingIT.java | 167 +
.../query/MultiOrderByCollectionIT.java | 28 +
.../MultiOrderByComplexUnionCollectionIT.java | 28 +
.../MultiOrderByComplexUnionConnectionIT.java | 28 +
.../query/MultiOrderByConnectionIT.java | 31 +
.../query/NotOrderByCollectionIT.java | 28 +
.../query/NotOrderByConnectionIT.java | 28 +
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 +
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 +
...leOrderByBoundRangeScanDescCollectionIT.java | 28 +
...leOrderByBoundRangeScanDescConnectionIT.java | 28 +
...eOrderByComplexIntersectionCollectionIT.java | 28 +
...eOrderByComplexIntersectionConnectionIT.java | 29 +
.../SingleOrderByComplexUnionCollectionIT.java | 28 +
.../SingleOrderByComplexUnionConnectionIT.java | 28 +
.../SingleOrderByIntersectionCollectionIT.java | 30 +
.../SingleOrderByIntersectionConnectionIT.java | 30 +
.../SingleOrderByLessThanLimitCollectionIT.java | 28 +
.../SingleOrderByLessThanLimitConnectionIT.java | 28 +
.../SingleOrderByMaxLimitCollectionIT.java | 29 +
.../SingleOrderByMaxLimitConnectionIT.java | 29 +
...SingleOrderByNoIntersectionCollectionIT.java | 28 +
...SingleOrderByNoIntersectionConnectionIT.java | 28 +
.../query/SingleOrderByNotCollectionIT.java | 28 +
.../query/SingleOrderByNotConnectionIT.java | 28 +
...OrderBySameRangeScanGreaterCollectionIT.java | 28 +
...OrderBySameRangeScanGreaterConnectionIT.java | 28 +
...meRangeScanGreaterThanEqualCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessCollectionIT.java | 28 +
...gleOrderBySameRangeScanLessConnectionIT.java | 28 +
...ySameRangeScanLessThanEqualCollectionIT.java | 28 +
...ySameRangeScanLessThanEqualConnectionIT.java | 28 +
.../query/ir/result/AbstractScanColumnTest.java | 84 +
.../query/ir/result/InOrderIterator.java | 115 +
.../ir/result/IntersectionIteratorTest.java | 306 +
.../query/ir/result/IteratorHelper.java | 18 +
.../ir/result/SubtractionIteratorTest.java | 180 +
.../query/ir/result/UnionIteratorTest.java | 466 +
.../persistence/query/tree/GrammarTreeTest.java | 592 +
.../persistence/query/tree/LongLiteralTest.java | 61 +
.../query/tree/StringLiteralTest.java | 87 +
.../system/UsergridSystemMonitorIT.java | 51 +
.../usergrid/utils/ConversionUtilsTest.java | 49 +
.../apache/usergrid/utils/IndexUtilsTest.java | 71 +
.../apache/usergrid/utils/JsonUtilsTest.java | 85 +
.../apache/usergrid/utils/ListUtilsTest.java | 53 +
.../apache/usergrid/utils/MailUtilsTest.java | 90 +
.../org/apache/usergrid/utils/MapUtilsTest.java | 41 +
.../apache/usergrid/utils/TestInflector.java | 81 +
.../apache/usergrid/utils/TimeUtilsTest.java | 60 +
.../apache/usergrid/utils/UUIDUtilsTest.java | 371 +
.../org/apache/usergrid/utils/package-info.java | 18 +
.../test/java/org/usergrid/AbstractCoreIT.java | 45 -
.../src/test/java/org/usergrid/Application.java | 124 -
.../org/usergrid/ConcurrentCoreITSuite.java | 50 -
.../usergrid/ConcurrentCoreIteratorITSuite.java | 62 -
.../org/usergrid/ConcurrentCoreTestSuite.java | 33 -
.../test/java/org/usergrid/CoreApplication.java | 171 -
.../src/test/java/org/usergrid/CoreITSetup.java | 43 -
.../test/java/org/usergrid/CoreITSetupImpl.java | 145 -
.../src/test/java/org/usergrid/CoreITSuite.java | 34 -
.../test/java/org/usergrid/CoreTestSuite.java | 47 -
.../java/org/usergrid/batch/AppArgsTest.java | 52 -
.../batch/BulkJobExecutionUnitTest.java | 209 -
.../java/org/usergrid/batch/BulkTestUtils.java | 38 -
.../batch/ConcurrentSchedulerITSuite.java | 31 -
.../batch/ConcurrentSchedulerTestSuite.java | 19 -
.../org/usergrid/batch/SchedulerITSuite.java | 34 -
.../org/usergrid/batch/SchedulerTestSuite.java | 18 -
.../usergrid/batch/UsergridJobFactoryTest.java | 31 -
.../batch/job/AbstractSchedulerRuntimeIT.java | 78 -
.../usergrid/batch/job/CountdownLatchJob.java | 67 -
.../org/usergrid/batch/job/DelayExecution.java | 104 -
.../org/usergrid/batch/job/DelayHeartbeat.java | 106 -
.../batch/job/FailureJobExceuction.java | 74 -
.../usergrid/batch/job/OnlyOnceExceution.java | 116 -
.../job/OnlyOnceUnlockOnFailExceution.java | 126 -
.../usergrid/batch/job/SchedulerRuntime1IT.java | 70 -
.../usergrid/batch/job/SchedulerRuntime2IT.java | 98 -
.../usergrid/batch/job/SchedulerRuntime3IT.java | 71 -
.../usergrid/batch/job/SchedulerRuntime4IT.java | 68 -
.../usergrid/batch/job/SchedulerRuntime5IT.java | 69 -
.../usergrid/batch/job/SchedulerRuntime6IT.java | 97 -
.../usergrid/batch/job/SchedulerRuntime7IT.java | 74 -
.../usergrid/batch/job/SchedulerRuntime8IT.java | 95 -
.../org/usergrid/batch/job/TestJobListener.java | 121 -
.../usergrid/batch/job/TestJobListenerTest.java | 144 -
.../org/usergrid/batch/job/package-info.java | 18 -
.../clustering/hazelcast/HazelcastTest.java | 111 -
.../count/BatchCountParallelismTest.java | 122 -
.../org/usergrid/count/SimpleBatcherTest.java | 51 -
.../count/common/CountSerDeUtilsTest.java | 68 -
.../org/usergrid/count/common/CountTest.java | 68 -
.../locking/cassandra/HectorLockManagerIT.java | 185 -
.../SingleNodeLockTestSingleNode.java | 168 -
.../zookeeper/AbstractZooKeeperTest.java | 126 -
.../org/usergrid/locking/zookeeper/ZooPut.java | 113 -
.../zookeeper/ZookeeperLockManagerTest.java | 182 -
.../test/java/org/usergrid/mq/MessagesIT.java | 278 -
.../java/org/usergrid/mq/QueuePathsTest.java | 48 -
.../org/usergrid/persistence/CollectionIT.java | 1637 -
.../usergrid/persistence/CoreSchemaManager.java | 66 -
.../org/usergrid/persistence/CounterIT.java | 235 -
.../persistence/EntityConnectionsIT.java | 292 -
.../persistence/EntityDictionaryIT.java | 133 -
.../usergrid/persistence/EntityManagerIT.java | 563 -
.../EntityPropertyComparatorTest.java | 206 -
.../org/usergrid/persistence/EntityTest.java | 100 -
.../java/org/usergrid/persistence/GeoIT.java | 524 -
.../java/org/usergrid/persistence/IndexIT.java | 462 -
.../org/usergrid/persistence/PathQueryIT.java | 164 -
.../org/usergrid/persistence/PermissionsIT.java | 191 -
.../org/usergrid/persistence/QueryTest.java | 311 -
.../usergrid/persistence/QueryUtilsTest.java | 41 -
.../org/usergrid/persistence/SchemaTest.java | 127 -
.../org/usergrid/persistence/UtilsTest.java | 38 -
.../cassandra/EntityManagerFactoryImplIT.java | 175 -
.../cassandra/QueryProcessorTest.java | 726 -
.../SimpleIndexBucketLocatorImplTest.java | 176 -
.../cassandra/util/TraceTagUnitTest.java | 38 -
.../persistence/entities/SampleEntity.java | 58 -
...EntityLocationRefDistanceComparatorTest.java | 102 -
.../query/AbstractIteratingQueryIT.java | 1299 -
.../persistence/query/AllInCollectionIT.java | 28 -
.../persistence/query/AllInConnectionIT.java | 28 -
.../query/AllInConnectionNoTypeIT.java | 56 -
.../query/IntersectionUnionPagingIT.java | 167 -
.../query/MultiOrderByCollectionIT.java | 28 -
.../MultiOrderByComplexUnionCollectionIT.java | 28 -
.../MultiOrderByComplexUnionConnectionIT.java | 28 -
.../query/MultiOrderByConnectionIT.java | 31 -
.../query/NotOrderByCollectionIT.java | 28 -
.../query/NotOrderByConnectionIT.java | 28 -
...gleOrderByBoundRangeScanAscCollectionIT.java | 28 -
...gleOrderByBoundRangeScanAscConnectionIT.java | 28 -
...leOrderByBoundRangeScanDescCollectionIT.java | 28 -
...leOrderByBoundRangeScanDescConnectionIT.java | 28 -
...eOrderByComplexIntersectionCollectionIT.java | 28 -
...eOrderByComplexIntersectionConnectionIT.java | 29 -
.../SingleOrderByComplexUnionCollectionIT.java | 28 -
.../SingleOrderByComplexUnionConnectionIT.java | 28 -
.../SingleOrderByIntersectionCollectionIT.java | 30 -
.../SingleOrderByIntersectionConnectionIT.java | 30 -
.../SingleOrderByLessThanLimitCollectionIT.java | 28 -
.../SingleOrderByLessThanLimitConnectionIT.java | 28 -
.../SingleOrderByMaxLimitCollectionIT.java | 29 -
.../SingleOrderByMaxLimitConnectionIT.java | 29 -
...SingleOrderByNoIntersectionCollectionIT.java | 28 -
...SingleOrderByNoIntersectionConnectionIT.java | 28 -
.../query/SingleOrderByNotCollectionIT.java | 28 -
.../query/SingleOrderByNotConnectionIT.java | 28 -
...OrderBySameRangeScanGreaterCollectionIT.java | 28 -
...OrderBySameRangeScanGreaterConnectionIT.java | 28 -
...meRangeScanGreaterThanEqualCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessCollectionIT.java | 28 -
...gleOrderBySameRangeScanLessConnectionIT.java | 28 -
...ySameRangeScanLessThanEqualCollectionIT.java | 28 -
...ySameRangeScanLessThanEqualConnectionIT.java | 28 -
.../query/ir/result/AbstractScanColumnTest.java | 84 -
.../query/ir/result/InOrderIterator.java | 115 -
.../ir/result/IntersectionIteratorTest.java | 306 -
.../query/ir/result/IteratorHelper.java | 18 -
.../ir/result/SubtractionIteratorTest.java | 180 -
.../query/ir/result/UnionIteratorTest.java | 466 -
.../persistence/query/tree/GrammarTreeTest.java | 592 -
.../persistence/query/tree/LongLiteralTest.java | 61 -
.../query/tree/StringLiteralTest.java | 87 -
.../system/UsergridSystemMonitorIT.java | 51 -
.../org/usergrid/utils/ConversionUtilsTest.java | 49 -
.../java/org/usergrid/utils/IndexUtilsTest.java | 71 -
.../java/org/usergrid/utils/JsonUtilsTest.java | 85 -
.../java/org/usergrid/utils/ListUtilsTest.java | 53 -
.../java/org/usergrid/utils/MailUtilsTest.java | 90 -
.../java/org/usergrid/utils/MapUtilsTest.java | 41 -
.../java/org/usergrid/utils/TestInflector.java | 81 -
.../java/org/usergrid/utils/TimeUtilsTest.java | 60 -
.../java/org/usergrid/utils/UUIDUtilsTest.java | 371 -
.../java/org/usergrid/utils/package-info.java | 18 -
stack/core/src/test/resources/log4j.properties | 16 +-
.../test/resources/usergrid-test-context.xml | 4 +-
.../collection/guice/CollectionModule.java | 4 +-
.../impl/EntityCollectionManagerImpl.java | 78 +-
.../collection/mvcc/stage/write/WriteFig.java | 42 -
.../mvcc/stage/write/WriteUniqueVerify.java | 160 +-
.../persistence/collection/rx/Concurrent.java | 80 -
.../collection/cassandra/CassandraRule.java | 2 +
.../changelog/ChangeLogGeneratorImplTest.java | 4 +-
.../stage/write/WriteUniqueVerifyStageTest.java | 49 +
.../mvcc/stage/write/WriteUniqueVerifyTest.java | 90 +-
.../collection/rx/ConcurrentTest.java | 149 -
.../util/InvalidValueGeneratorTest.java | 48 +
.../graph/serialization/impl/CassUtils.java | 11 +-
.../impl/EdgeMetadataSerializationImpl.java | 6 +-
.../persistence/graph/EdgeManagerIT.java | 135 +-
.../EdgeMetadataSerializationTest.java | 129 +-
stack/launcher/pom.xml | 12 +-
.../java/org/apache/usergrid/launcher/App.java | 288 +
.../apache/usergrid/launcher/AppleUtils.java | 38 +
.../launcher/ClasspathStaticHttpHandler.java | 320 +
.../launcher/CustomJSPTemplateProcessor.java | 137 +
.../usergrid/launcher/EmbeddedServerHelper.java | 193 +
.../org/apache/usergrid/launcher/JarMain.java | 40 +
.../apache/usergrid/launcher/LauncherFrame.java | 461 +
.../usergrid/launcher/LogViewerFrame.java | 104 +
.../org/apache/usergrid/launcher/Server.java | 618 +
.../apache/usergrid/launcher/package-info.java | 18 +
.../main/java/org/usergrid/launcher/App.java | 288 -
.../java/org/usergrid/launcher/AppleUtils.java | 38 -
.../launcher/ClasspathStaticHttpHandler.java | 320 -
.../launcher/CustomJSPTemplateProcessor.java | 137 -
.../usergrid/launcher/EmbeddedServerHelper.java | 193 -
.../java/org/usergrid/launcher/JarMain.java | 40 -
.../org/usergrid/launcher/LauncherFrame.java | 461 -
.../org/usergrid/launcher/LogViewerFrame.java | 104 -
.../main/java/org/usergrid/launcher/Server.java | 618 -
.../org/usergrid/launcher/package-info.java | 18 -
.../src/main/resources/log4j.properties | 14 +-
.../org/apache/usergrid/launcher/dock_icon.png | Bin 0 -> 11592 bytes
.../org/apache/usergrid/launcher/icon_16.png | Bin 0 -> 3273 bytes
.../org/apache/usergrid/launcher/icon_256.png | Bin 0 -> 12578 bytes
.../org/apache/usergrid/launcher/icon_32.png | Bin 0 -> 3862 bytes
.../org/apache/usergrid/launcher/icon_64.png | Bin 0 -> 5079 bytes
.../org/apache/usergrid/launcher/log_viewer.png | Bin 0 -> 6610 bytes
.../org/apache/usergrid/launcher/start.png | Bin 0 -> 9253 bytes
.../apache/usergrid/launcher/start_active.png | Bin 0 -> 9334 bytes
.../apache/usergrid/launcher/status_green.png | Bin 0 -> 2048 bytes
.../org/apache/usergrid/launcher/status_off.png | Bin 0 -> 1847 bytes
.../org/apache/usergrid/launcher/status_red.png | Bin 0 -> 2047 bytes
.../apache/usergrid/launcher/status_yellow.png | Bin 0 -> 2092 bytes
.../org/apache/usergrid/launcher/stop.png | Bin 0 -> 8858 bytes
.../apache/usergrid/launcher/stop_active.png | Bin 0 -> 8844 bytes
.../apache/usergrid/launcher/web_browser.png | Bin 0 -> 4531 bytes
.../org/usergrid/launcher/dock_icon.png | Bin 11592 -> 0 bytes
.../resources/org/usergrid/launcher/icon_16.png | Bin 3273 -> 0 bytes
.../org/usergrid/launcher/icon_256.png | Bin 12578 -> 0 bytes
.../resources/org/usergrid/launcher/icon_32.png | Bin 3862 -> 0 bytes
.../resources/org/usergrid/launcher/icon_64.png | Bin 5079 -> 0 bytes
.../org/usergrid/launcher/log_viewer.png | Bin 6610 -> 0 bytes
.../resources/org/usergrid/launcher/start.png | Bin 9253 -> 0 bytes
.../org/usergrid/launcher/start_active.png | Bin 9334 -> 0 bytes
.../org/usergrid/launcher/status_green.png | Bin 2048 -> 0 bytes
.../org/usergrid/launcher/status_off.png | Bin 1847 -> 0 bytes
.../org/usergrid/launcher/status_red.png | Bin 2047 -> 0 bytes
.../org/usergrid/launcher/status_yellow.png | Bin 2092 -> 0 bytes
.../resources/org/usergrid/launcher/stop.png | Bin 8858 -> 0 bytes
.../org/usergrid/launcher/stop_active.png | Bin 8844 -> 0 bytes
.../org/usergrid/launcher/web_browser.png | Bin 4531 -> 0 bytes
.../resources/usergrid-standalone-context.xml | 2 +-
.../0.0.3/usergrid-java-client-0.0.3.jar | Bin 0 -> 45750 bytes
.../usergrid-java-client-0.0.3.jar.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.jar.sha1 | 1 +
.../0.0.3/usergrid-java-client-0.0.3.pom | 87 +
.../usergrid-java-client-0.0.3.pom.lastUpdated | 5 +
.../0.0.3/usergrid-java-client-0.0.3.pom.sha1 | 1 +
.../maven-metadata-local.xml | 13 +
stack/mongo-emulator/README.txt | 2 +-
stack/mongo-emulator/pom.xml | 14 +-
.../usergrid/mongo/MongoChannelHandler.java | 144 +
.../usergrid/mongo/MongoMessageDecoder.java | 115 +
.../usergrid/mongo/MongoMessageEncoder.java | 46 +
.../org/apache/usergrid/mongo/MongoQuery.java | 30 +
.../org/apache/usergrid/mongo/MongoServer.java | 171 +
.../mongo/MongoServerPipelineFactory.java | 55 +
.../usergrid/mongo/commands/Buildinfo.java | 43 +
.../usergrid/mongo/commands/Collstats.java | 58 +
.../apache/usergrid/mongo/commands/Count.java | 65 +
.../apache/usergrid/mongo/commands/Dbstats.java | 40 +
.../usergrid/mongo/commands/Getlasterror.java | 48 +
.../usergrid/mongo/commands/ListDatabases.java | 51 +
.../usergrid/mongo/commands/MongoCommand.java | 81 +
.../mongo/commands/ReplSetGetStatus.java | 37 +
.../usergrid/mongo/commands/ServerStatus.java | 62 +
.../usergrid/mongo/commands/Whatsmyuri.java | 41 +
.../apache/usergrid/mongo/protocol/Message.java | 191 +
.../apache/usergrid/mongo/protocol/OpCrud.java | 46 +
.../usergrid/mongo/protocol/OpDelete.java | 196 +
.../usergrid/mongo/protocol/OpGetMore.java | 112 +
.../usergrid/mongo/protocol/OpInsert.java | 180 +
.../usergrid/mongo/protocol/OpKillCursors.java | 115 +
.../apache/usergrid/mongo/protocol/OpMsg.java | 77 +
.../apache/usergrid/mongo/protocol/OpQuery.java | 447 +
.../apache/usergrid/mongo/protocol/OpReply.java | 189 +
.../usergrid/mongo/protocol/OpUpdate.java | 206 +
.../usergrid/mongo/query/MongoQueryParser.java | 291 +
.../mongo/testproxy/MongoMessageFrame.java | 55 +
.../testproxy/MongoProxyInboundHandler.java | 197 +
.../testproxy/MongoProxyPipelineFactory.java | 53 +
.../mongo/testproxy/MongoProxyServer.java | 55 +
.../testproxy/MongoProxyServerHandler.java | 58 +
.../apache/usergrid/mongo/utils/BSONUtils.java | 50 +
.../org/usergrid/mongo/MongoChannelHandler.java | 144 -
.../org/usergrid/mongo/MongoMessageDecoder.java | 115 -
.../org/usergrid/mongo/MongoMessageEncoder.java | 46 -
.../java/org/usergrid/mongo/MongoQuery.java | 30 -
.../java/org/usergrid/mongo/MongoServer.java | 171 -
.../mongo/MongoServerPipelineFactory.java | 55 -
.../org/usergrid/mongo/commands/Buildinfo.java | 43 -
.../org/usergrid/mongo/commands/Collstats.java | 58 -
.../java/org/usergrid/mongo/commands/Count.java | 65 -
.../org/usergrid/mongo/commands/Dbstats.java | 40 -
.../usergrid/mongo/commands/Getlasterror.java | 48 -
.../usergrid/mongo/commands/ListDatabases.java | 51 -
.../usergrid/mongo/commands/MongoCommand.java | 81 -
.../mongo/commands/ReplSetGetStatus.java | 37 -
.../usergrid/mongo/commands/ServerStatus.java | 63 -
.../org/usergrid/mongo/commands/Whatsmyuri.java | 41 -
.../org/usergrid/mongo/protocol/Message.java | 191 -
.../org/usergrid/mongo/protocol/OpCrud.java | 46 -
.../org/usergrid/mongo/protocol/OpDelete.java | 196 -
.../org/usergrid/mongo/protocol/OpGetMore.java | 112 -
.../org/usergrid/mongo/protocol/OpInsert.java | 180 -
.../usergrid/mongo/protocol/OpKillCursors.java | 115 -
.../java/org/usergrid/mongo/protocol/OpMsg.java | 77 -
.../org/usergrid/mongo/protocol/OpQuery.java | 447 -
.../org/usergrid/mongo/protocol/OpReply.java | 189 -
.../org/usergrid/mongo/protocol/OpUpdate.java | 206 -
.../usergrid/mongo/query/MongoQueryParser.java | 291 -
.../mongo/testproxy/MongoMessageFrame.java | 55 -
.../testproxy/MongoProxyInboundHandler.java | 197 -
.../testproxy/MongoProxyPipelineFactory.java | 53 -
.../mongo/testproxy/MongoProxyServer.java | 55 -
.../testproxy/MongoProxyServerHandler.java | 58 -
.../org/usergrid/mongo/utils/BSONUtils.java | 50 -
.../usergrid/mongo/AbstractMongoTest.java | 62 +
.../apache/usergrid/mongo/BasicMongoTest.java | 340 +
.../usergrid/mongo/DatabaseInitializer.java | 145 +
.../apache/usergrid/mongo/MongoQueryTest.java | 503 +
.../org/usergrid/mongo/AbstractMongoTest.java | 61 -
.../java/org/usergrid/mongo/BasicMongoTest.java | 340 -
.../org/usergrid/mongo/DatabaseInitializer.java | 145 -
.../java/org/usergrid/mongo/MongoQueryTest.java | 503 -
.../test/resources/usergrid-test-context.xml | 4 +-
stack/pom.xml | 42 +-
stack/query-validator/pom.xml | 240 +-
.../query/validator/ApiServerRunner.java | 212 +
.../validator/DefaultQueryResultsMatcher.java | 32 +
.../usergrid/query/validator/QueryEntity.java | 63 +
.../usergrid/query/validator/QueryRequest.java | 67 +
.../usergrid/query/validator/QueryResponse.java | 105 +
.../query/validator/QueryResultsMatcher.java | 29 +
.../usergrid/query/validator/QueryRunner.java | 31 +
.../validator/QueryValidationConfiguration.java | 94 +
.../query/validator/QueryValidator.java | 78 +
.../usergrid/query/validator/SqliteRunner.java | 192 +
.../query/validator/ApiServerRunner.java | 213 -
.../validator/DefaultQueryResultsMatcher.java | 32 -
.../usergrid/query/validator/QueryEntity.java | 63 -
.../usergrid/query/validator/QueryRequest.java | 67 -
.../usergrid/query/validator/QueryResponse.java | 105 -
.../query/validator/QueryResultsMatcher.java | 29 -
.../usergrid/query/validator/QueryRunner.java | 31 -
.../validator/QueryValidationConfiguration.java | 94 -
.../query/validator/QueryValidator.java | 78 -
.../usergrid/query/validator/SqliteRunner.java | 192 -
.../usergrid-query-validator-context.xml | 6 +-
.../query/validator/AbstractQueryIT.java | 133 +
.../query/validator/CassandraRunner.java | 199 +
.../usergrid/query/validator/QueryITSuite.java | 40 +
.../query/validator/QueryValidationTest.java | 339 +
.../query/validator/QueryValidatorRunner.java | 208 +
.../query/validator/users/UserQueryIT.java | 877 +
.../query/validator/AbstractQueryIT.java | 133 -
.../usergrid/query/validator/QueryITSuite.java | 39 -
.../query/validator/users/UserQueryIT.java | 877 -
.../src/test/resources/log4j.properties | 18 +-
.../test/resources/usergrid-test-context.xml | 10 +-
stack/rest/pom.xml | 24 +-
.../usergrid/rest/AbstractContextResource.java | 164 +
.../org/apache/usergrid/rest/ApiResponse.java | 636 +
.../rest/JacksonCustomMapperProvider.java | 65 +
.../org/apache/usergrid/rest/RootResource.java | 397 +
.../rest/ServerEnvironmentProperties.java | 47 +
.../apache/usergrid/rest/SwaggerServlet.java | 171 +
.../apache/usergrid/rest/SystemResource.java | 110 +
.../usergrid/rest/TextToJsonSwapWriter.java | 119 +
.../rest/applications/ApplicationResource.java | 610 +
.../rest/applications/AuthResource.java | 251 +
.../rest/applications/ServiceResource.java | 662 +
.../applications/assets/AssetsResource.java | 190 +
.../applications/events/EventsResource.java | 69 +
.../rest/applications/queues/QueueResource.java | 204 +
.../queues/QueueSubscriberResource.java | 158 +
.../queues/QueueSubscriptionResource.java | 160 +
.../queues/QueueTransactionsResource.java | 99 +
.../users/AbstractUserExtensionResource.java | 47 +
.../rest/applications/users/UserResource.java | 580 +
.../rest/applications/users/UsersResource.java | 264 +
.../exceptions/AbstractExceptionMapper.java | 106 +
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 +
.../AuthorizationExceptionMapper.java | 36 +
...cateUniquePropertyExistsExceptionMapper.java | 35 +
.../EntityNotFoundExceptionMapper.java | 34 +
...orbiddenServiceOperationExceptionMapper.java | 35 +
.../IllegalArgumentExceptionMapper.java | 32 +
.../exceptions/JsonReadExceptionMapper.java | 35 +
.../exceptions/JsonWriteExceptionMapper.java | 35 +
.../exceptions/ManagementExceptionMapper.java | 38 +
.../usergrid/rest/exceptions/NoOpException.java | 50 +
.../rest/exceptions/NoOpExceptionMapper.java | 32 +
.../NotImplementedExceptionMapper.java | 32 +
.../exceptions/OAuthProblemExceptionMapper.java | 51 +
...rganizationApplicationNotFoundException.java | 39 +
...ationApplicationNotFoundExceptionMapper.java | 16 +
.../exceptions/PersistenceExceptionMapper.java | 27 +
.../exceptions/QueryParseExceptionMapper.java | 34 +
.../exceptions/QueryTokenExceptionMapper.java | 36 +
.../RecentlyUsedPasswordExceptionMapper.java | 21 +
.../rest/exceptions/RedirectionException.java | 27 +
.../exceptions/RedirectionExceptionMapper.java | 30 +
...RequiredPropertyNotFoundExceptionMapper.java | 35 +
.../rest/exceptions/SecurityException.java | 88 +
.../exceptions/SecurityExceptionMapper.java | 45 +
.../rest/exceptions/ServiceExceptionMapper.java | 28 +
.../ServiceResourceNotFoundExceptionMapper.java | 41 +
.../rest/exceptions/ThrowableMapper.java | 26 +
.../TransactionNotFoundExceptionMapper.java | 34 +
.../rest/filters/ContentTypeFilter.java | 323 +
.../rest/filters/JSONPCallbackFilter.java | 66 +
.../usergrid/rest/filters/MeteringFilter.java | 343 +
.../usergrid/rest/filters/TracingFilter.java | 74 +
.../rest/management/ManagementResource.java | 478 +
.../management/metrics/MetricsResource.java | 39 +
.../organizations/OrganizationResource.java | 254 +
.../organizations/OrganizationsResource.java | 192 +
.../applications/ApplicationResource.java | 195 +
.../applications/ApplicationsResource.java | 158 +
.../organizations/users/UsersResource.java | 341 +
.../rest/management/users/UserResource.java | 423 +
.../rest/management/users/UsersResource.java | 211 +
.../organizations/OrganizationsResource.java | 206 +
.../organizations/OrganizationResource.java | 159 +
.../rest/security/CrossOriginRequestFilter.java | 38 +
.../security/SecuredResourceFilterFactory.java | 325 +
.../annotations/RequireAdminUserAccess.java | 31 +
.../annotations/RequireApplicationAccess.java | 34 +
.../annotations/RequireOrganizationAccess.java | 34 +
.../annotations/RequireSystemAccess.java | 31 +
.../security/shiro/RestSecurityManager.java | 60 +
.../ShiroAuthenticationExceptionMapper.java | 59 +
.../shiro/filters/BasicAuthSecurityFilter.java | 111 +
.../ClientCredentialsSecurityFilter.java | 69 +
.../OAuth2AccessTokenSecurityFilter.java | 211 +
.../security/shiro/filters/SecurityFilter.java | 136 +
.../session/HttpRequestSessionManager.java | 87 +
.../session/HttpServletRequestSession.java | 132 +
.../usergrid/rest/test/PropertiesResource.java | 87 +
.../apache/usergrid/rest/utils/CORSUtils.java | 173 +
.../apache/usergrid/rest/utils/JSONPUtils.java | 103 +
.../usergrid/rest/utils/PathingUtils.java | 35 +
.../usergrid/rest/AbstractContextResource.java | 164 -
.../java/org/usergrid/rest/ApiResponse.java | 636 -
.../rest/JacksonCustomMapperProvider.java | 65 -
.../java/org/usergrid/rest/RootResource.java | 397 -
.../rest/ServerEnvironmentProperties.java | 47 -
.../java/org/usergrid/rest/SwaggerServlet.java | 171 -
.../java/org/usergrid/rest/SystemResource.java | 110 -
.../org/usergrid/rest/TextToJsonSwapWriter.java | 119 -
.../rest/applications/ApplicationResource.java | 610 -
.../rest/applications/AuthResource.java | 251 -
.../rest/applications/ServiceResource.java | 662 -
.../applications/assets/AssetsResource.java | 190 -
.../applications/events/EventsResource.java | 69 -
.../rest/applications/queues/QueueResource.java | 204 -
.../queues/QueueSubscriberResource.java | 158 -
.../queues/QueueSubscriptionResource.java | 160 -
.../queues/QueueTransactionsResource.java | 99 -
.../users/AbstractUserExtensionResource.java | 47 -
.../rest/applications/users/UserResource.java | 580 -
.../rest/applications/users/UsersResource.java | 264 -
.../exceptions/AbstractExceptionMapper.java | 106 -
.../usergrid/rest/exceptions/AuthErrorInfo.java | 111 -
.../AuthorizationExceptionMapper.java | 36 -
...cateUniquePropertyExistsExceptionMapper.java | 35 -
.../EntityNotFoundExceptionMapper.java | 34 -
...orbiddenServiceOperationExceptionMapper.java | 35 -
.../IllegalArgumentExceptionMapper.java | 32 -
.../exceptions/JsonReadExceptionMapper.java | 35 -
.../exceptions/JsonWriteExceptionMapper.java | 35 -
.../exceptions/ManagementExceptionMapper.java | 38 -
.../usergrid/rest/exceptions/NoOpException.java | 50 -
.../rest/exceptions/NoOpExceptionMapper.java | 32 -
.../NotImplementedExceptionMapper.java | 32 -
.../exceptions/OAuthProblemExceptionMapper.java | 51 -
...rganizationApplicationNotFoundException.java | 39 -
...ationApplicationNotFoundExceptionMapper.java | 16 -
.../exceptions/PersistenceExceptionMapper.java | 27 -
.../exceptions/QueryParseExceptionMapper.java | 34 -
.../exceptions/QueryTokenExceptionMapper.java | 36 -
.../RecentlyUsedPasswordExceptionMapper.java | 21 -
.../rest/exceptions/RedirectionException.java | 27 -
.../exceptions/RedirectionExceptionMapper.java | 30 -
...RequiredPropertyNotFoundExceptionMapper.java | 35 -
.../rest/exceptions/SecurityException.java | 88 -
.../exceptions/SecurityExceptionMapper.java | 45 -
.../rest/exceptions/ServiceExceptionMapper.java | 28 -
.../ServiceResourceNotFoundExceptionMapper.java | 41 -
.../rest/exceptions/ThrowableMapper.java | 26 -
.../TransactionNotFoundExceptionMapper.java | 34 -
.../rest/filters/ContentTypeFilter.java | 323 -
.../rest/filters/JSONPCallbackFilter.java | 66 -
.../usergrid/rest/filters/MeteringFilter.java | 343 -
.../usergrid/rest/filters/TracingFilter.java | 74 -
.../rest/management/ManagementResource.java | 478 -
.../management/metrics/MetricsResource.java | 39 -
.../organizations/OrganizationResource.java | 254 -
.../organizations/OrganizationsResource.java | 192 -
.../applications/ApplicationResource.java | 195 -
.../applications/ApplicationsResource.java | 158 -
.../organizations/users/UsersResource.java | 341 -
.../rest/management/users/UserResource.java | 423 -
.../rest/management/users/UsersResource.java | 211 -
.../organizations/OrganizationsResource.java | 206 -
.../organizations/OrganizationResource.java | 159 -
.../rest/security/CrossOriginRequestFilter.java | 38 -
.../security/SecuredResourceFilterFactory.java | 325 -
.../annotations/RequireAdminUserAccess.java | 31 -
.../annotations/RequireApplicationAccess.java | 34 -
.../annotations/RequireOrganizationAccess.java | 34 -
.../annotations/RequireSystemAccess.java | 31 -
.../security/shiro/RestSecurityManager.java | 60 -
.../ShiroAuthenticationExceptionMapper.java | 59 -
.../shiro/filters/BasicAuthSecurityFilter.java | 111 -
.../ClientCredentialsSecurityFilter.java | 69 -
.../OAuth2AccessTokenSecurityFilter.java | 211 -
.../security/shiro/filters/SecurityFilter.java | 136 -
.../session/HttpRequestSessionManager.java | 87 -
.../session/HttpServletRequestSession.java | 132 -
.../usergrid/rest/test/PropertiesResource.java | 87 -
.../java/org/usergrid/rest/utils/CORSUtils.java | 173 -
.../org/usergrid/rest/utils/JSONPUtils.java | 103 -
.../org/usergrid/rest/utils/PathingUtils.java | 35 -
.../main/resources/usergrid-rest-context.xml | 12 +-
.../apache/usergrid/rest/TestResource/error.jsp | 17 +
.../apache/usergrid/rest/TestResource/test.jsp | 13 +
.../ApplicationResource/authorize_form.jsp | 43 +
.../applications/ApplicationResource/error.jsp | 17 +
.../users/UserResource/activate.jsp | 16 +
.../applications/users/UserResource/confirm.jsp | 17 +
.../applications/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../applications/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 37 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../ManagementResource/authorize_form.jsp | 43 +
.../management/ManagementResource/error.jsp | 17 +
.../OrganizationResource/activate.jsp | 16 +
.../OrganizationResource/confirm.jsp | 17 +
.../OrganizationResource/error.jsp | 17 +
.../management/users/UserResource/activate.jsp | 16 +
.../management/users/UserResource/confirm.jsp | 17 +
.../management/users/UserResource/error.jsp | 17 +
.../users/UserResource/resetpw_email_form.jsp | 31 +
.../UserResource/resetpw_email_success.jsp | 19 +
.../users/UserResource/resetpw_set_form.jsp | 41 +
.../users/UserResource/resetpw_set_success.jsp | 19 +
.../management/users/UsersResource/error.jsp | 17 +
.../users/UsersResource/resetpw_email_form.jsp | 34 +
.../UsersResource/resetpw_email_success.jsp | 19 +
.../org/usergrid/rest/TestResource/error.jsp | 17 -
.../jsp/org/usergrid/rest/TestResource/test.jsp | 13 -
.../ApplicationResource/authorize_form.jsp | 43 -
.../applications/ApplicationResource/error.jsp | 17 -
.../users/UserResource/activate.jsp | 16 -
.../applications/users/UserResource/confirm.jsp | 17 -
.../applications/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../applications/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 37 -
.../UsersResource/resetpw_email_success.jsp | 19 -
.../ManagementResource/authorize_form.jsp | 43 -
.../management/ManagementResource/error.jsp | 17 -
.../OrganizationResource/activate.jsp | 16 -
.../OrganizationResource/confirm.jsp | 17 -
.../OrganizationResource/error.jsp | 17 -
.../management/users/UserResource/activate.jsp | 16 -
.../management/users/UserResource/confirm.jsp | 17 -
.../management/users/UserResource/error.jsp | 17 -
.../users/UserResource/resetpw_email_form.jsp | 31 -
.../UserResource/resetpw_email_success.jsp | 19 -
.../users/UserResource/resetpw_set_form.jsp | 41 -
.../users/UserResource/resetpw_set_success.jsp | 19 -
.../management/users/UsersResource/error.jsp | 17 -
.../users/UsersResource/resetpw_email_form.jsp | 34 -
.../UsersResource/resetpw_email_success.jsp | 19 -
stack/rest/src/main/webapp/WEB-INF/web.xml | 169 +-
.../apache/usergrid/rest/AbstractRestIT.java | 355 +
.../java/org/apache/usergrid/rest/BasicIT.java | 310 +
.../usergrid/rest/ConcurrentRestITSuite.java | 47 +
.../usergrid/rest/DatabaseInitializer.java | 145 +
.../java/org/apache/usergrid/rest/ITSetup.java | 166 +
.../org/apache/usergrid/rest/RestITSuite.java | 55 +
.../apache/usergrid/rest/TestContextSetup.java | 58 +
.../apache/usergrid/rest/TomcatResource.java | 69 +
.../ApplicationRequestCounterIT.java | 93 +
.../applications/ApplicationResourceIT.java | 531 +
.../rest/applications/DevicesResourceIT.java | 62 +
.../applications/assets/AssetResourceIT.java | 260 +
.../collection/BadGrammarQueryTest.java | 60 +
.../collection/BrowserCompatibilityTest.java | 86 +
.../collection/PagingResourceIT.java | 218 +
.../collection/activities/AndOrQueryTest.java | 176 +
.../collection/activities/OrderByTest.java | 149 +
.../activities/PagingEntitiesTest.java | 119 +
.../collection/activities/PutTest.java | 64 +
.../collection/groups/GeoPagingTest.java | 124 +
.../collection/groups/UpdateGroupIT.java | 108 +
.../applications/events/EventsResourceIT.java | 109 +
.../queues/AbstractQueueResourceIT.java | 468 +
.../queues/QueueResourceLong1IT.java | 130 +
.../queues/QueueResourceLong2IT.java | 82 +
.../queues/QueueResourceLong3IT.java | 184 +
.../queues/QueueResourceShortIT.java | 415 +
.../applications/users/ActivityResourceIT.java | 180 +
.../users/CollectionsResourceIT.java | 199 +
.../users/ConnectionResourceTest.java | 236 +
.../applications/users/GroupResourceIT.java | 270 +
.../applications/users/OwnershipResourceIT.java | 344 +
.../users/PermissionsResourceIT.java | 699 +
.../applications/users/RetrieveUsersTest.java | 66 +
.../rest/applications/users/UserResourceIT.java | 1286 +
.../users/extensions/TestResource.java | 50 +
.../rest/applications/utils/TestUtils.java | 46 +
.../rest/applications/utils/UserRepo.java | 65 +
.../rest/filters/ContentTypeResourceIT.java | 310 +
.../rest/management/ManagementResourceIT.java | 531 +
.../rest/management/RegistrationIT.java | 351 +
.../organizations/AdminEmailEncodingIT.java | 101 +
.../organizations/OrganizationResourceIT.java | 71 +
.../organizations/OrganizationsResourceIT.java | 257 +
.../rest/management/users/MUUserResourceIT.java | 602 +
.../UsersOrganizationsResourceIT.java | 56 +
.../rest/test/PropertiesResourceIT.java | 75 +
.../rest/test/resource/CollectionResource.java | 26 +
.../usergrid/rest/test/resource/Connection.java | 51 +
.../rest/test/resource/CustomCollection.java | 31 +
.../rest/test/resource/EntityResource.java | 104 +
.../apache/usergrid/rest/test/resource/Me.java | 35 +
.../rest/test/resource/NamedResource.java | 185 +
.../rest/test/resource/ResultsParser.java | 22 +
.../rest/test/resource/RootResource.java | 64 +
.../rest/test/resource/SetResource.java | 82 +
.../rest/test/resource/TestContext.java | 170 +
.../rest/test/resource/ValueResource.java | 307 +
.../rest/test/resource/app/Application.java | 72 +
.../usergrid/rest/test/resource/app/Device.java | 48 +
.../usergrid/rest/test/resource/app/User.java | 54 +
.../rest/test/resource/app/UsersCollection.java | 62 +
.../resource/app/queue/DevicesCollection.java | 36 +
.../rest/test/resource/app/queue/Queue.java | 183 +
.../resource/app/queue/QueuesCollection.java | 35 +
.../app/queue/SubscribersCollection.java | 59 +
.../test/resource/app/queue/Transaction.java | 76 +
.../app/queue/TransactionsCollection.java | 35 +
.../rest/test/resource/mgmt/Application.java | 48 +
.../resource/mgmt/ApplicationsCollection.java | 51 +
.../rest/test/resource/mgmt/Management.java | 93 +
.../rest/test/resource/mgmt/Organization.java | 59 +
.../resource/mgmt/OrganizationsCollection.java | 54 +
.../rest/test/security/TestAdminUser.java | 53 +
.../rest/test/security/TestAppUser.java | 53 +
.../usergrid/rest/test/security/TestUser.java | 126 +
.../java/org/usergrid/rest/AbstractRestIT.java | 355 -
.../test/java/org/usergrid/rest/BasicIT.java | 310 -
.../usergrid/rest/ConcurrentRestITSuite.java | 47 -
.../org/usergrid/rest/DatabaseInitializer.java | 145 -
.../test/java/org/usergrid/rest/ITSetup.java | 171 -
.../java/org/usergrid/rest/RestITSuite.java | 55 -
.../org/usergrid/rest/TestContextSetup.java | 58 -
.../java/org/usergrid/rest/TomcatResource.java | 69 -
.../ApplicationRequestCounterIT.java | 93 -
.../applications/ApplicationResourceIT.java | 531 -
.../rest/applications/DevicesResourceIT.java | 62 -
.../applications/assets/AssetResourceIT.java | 260 -
.../collection/BadGrammarQueryTest.java | 60 -
.../collection/BrowserCompatibilityTest.java | 86 -
.../collection/PagingResourceIT.java | 218 -
.../collection/activities/AndOrQueryTest.java | 176 -
.../collection/activities/OrderByTest.java | 149 -
.../activities/PagingEntitiesTest.java | 119 -
.../collection/activities/PutTest.java | 64 -
.../collection/groups/GeoPagingTest.java | 124 -
.../collection/groups/UpdateGroupIT.java | 108 -
.../applications/events/EventsResourceIT.java | 109 -
.../queues/AbstractQueueResourceIT.java | 468 -
.../queues/QueueResourceLong1IT.java | 130 -
.../queues/QueueResourceLong2IT.java | 82 -
.../queues/QueueResourceLong3IT.java | 184 -
.../queues/QueueResourceShortIT.java | 415 -
.../applications/users/ActivityResourceIT.java | 180 -
.../users/CollectionsResourceIT.java | 199 -
.../users/ConnectionResourceTest.java | 236 -
.../applications/users/GroupResourceIT.java | 270 -
.../applications/users/OwnershipResourceIT.java | 344 -
.../users/PermissionsResourceIT.java | 699 -
.../applications/users/RetrieveUsersTest.java | 66 -
.../rest/applications/users/UserResourceIT.java | 1286 -
.../users/extensions/TestResource.java | 50 -
.../rest/applications/utils/TestUtils.java | 46 -
.../rest/applications/utils/UserRepo.java | 65 -
.../rest/filters/ContentTypeResourceIT.java | 310 -
.../rest/management/ManagementResourceIT.java | 531 -
.../rest/management/RegistrationIT.java | 351 -
.../organizations/AdminEmailEncodingIT.java | 101 -
.../organizations/OrganizationResourceIT.java | 70 -
.../organizations/OrganizationsResourceIT.java | 256 -
.../rest/management/users/MUUserResourceIT.java | 602 -
.../UsersOrganizationsResourceIT.java | 56 -
.../rest/test/PropertiesResourceIT.java | 75 -
.../rest/test/resource/CollectionResource.java | 26 -
.../usergrid/rest/test/resource/Connection.java | 51 -
.../rest/test/resource/CustomCollection.java | 31 -
.../rest/test/resource/EntityResource.java | 104 -
.../org/usergrid/rest/test/resource/Me.java | 35 -
.../rest/test/resource/NamedResource.java | 185 -
.../rest/test/resource/ResultsParser.java | 22 -
.../rest/test/resource/RootResource.java | 64 -
.../rest/test/resource/SetResource.java | 82 -
.../rest/test/resource/TestContext.java | 170 -
.../rest/test/resource/ValueResource.java | 307 -
.../rest/test/resource/app/Application.java | 72 -
.../usergrid/rest/test/resource/app/Device.java | 48 -
.../usergrid/rest/test/resource/app/User.java | 54 -
.../rest/test/resource/app/UsersCollection.java | 62 -
.../resource/app/queue/DevicesCollection.java | 36 -
.../rest/test/resource/app/queue/Queue.java | 183 -
.../resource/app/queue/QueuesCollection.java | 35 -
.../app/queue/SubscribersCollection.java | 59 -
.../test/resource/app/queue/Transaction.java | 76 -
.../app/queue/TransactionsCollection.java | 35 -
.../rest/test/resource/mgmt/Application.java | 48 -
.../resource/mgmt/ApplicationsCollection.java | 51 -
.../rest/test/resource/mgmt/Management.java | 93 -
.../rest/test/resource/mgmt/Organization.java | 59 -
.../resource/mgmt/OrganizationsCollection.java | 54 -
.../rest/test/security/TestAdminUser.java | 53 -
.../rest/test/security/TestAppUser.java | 53 -
.../usergrid/rest/test/security/TestUser.java | 126 -
stack/rest/src/test/resources/log4j.properties | 16 +-
.../test/resources/usergrid-test-context.xml | 12 +-
stack/services/groupstest.out | 64570 -----------------
stack/services/pom.xml | 14 +-
.../management/AccountCreationProps.java | 128 +
.../usergrid/management/ActivationState.java | 8 +
.../usergrid/management/ApplicationCreator.java | 14 +
.../usergrid/management/ApplicationInfo.java | 134 +
.../usergrid/management/ManagementService.java | 319 +
.../usergrid/management/OrganizationInfo.java | 185 +
.../management/OrganizationOwnerInfo.java | 53 +
.../management/OrganizationProfile.java | 87 +
.../apache/usergrid/management/UserInfo.java | 149 +
.../cassandra/AccountCreationPropsImpl.java | 157 +
.../cassandra/ApplicationCreatorImpl.java | 77 +
.../cassandra/ManagementServiceImpl.java | 2923 +
.../ApplicationCreationException.java | 26 +
.../exceptions/DisabledAdminUserException.java | 42 +
.../exceptions/DisabledAppUserException.java | 42 +
.../exceptions/IncorrectPasswordException.java | 42 +
.../exceptions/ManagementException.java | 42 +
.../RecentlyUsedPasswordException.java | 27 +
.../UnableToLeaveOrganizationException.java | 42 +
.../UnactivatedAdminUserException.java | 42 +
.../exceptions/UnactivatedAppUserException.java | 42 +
.../UnactivatedOrganizationException.java | 42 +
.../UnconfirmedAdminUserException.java | 42 +
.../usergrid/management/utils/AccountUtils.java | 41 +
.../usergrid/security/AuthPrincipalInfo.java | 71 +
.../usergrid/security/AuthPrincipalType.java | 115 +
.../security/crypto/EncryptionService.java | 70 +
.../security/crypto/EncryptionServiceImpl.java | 208 +
.../security/crypto/command/BcryptCommand.java | 92 +
.../crypto/command/EncryptionCommand.java | 49 +
.../security/crypto/command/Md5HashCommand.java | 61 +
.../crypto/command/PlainTextCommand.java | 64 +
.../crypto/command/SaltedHasherCommand.java | 67 +
.../crypto/command/Sha1HashCommand.java | 73 +
.../usergrid/security/oauth/AccessInfo.java | 187 +
.../security/oauth/ClientCredentialsInfo.java | 93 +
.../usergrid/security/oauth/OAuthProxy.java | 43 +
.../security/oauth/OAuthProxyFactory.java | 31 +
.../security/providers/AbstractProvider.java | 61 +
.../security/providers/FacebookProvider.java | 183 +
.../security/providers/FoursquareProvider.java | 159 +
.../providers/PingIdentityProvider.java | 143 +
.../security/providers/SignInAsProvider.java | 19 +
.../providers/SignInProviderFactory.java | 51 +
.../security/salt/NoOpSaltProvider.java | 36 +
.../security/salt/PropertiesSaltProvider.java | 53 +
.../usergrid/security/salt/SaltProvider.java | 31 +
.../security/shiro/CustomPermission.java | 225 +
.../shiro/CustomPermissionResolver.java | 29 +
.../shiro/PrincipalCredentialsToken.java | 139 +
.../apache/usergrid/security/shiro/Realm.java | 540 +
.../AbstractAccessTokenCredentials.java | 33 +
.../credentials/AbstractClientCredentials.java | 28 +
.../AbstractPasswordCredentials.java | 33 +
.../credentials/AccessTokenCredentials.java | 22 +
.../shiro/credentials/AdminUserAccessToken.java | 24 +
.../shiro/credentials/AdminUserCredentials.java | 21 +
.../shiro/credentials/AdminUserPassword.java | 24 +
.../credentials/ApplicationAccessToken.java | 24 +
.../ApplicationClientCredentials.java | 24 +
.../credentials/ApplicationCredentials.java | 21 +
.../shiro/credentials/ApplicationGuest.java | 24 +
.../credentials/ApplicationUserAccessToken.java | 24 +
.../credentials/ApplicationUserCredentials.java | 21 +
.../credentials/ApplicationUserPassword.java | 24 +
.../shiro/credentials/ClientCredentials.java | 24 +
.../credentials/OrganizationAccessToken.java | 24 +
.../OrganizationClientCredentials.java | 24 +
.../credentials/OrganizationCredentials.java | 21 +
.../shiro/credentials/PasswordCredentials.java | 22 +
.../shiro/credentials/PrincipalCredentials.java | 21 +
.../shiro/principals/AdminUserPrincipal.java | 29 +
.../principals/ApplicationGuestPrincipal.java | 48 +
.../shiro/principals/ApplicationPrincipal.java | 48 +
.../principals/ApplicationUserPrincipal.java | 35 +
.../shiro/principals/OrganizationPrincipal.java | 48 +
.../shiro/principals/PrincipalIdentifier.java | 51 +
.../shiro/principals/UserPrincipal.java | 69 +
.../security/shiro/utils/SubjectUtils.java | 449 +
.../usergrid/security/tokens/TokenCategory.java | 83 +
.../usergrid/security/tokens/TokenInfo.java | 125 +
.../usergrid/security/tokens/TokenService.java | 39 +
.../tokens/cassandra/TokenServiceImpl.java | 627 +
.../tokens/exceptions/BadTokenException.java | 32 +
.../exceptions/ExpiredTokenException.java | 32 +
.../exceptions/InvalidTokenException.java | 32 +
.../tokens/exceptions/TokenException.java | 35 +
.../services/AbstractCollectionService.java | 571 +
.../services/AbstractConnectionsService.java | 520 +
.../AbstractPathBasedColllectionService.java | 148 +
.../usergrid/services/AbstractService.java | 1306 +
.../org/apache/usergrid/services/Service.java | 49 +
.../apache/usergrid/services/ServiceAction.java | 21 +
.../ServiceCollectionEventListener.java | 22 +
.../usergrid/services/ServiceContext.java | 448 +
.../services/ServiceExecutionEvent.java | 79 +
.../services/ServiceExecutionEventListener.java | 22 +
.../apache/usergrid/services/ServiceInfo.java | 438 +
.../usergrid/services/ServiceManager.java | 431 +
.../services/ServiceManagerFactory.java | 131 +
.../usergrid/services/ServiceParameter.java | 452 +
.../usergrid/services/ServicePayload.java | 199 +
.../usergrid/services/ServiceRequest.java | 372 +
.../usergrid/services/ServiceResults.java | 304 +
.../apache/usergrid/services/ServiceUtils.java | 21 +
.../services/activities/ActivitiesService.java | 33 +
.../applications/ApplicationsService.java | 215 +
.../usergrid/services/assets/AssetsService.java | 57 +
.../services/assets/data/AssetMimeHandler.java | 90 +
.../services/assets/data/AssetUtils.java | 107 +
.../services/assets/data/BinaryStore.java | 27 +
.../assets/data/LocalFileBinaryStore.java | 85 +
.../services/assets/data/S3BinaryStore.java | 202 +
.../services/devices/DevicesService.java | 51 +
.../services/devices/users/UsersService.java | 32 +
.../ForbiddenServiceOperationException.java | 41 +
.../services/exceptions/ServiceException.java | 45 +
.../exceptions/ServiceInvocationException.java | 83 +
.../ServiceResourceNotFoundException.java | 39 +
.../UndefinedServiceEntityTypeException.java | 45 +
.../UnsupportedServiceOperationException.java | 39 +
.../generic/GenericCollectionService.java | 27 +
.../generic/GenericConnectionsService.java | 27 +
.../services/generic/RootCollectionService.java | 27 +
.../usergrid/services/groups/GroupsService.java | 224 +
.../groups/activities/ActivitiesService.java | 74 +
.../services/groups/roles/RolesService.java | 32 +
.../services/groups/users/UsersService.java | 32 +
.../users/activities/ActivitiesService.java | 84 +
.../groups/users/devices/DevicesService.java | 32 +
.../services/messages/MessagesService.java | 33 +
.../usergrid/services/roles/RolesService.java | 236 +
.../services/roles/groups/GroupsService.java | 32 +
.../services/roles/users/UsersService.java | 84 +
.../usergrid/services/users/UsersService.java | 287 +
.../users/activities/ActivitiesService.java | 142 +
.../services/users/devices/DevicesService.java | 32 +
.../users/following/FollowingService.java | 47 +
.../services/users/groups/GroupsService.java | 32 +
.../services/users/roles/RolesService.java | 84 +
.../org/apache/usergrid/utils/PythonUtils.java | 102 +
.../management/AccountCreationProps.java | 119 -
.../usergrid/management/ActivationState.java | 8 -
.../usergrid/management/ApplicationCreator.java | 14 -
.../usergrid/management/ApplicationInfo.java | 134 -
.../usergrid/management/ManagementService.java | 319 -
.../usergrid/management/OrganizationInfo.java | 185 -
.../management/OrganizationOwnerInfo.java | 53 -
.../management/OrganizationProfile.java | 87 -
.../java/org/usergrid/management/UserInfo.java | 149 -
.../cassandra/AccountCreationPropsImpl.java | 112 -
.../cassandra/ApplicationCreatorImpl.java | 77 -
.../cassandra/ManagementServiceImpl.java | 2923 -
.../ApplicationCreationException.java | 26 -
.../exceptions/DisabledAdminUserException.java | 42 -
.../exceptions/DisabledAppUserException.java | 42 -
.../exceptions/IncorrectPasswordException.java | 42 -
.../exceptions/ManagementException.java | 42 -
.../RecentlyUsedPasswordException.java | 27 -
.../UnableToLeaveOrganizationException.java | 42 -
.../UnactivatedAdminUserException.java | 42 -
.../exceptions/UnactivatedAppUserException.java | 42 -
.../UnactivatedOrganizationException.java | 42 -
.../UnconfirmedAdminUserException.java | 42 -
.../usergrid/management/utils/AccountUtils.java | 42 -
.../usergrid/security/AuthPrincipalInfo.java | 71 -
.../usergrid/security/AuthPrincipalType.java | 115 -
.../security/crypto/EncryptionService.java | 70 -
.../security/crypto/EncryptionServiceImpl.java | 208 -
.../security/crypto/command/BcryptCommand.java | 92 -
.../crypto/command/EncryptionCommand.java | 49 -
.../security/crypto/command/Md5HashCommand.java | 61 -
.../crypto/command/PlainTextCommand.java | 64 -
.../crypto/command/SaltedHasherCommand.java | 67 -
.../crypto/command/Sha1HashCommand.java | 73 -
.../org/usergrid/security/oauth/AccessInfo.java | 187 -
.../security/oauth/ClientCredentialsInfo.java | 93 -
.../org/usergrid/security/oauth/OAuthProxy.java | 43 -
.../security/oauth/OAuthProxyFactory.java | 31 -
.../security/providers/AbstractProvider.java | 61 -
.../security/providers/FacebookProvider.java | 183 -
.../security/providers/FoursquareProvider.java | 159 -
.../providers/PingIdentityProvider.java | 143 -
.../security/providers/SignInAsProvider.java | 19 -
.../providers/SignInProviderFactory.java | 51 -
.../security/salt/NoOpSaltProvider.java | 36 -
.../security/salt/PropertiesSaltProvider.java | 53 -
.../usergrid/security/salt/SaltProvider.java | 31 -
.../security/shiro/CustomPermission.java | 225 -
.../shiro/CustomPermissionResolver.java | 29 -
.../shiro/PrincipalCredentialsToken.java | 139 -
.../java/org/usergrid/security/shiro/Realm.java | 540 -
.../AbstractAccessTokenCredentials.java | 33 -
.../credentials/AbstractClientCredentials.java | 28 -
.../AbstractPasswordCredentials.java | 33 -
.../credentials/AccessTokenCredentials.java | 22 -
.../shiro/credentials/AdminUserAccessToken.java | 24 -
.../shiro/credentials/AdminUserCredentials.java | 21 -
.../shiro/credentials/AdminUserPassword.java | 24 -
.../credentials/ApplicationAccessToken.java | 24 -
.../ApplicationClientCredentials.java | 24 -
.../credentials/ApplicationCredentials.java | 21 -
.../shiro/credentials/ApplicationGuest.java | 24 -
.../credentials/ApplicationUserAccessToken.java | 24 -
.../credentials/ApplicationUserCredentials.java | 21 -
.../credentials/ApplicationUserPassword.java | 24 -
.../shiro/credentials/ClientCredentials.java | 24 -
.../credentials/OrganizationAccessToken.java | 24 -
.../OrganizationClientCredentials.java | 24 -
.../credentials/OrganizationCredentials.java | 21 -
.../shiro/credentials/PasswordCredentials.java | 22 -
.../shiro/credentials/PrincipalCredentials.java | 21 -
.../shiro/principals/AdminUserPrincipal.java | 29 -
.../principals/ApplicationGuestPrincipal.java | 48 -
.../shiro/principals/ApplicationPrincipal.java | 48 -
.../principals/ApplicationUserPrincipal.java | 35 -
.../shiro/principals/OrganizationPrincipal.java | 48 -
.../shiro/principals/PrincipalIdentifier.java | 51 -
.../shiro/principals/UserPrincipal.java | 69 -
.../security/shiro/utils/SubjectUtils.java | 449 -
.../usergrid/security/tokens/TokenCategory.java | 83 -
.../org/usergrid/security/tokens/TokenInfo.java | 125 -
.../usergrid/security/tokens/TokenService.java | 39 -
.../tokens/cassandra/TokenServiceImpl.java | 627 -
.../tokens/exceptions/BadTokenException.java | 32 -
.../exceptions/ExpiredTokenException.java | 32 -
.../exceptions/InvalidTokenException.java | 32 -
.../tokens/exceptions/TokenException.java | 35 -
.../services/AbstractCollectionService.java | 571 -
.../services/AbstractConnectionsService.java | 521 -
.../AbstractPathBasedColllectionService.java | 149 -
.../org/usergrid/services/AbstractService.java | 1306 -
.../java/org/usergrid/services/Service.java | 49 -
.../org/usergrid/services/ServiceAction.java | 21 -
.../ServiceCollectionEventListener.java | 22 -
.../org/usergrid/services/ServiceContext.java | 449 -
.../services/ServiceExecutionEvent.java | 79 -
.../services/ServiceExecutionEventListener.java | 22 -
.../java/org/usergrid/services/ServiceInfo.java | 438 -
.../org/usergrid/services/ServiceManager.java | 431 -
.../services/ServiceManagerFactory.java | 131 -
.../org/usergrid/services/ServiceParameter.java | 452 -
.../org/usergrid/services/ServicePayload.java | 199 -
.../org/usergrid/services/ServiceRequest.java | 372 -
.../org/usergrid/services/ServiceResults.java | 304 -
.../org/usergrid/services/ServiceUtils.java | 21 -
.../services/activities/ActivitiesService.java | 33 -
.../applications/ApplicationsService.java | 215 -
.../usergrid/services/assets/AssetsService.java | 57 -
.../services/assets/data/AssetMimeHandler.java | 90 -
.../services/assets/data/AssetUtils.java | 107 -
.../services/assets/data/BinaryStore.java | 27 -
.../assets/data/LocalFileBinaryStore.java | 85 -
.../services/assets/data/S3BinaryStore.java | 202 -
.../services/devices/DevicesService.java | 51 -
.../services/devices/users/UsersService.java | 32 -
.../ForbiddenServiceOperationException.java | 41 -
.../services/exceptions/ServiceException.java | 45 -
.../exceptions/ServiceInvocationException.java | 83 -
.../ServiceResourceNotFoundException.java | 39 -
.../UndefinedServiceEntityTypeException.java | 45 -
.../UnsupportedServiceOperationException.java | 39 -
.../generic/GenericCollectionService.java | 27 -
.../generic/GenericConnectionsService.java | 27 -
.../services/generic/RootCollectionService.java | 27 -
.../usergrid/services/groups/GroupsService.java | 224 -
.../groups/activities/ActivitiesService.java | 74 -
.../services/groups/roles/RolesService.java | 32 -
.../services/groups/users/UsersService.java | 32 -
.../users/activities/ActivitiesService.java | 84 -
.../groups/users/devices/DevicesService.java | 32 -
.../services/messages/MessagesService.java | 33 -
.../usergrid/services/roles/RolesService.java | 236 -
.../services/roles/groups/GroupsService.java | 32 -
.../services/roles/users/UsersService.java | 84 -
.../usergrid/services/users/UsersService.java | 287 -
.../users/activities/ActivitiesService.java | 142 -
.../services/users/devices/DevicesService.java | 32 -
.../users/following/FollowingService.java | 47 -
.../services/users/groups/GroupsService.java | 32 -
.../services/users/roles/RolesService.java | 84 -
.../java/org/usergrid/utils/PythonUtils.java | 102 -
.../pyusergrid/services/pytest/PytestService.py | 4 +-
.../python/pyusergrid/services/pytest/test.py | 2 +-
stack/services/src/main/python/test/test.py | 2 +-
.../resources/usergrid-services-context.xml | 18 +-
.../test/java/baas/io/simple/SimpleService.java | 2 +-
.../usergrid/ConcurrentServiceITSuite.java | 43 +
.../org/apache/usergrid/ServiceApplication.java | 188 +
.../org/apache/usergrid/ServiceITSetup.java | 44 +
.../org/apache/usergrid/ServiceITSetupImpl.java | 129 +
.../org/apache/usergrid/ServiceITSuite.java | 41 +
.../apache/usergrid/management/EmailFlowIT.java | 419 +
.../management/ManagementTestHelper.java | 40 +
.../usergrid/management/MockImapClient.java | 83 +
.../usergrid/management/OrganizationIT.java | 229 +
.../org/apache/usergrid/management/RoleIT.java | 97 +
.../cassandra/ApplicationCreatorIT.java | 66 +
.../cassandra/ManagementServiceIT.java | 729 +
.../cassandra/ManagementTestHelperImpl.java | 85 +
.../org/apache/usergrid/python/JythonTest.java | 38 +
.../usergrid/security/CustomResolverTest.java | 169 +
.../crypto/EncryptionServiceImplTest.java | 170 +
.../crypto/command/BcryptCommandTest.java | 165 +
.../crypto/command/Md5HashCommandTest.java | 71 +
.../crypto/command/Sha1HashCommandTest.java | 67 +
.../security/providers/FacebookProviderIT.java | 81 +
.../providers/PingIdentityProviderIT.java | 63 +
.../security/tokens/TokenServiceIT.java | 440 +
.../usergrid/services/AbstractServiceIT.java | 38 +
.../usergrid/services/ActivitiesServiceIT.java | 111 +
.../services/ApplicationsServiceIT.java | 35 +
.../usergrid/services/CollectionServiceIT.java | 290 +
.../usergrid/services/ConnectionsServiceIT.java | 82 +
.../usergrid/services/GroupServiceIT.java | 80 +
.../usergrid/services/RolesServiceIT.java | 279 +
.../usergrid/services/ServiceFactoryIT.java | 57 +
.../usergrid/services/ServiceInfoTest.java | 108 +
.../usergrid/services/ServiceInvocationIT.java | 145 +
.../usergrid/services/ServiceRequestIT.java | 78 +
.../usergrid/services/UsersServiceIT.java | 52 +
.../services/assets/data/AssetUtilsTest.java | 44 +
.../org/usergrid/ConcurrentServiceITSuite.java | 43 -
.../java/org/usergrid/ServiceApplication.java | 188 -
.../test/java/org/usergrid/ServiceITSetup.java | 44 -
.../java/org/usergrid/ServiceITSetupImpl.java | 129 -
.../test/java/org/usergrid/ServiceITSuite.java | 41 -
.../org/usergrid/management/EmailFlowIT.java | 419 -
.../management/ManagementTestHelper.java | 40 -
.../org/usergrid/management/MockImapClient.java | 83 -
.../org/usergrid/management/OrganizationIT.java | 229 -
.../java/org/usergrid/management/RoleIT.java | 97 -
.../cassandra/ApplicationCreatorIT.java | 66 -
.../cassandra/ManagementServiceIT.java | 729 -
.../cassandra/ManagementTestHelperImpl.java | 85 -
.../java/org/usergrid/python/JythonTest.java | 38 -
.../usergrid/security/CustomResolverTest.java | 169 -
.../crypto/EncryptionServiceImplTest.java | 170 -
.../crypto/command/BcryptCommandTest.java | 165 -
.../crypto/command/Md5HashCommandTest.java | 71 -
.../crypto/command/Sha1HashCommandTest.java | 67 -
.../security/providers/FacebookProviderIT.java | 81 -
.../providers/PingIdentityProviderIT.java | 63 -
.../security/tokens/TokenServiceIT.java | 440 -
.../usergrid/services/AbstractServiceIT.java | 38 -
.../usergrid/services/ActivitiesServiceIT.java | 111 -
.../services/ApplicationsServiceIT.java | 35 -
.../usergrid/services/CollectionServiceIT.java | 290 -
.../usergrid/services/ConnectionsServiceIT.java | 82 -
.../org/usergrid/services/GroupServiceIT.java | 80 -
.../org/usergrid/services/RolesServiceIT.java | 279 -
.../org/usergrid/services/ServiceFactoryIT.java | 57 -
.../org/usergrid/services/ServiceInfoTest.java | 108 -
.../usergrid/services/ServiceInvocationIT.java | 145 -
.../org/usergrid/services/ServiceRequestIT.java | 78 -
.../org/usergrid/services/UsersServiceIT.java | 52 -
.../services/assets/data/AssetUtilsTest.java | 44 -
.../src/test/resources/log4j.properties | 14 +-
.../test/resources/usergrid-test-context.xml | 8 +-
stack/test-utils/pom.xml | 8 +-
.../apache/usergrid/NoExitSecurityManager.java | 64 +
.../usergrid/cassandra/AvailablePortFinder.java | 211 +
.../usergrid/cassandra/CassandraResource.java | 505 +
.../usergrid/cassandra/ClearShiroSubject.java | 31 +
.../apache/usergrid/cassandra/Concurrent.java | 15 +
.../cassandra/ConcurrentJunitRunner.java | 75 +
.../usergrid/cassandra/ConcurrentSuite.java | 101 +
.../apache/usergrid/cassandra/DataControl.java | 17 +
.../apache/usergrid/cassandra/DataLoader.java | 9 +
.../usergrid/cassandra/SchemaManager.java | 18 +
.../org/usergrid/NoExitSecurityManager.java | 64 -
.../usergrid/cassandra/AvailablePortFinder.java | 211 -
.../usergrid/cassandra/CassandraResource.java | 505 -
.../usergrid/cassandra/ClearShiroSubject.java | 31 -
.../java/org/usergrid/cassandra/Concurrent.java | 15 -
.../cassandra/ConcurrentJunitRunner.java | 75 -
.../org/usergrid/cassandra/ConcurrentSuite.java | 101 -
.../org/usergrid/cassandra/DataControl.java | 17 -
.../java/org/usergrid/cassandra/DataLoader.java | 9 -
.../org/usergrid/cassandra/SchemaManager.java | 18 -
.../cassandra/AnotherCassandraResourceIT.java | 68 +
.../cassandra/CassandraResourceITSuite.java | 25 +
.../cassandra/CassandraResourceTest.java | 104 +
.../usergrid/cassandra/FakeSchemaManager.java | 32 +
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 +
.../YetAnotherCassandraResourceIT.java | 70 +
.../cassandra/AnotherCassandraResourceIT.java | 68 -
.../cassandra/CassandraResourceITSuite.java | 25 -
.../cassandra/CassandraResourceTest.java | 104 -
.../usergrid/cassandra/FakeSchemaManager.java | 32 -
.../usergrid/cassandra/OkThisIsTheLastIT.java | 76 -
.../YetAnotherCassandraResourceIT.java | 70 -
.../test/resources/usergrid-test-context.xml | 6 +-
stack/tools/README.md | 4 +-
stack/tools/pom.xml | 16 +-
.../java/org/apache/usergrid/tools/ApiDoc.java | 114 +
.../org/apache/usergrid/tools/AppAudit.java | 231 +
.../org/apache/usergrid/tools/AppNameFix.java | 109 +
.../java/org/apache/usergrid/tools/Cli.java | 269 +
.../java/org/apache/usergrid/tools/Command.java | 99 +
.../org/apache/usergrid/tools/CredExport.java | 122 +
.../apache/usergrid/tools/DupAdminRepair.java | 310 +
.../org/apache/usergrid/tools/DupOrgRepair.java | 266 +
.../apache/usergrid/tools/EntityCleanup.java | 176 +
.../usergrid/tools/EntityInsertBenchMark.java | 273 +
.../usergrid/tools/EntityReadBenchMark.java | 360 +
.../org/apache/usergrid/tools/EntityUpdate.java | 191 +
.../java/org/apache/usergrid/tools/Export.java | 431 +
.../usergrid/tools/ExportDataCreator.java | 105 +
.../usergrid/tools/ExportingToolBase.java | 183 +
.../java/org/apache/usergrid/tools/Import.java | 545 +
.../org/apache/usergrid/tools/ImportFB.java | 101 +
.../org/apache/usergrid/tools/IndexRebuild.java | 206 +
.../java/org/apache/usergrid/tools/Metrics.java | 213 +
.../usergrid/tools/OrganizationExport.java | 117 +
.../apache/usergrid/tools/PopulateSample.java | 142 +
.../apache/usergrid/tools/ResetSuperUser.java | 105 +
.../java/org/apache/usergrid/tools/SetupDB.java | 57 +
.../java/org/apache/usergrid/tools/Test.java | 53 +
.../org/apache/usergrid/tools/ToolBase.java | 246 +
.../usergrid/tools/UniqueIndexCleanup.java | 381 +
.../org/apache/usergrid/tools/UserManager.java | 45 +
.../apache/usergrid/tools/WarehouseExport.java | 516 +
.../apache/usergrid/tools/WarehouseUpsert.java | 153 +
.../usergrid/tools/apidoc/swagger/Api.java | 92 +
.../tools/apidoc/swagger/ApiListing.java | 145 +
.../tools/apidoc/swagger/ApiOperation.java | 247 +
.../tools/apidoc/swagger/ApiOperationError.java | 60 +
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 +
.../apidoc/swagger/ApiParamAllowableValues.java | 62 +
.../apache/usergrid/tools/bean/AppScore.java | 82 +
.../apache/usergrid/tools/bean/ExportOrg.java | 69 +
.../apache/usergrid/tools/bean/MetricLine.java | 82 +
.../apache/usergrid/tools/bean/MetricQuery.java | 93 +
.../apache/usergrid/tools/bean/MetricSort.java | 26 +
.../apache/usergrid/tools/bean/OrgScore.java | 93 +
.../main/java/org/usergrid/tools/ApiDoc.java | 114 -
.../main/java/org/usergrid/tools/AppAudit.java | 231 -
.../java/org/usergrid/tools/AppNameFix.java | 109 -
.../src/main/java/org/usergrid/tools/Cli.java | 269 -
.../main/java/org/usergrid/tools/Command.java | 99 -
.../java/org/usergrid/tools/CredExport.java | 122 -
.../java/org/usergrid/tools/DupAdminRepair.java | 310 -
.../java/org/usergrid/tools/DupOrgRepair.java | 266 -
.../java/org/usergrid/tools/EntityCleanup.java | 176 -
.../usergrid/tools/EntityInsertBenchMark.java | 273 -
.../org/usergrid/tools/EntityReadBenchMark.java | 360 -
.../java/org/usergrid/tools/EntityUpdate.java | 191 -
.../main/java/org/usergrid/tools/Export.java | 431 -
.../org/usergrid/tools/ExportDataCreator.java | 105 -
.../org/usergrid/tools/ExportingToolBase.java | 183 -
.../main/java/org/usergrid/tools/Import.java | 545 -
.../main/java/org/usergrid/tools/ImportFB.java | 101 -
.../java/org/usergrid/tools/IndexRebuild.java | 206 -
.../main/java/org/usergrid/tools/Metrics.java | 213 -
.../org/usergrid/tools/OrganizationExport.java | 117 -
.../java/org/usergrid/tools/PopulateSample.java | 142 -
.../java/org/usergrid/tools/ResetSuperUser.java | 105 -
.../main/java/org/usergrid/tools/SetupDB.java | 57 -
.../src/main/java/org/usergrid/tools/Test.java | 53 -
.../main/java/org/usergrid/tools/ToolBase.java | 246 -
.../org/usergrid/tools/UniqueIndexCleanup.java | 381 -
.../java/org/usergrid/tools/UserManager.java | 45 -
.../org/usergrid/tools/WarehouseExport.java | 516 -
.../org/usergrid/tools/WarehouseUpsert.java | 153 -
.../org/usergrid/tools/apidoc/swagger/Api.java | 92 -
.../tools/apidoc/swagger/ApiListing.java | 145 -
.../tools/apidoc/swagger/ApiOperation.java | 247 -
.../tools/apidoc/swagger/ApiOperationError.java | 60 -
.../usergrid/tools/apidoc/swagger/ApiParam.java | 184 -
.../apidoc/swagger/ApiParamAllowableValues.java | 62 -
.../java/org/usergrid/tools/bean/AppScore.java | 82 -
.../java/org/usergrid/tools/bean/ExportOrg.java | 69 -
.../org/usergrid/tools/bean/MetricLine.java | 82 -
.../org/usergrid/tools/bean/MetricQuery.java | 93 -
.../org/usergrid/tools/bean/MetricSort.java | 26 -
.../java/org/usergrid/tools/bean/OrgScore.java | 93 -
stack/tools/src/main/resources/log4j.xml | 2 +-
stack/websocket/pom.xml | 12 +-
.../websocket/WebSocketChannelHandler.java | 357 +
.../usergrid/websocket/WebSocketKeyStore.java | 49 +
.../usergrid/websocket/WebSocketServer.java | 195 +
.../websocket/WebSocketServerIndexPage.java | 71 +
.../WebSocketServerPipelineFactory.java | 75 +
.../websocket/WebSocketSslContextFactory.java | 62 +
.../websocket/WebSocketChannelHandler.java | 357 -
.../usergrid/websocket/WebSocketKeyStore.java | 49 -
.../org/usergrid/websocket/WebSocketServer.java | 195 -
.../websocket/WebSocketServerIndexPage.java | 71 -
.../WebSocketServerPipelineFactory.java | 75 -
.../websocket/WebSocketSslContextFactory.java | 62 -
.../usergrid/websocket/ExampleListener.java | 41 +
.../websocket/SimpleMessageProducer.java | 61 +
.../usergrid/websocket/WebSocketServerTest.java | 43 +
.../org/usergrid/websocket/ExampleListener.java | 41 -
.../websocket/SimpleMessageProducer.java | 61 -
.../usergrid/websocket/WebSocketServerTest.java | 42 -
.../test/resources/testApplicationContext.xml | 20 +-
2327 files changed, 177331 insertions(+), 270094 deletions(-)
----------------------------------------------------------------------
[30/50] [abbrv] git commit: Cleaned up cassandra write timestamps
Posted by sn...@apache.org.
Cleaned up cassandra write timestamps
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/d312b316
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/d312b316
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/d312b316
Branch: refs/heads/optimistic-tx-semantics
Commit: d312b31657cf78045021f2918d9bc22cd99c3b50
Parents: 85ffe7b
Author: Todd Nine <tn...@apigee.com>
Authored: Tue Feb 11 18:09:46 2014 -0700
Committer: Todd Nine <tn...@apigee.com>
Committed: Tue Feb 11 18:09:46 2014 -0700
----------------------------------------------------------------------
.../graph/serialization/impl/CassUtils.java | 11 +-
.../impl/EdgeMetadataSerializationImpl.java | 6 +-
.../EdgeMetadataSerializationTest.java | 129 +++++++++++++++++--
3 files changed, 122 insertions(+), 24 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d312b316/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/CassUtils.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/CassUtils.java b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/CassUtils.java
index 7d6c70e..f49d832 100644
--- a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/CassUtils.java
+++ b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/CassUtils.java
@@ -34,18 +34,9 @@ public class CassUtils {
* @param version
* @return
*/
- public static long getDeleteTimestamp(UUID version){
-// return version.timestamp()+1;
+ public static long getTimestamp( UUID version ){
return version.timestamp();
}
- /**
- * Get the write timestamp from a version
- * @param version
- * @return
- */
- public static long getWriteTimestamp(UUID version){
- return version.timestamp();
- }
}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d312b316/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/EdgeMetadataSerializationImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/EdgeMetadataSerializationImpl.java b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/EdgeMetadataSerializationImpl.java
index c2aadb2..ed3cd0b 100644
--- a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/EdgeMetadataSerializationImpl.java
+++ b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/serialization/impl/EdgeMetadataSerializationImpl.java
@@ -134,7 +134,7 @@ public class EdgeMetadataSerializationImpl implements EdgeMetadataSerialization,
final Id source = edge.getSourceNode();
final Id target = edge.getTargetNode();
final String edgeType = edge.getType();
- final long timestamp = CassUtils.getWriteTimestamp( edge.getVersion() );
+ final long timestamp = CassUtils.getTimestamp( edge.getVersion() );
//add source->target edge type to meta data
@@ -213,7 +213,7 @@ public class EdgeMetadataSerializationImpl implements EdgeMetadataSerialization,
final UUID version,
final MultiTennantColumnFamily<OrganizationScope, Id, String> cf ) {
- final long timestamp = CassUtils.getDeleteTimestamp( version );
+ final long timestamp = CassUtils.getTimestamp( version );
//write target<--source edge type meta data
@@ -248,7 +248,7 @@ public class EdgeMetadataSerializationImpl implements EdgeMetadataSerialization,
MutationBatch batch = keyspace.prepareMutationBatch();
- final long timestamp = CassUtils.getDeleteTimestamp( version );
+ final long timestamp = CassUtils.getTimestamp( version );
//write target<--source edge type and id type to meta data
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d312b316/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/serialization/EdgeMetadataSerializationTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/serialization/EdgeMetadataSerializationTest.java b/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/serialization/EdgeMetadataSerializationTest.java
index 0600119..425fb01 100644
--- a/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/serialization/EdgeMetadataSerializationTest.java
+++ b/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/serialization/EdgeMetadataSerializationTest.java
@@ -21,6 +21,7 @@ package org.apache.usergrid.persistence.graph.serialization;
import java.util.Iterator;
+import java.util.UUID;
import org.jukito.JukitoRunner;
import org.jukito.UseModules;
@@ -38,8 +39,15 @@ import org.apache.usergrid.persistence.graph.guice.TestGraphModule;
import org.apache.usergrid.persistence.model.entity.Id;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
+import com.fasterxml.uuid.UUIDComparator;
import com.google.inject.Inject;
+import com.netflix.astyanax.Keyspace;
+import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
+import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
+import com.netflix.astyanax.model.Column;
+import com.netflix.astyanax.model.ColumnFamily;
+import com.netflix.astyanax.serializers.StringSerializer;
import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.createEdge;
import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.createId;
@@ -47,6 +55,7 @@ import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.crea
import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.createSearchIdType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -55,8 +64,8 @@ import static org.mockito.Mockito.when;
*
*
*/
-@RunWith( JukitoRunner.class )
-@UseModules( { TestGraphModule.class } )
+@RunWith(JukitoRunner.class)
+@UseModules({ TestGraphModule.class })
public class EdgeMetadataSerializationTest {
@@ -72,6 +81,10 @@ public class EdgeMetadataSerializationTest {
@Inject
protected EdgeMetadataSerialization serialization;
+ @Inject
+ protected Keyspace keyspace;
+
+
protected OrganizationScope scope;
@@ -179,8 +192,8 @@ public class EdgeMetadataSerializationTest {
serialization.writeEdge( scope, edge4 ).execute();
//now check we get both types back
- Iterator<String> types = serialization.getIdTypesFromSource( scope,
- createSearchIdType( sourceId, "edge", null ) );
+ Iterator<String> types =
+ serialization.getIdTypesFromSource( scope, createSearchIdType( sourceId, "edge", null ) );
assertEquals( "target", types.next() );
assertEquals( "target2", types.next() );
@@ -225,8 +238,8 @@ public class EdgeMetadataSerializationTest {
serialization.writeEdge( scope, edge4 ).execute();
//now check we get both types back
- Iterator<String> types = serialization.getIdTypesToTarget( scope, createSearchIdType( targetId, "edge",
- null ) );
+ Iterator<String> types =
+ serialization.getIdTypesToTarget( scope, createSearchIdType( targetId, "edge", null ) );
assertEquals( "source", types.next() );
assertEquals( "source2", types.next() );
@@ -354,7 +367,6 @@ public class EdgeMetadataSerializationTest {
}
-
/**
* Test write and read edge types from source -> target
*/
@@ -374,8 +386,8 @@ public class EdgeMetadataSerializationTest {
serialization.writeEdge( scope, edge3 ).execute();
//now check we get both types back
- Iterator<String> edges = serialization.getIdTypesFromSource( scope,
- createSearchIdType( sourceId, "edge", null ) );
+ Iterator<String> edges =
+ serialization.getIdTypesFromSource( scope, createSearchIdType( sourceId, "edge", null ) );
assertEquals( "target", edges.next() );
assertEquals( "target2", edges.next() );
@@ -429,8 +441,8 @@ public class EdgeMetadataSerializationTest {
//now check we get both types back
- Iterator<String> edges = serialization.getIdTypesToTarget( scope, createSearchIdType( targetId, "edge",
- null ) );
+ Iterator<String> edges =
+ serialization.getIdTypesToTarget( scope, createSearchIdType( targetId, "edge", null ) );
assertEquals( "source", edges.next() );
assertEquals( "source2", edges.next() );
@@ -461,4 +473,99 @@ public class EdgeMetadataSerializationTest {
assertFalse( edges.hasNext() );
}
+
+
+ @Test
+ public void validateDeleteCollision() throws ConnectionException {
+
+
+ final String CF_NAME = "test";
+ final StringSerializer STR_SER = StringSerializer.get();
+
+ ColumnFamily<String, String> testCf = new ColumnFamily<String, String>( CF_NAME, STR_SER, STR_SER );
+ keyspace.createColumnFamily( testCf, null );
+
+
+ final String key = "key";
+ final String colname = "name";
+ final String colvalue = "value";
+
+ UUID firstUUID = UUIDGenerator.newTimeUUID();
+
+ UUID secondUUID = UUIDGenerator.newTimeUUID();
+
+ UUID thirdUUID = UUIDGenerator.newTimeUUID();
+
+ assertTrue( "First before second", UUIDComparator.staticCompare( firstUUID, secondUUID ) < 0 );
+
+ assertTrue( "Second before third", UUIDComparator.staticCompare( secondUUID, thirdUUID ) < 0 );
+
+ MutationBatch batch = keyspace.prepareMutationBatch();
+
+ batch.withRow( testCf, key ).setTimestamp( firstUUID.timestamp() ).putColumn( colname, colvalue );
+
+ batch.execute();
+
+ //now read it back to validate
+
+ Column<String> col = keyspace.prepareQuery( testCf ).getKey( key ).getColumn( colname ).execute().getResult();
+
+ assertEquals( colname, col.getName() );
+ assertEquals( colvalue, col.getStringValue() );
+
+ //now issue a write and a delete with the same timestamp, write will win
+
+ batch = keyspace.prepareMutationBatch();
+ batch.withRow( testCf, key ).setTimestamp( firstUUID.timestamp() ).putColumn( colname, colvalue );
+ batch.withRow( testCf, key ).setTimestamp( firstUUID.timestamp() ).deleteColumn( colname );
+ batch.execute();
+
+ boolean deleted = false;
+
+ try {
+ keyspace.prepareQuery( testCf ).getKey( key ).getColumn( colname ).execute().getResult();
+ }
+ catch ( NotFoundException nfe ) {
+ deleted = true;
+ }
+
+ assertTrue( deleted );
+
+ //ensure that if we have a latent write, it won't overwrite a newer value
+ batch.withRow( testCf, key ).setTimestamp( secondUUID.timestamp() ).putColumn( colname, colvalue );
+ batch.execute();
+
+ col = keyspace.prepareQuery( testCf ).getKey( key ).getColumn( colname ).execute().getResult();
+
+ assertEquals( colname, col.getName() );
+ assertEquals( colvalue, col.getStringValue() );
+
+ //now issue a delete with the first timestamp, column should still be present
+ batch = keyspace.prepareMutationBatch();
+ batch.withRow( testCf, key ).setTimestamp( firstUUID.timestamp() ).deleteColumn( colname );
+ batch.execute();
+
+
+ col = keyspace.prepareQuery( testCf ).getKey( key ).getColumn( colname ).execute().getResult();
+
+ assertEquals( colname, col.getName() );
+ assertEquals( colvalue, col.getStringValue() );
+
+ //now delete it with the 3rd timestamp, it should disappear
+
+ batch = keyspace.prepareMutationBatch();
+ batch.withRow( testCf, key ).setTimestamp( thirdUUID.timestamp() ).deleteColumn( colname );
+ batch.execute();
+
+ deleted = false;
+
+ try {
+ keyspace.prepareQuery( testCf ).getKey( key ).getColumn( colname ).execute().getResult();
+ }
+ catch ( NotFoundException nfe ) {
+ deleted = true;
+ }
+
+ assertTrue( deleted );
+ }
}
[33/50] [abbrv] git commit: Merge branch 'two-dot-o' of
github.com:usergrid/usergrid into two-dot-o
Posted by sn...@apache.org.
Merge branch 'two-dot-o' of github.com:usergrid/usergrid into two-dot-o
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/8a081182
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/8a081182
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/8a081182
Branch: refs/heads/optimistic-tx-semantics
Commit: 8a081182bec5555cd8f6c1abd76c689de9c2c750
Parents: fc35556 5627750
Author: Todd Nine <tn...@apigee.com>
Authored: Wed Feb 12 20:28:57 2014 -0700
Committer: Todd Nine <tn...@apigee.com>
Committed: Wed Feb 12 20:28:57 2014 -0700
----------------------------------------------------------------------
stack/awscluster/README.md | 84 +++++
stack/awscluster/assembly.xml | 29 ++
stack/awscluster/aws-sample.properties | 2 +
stack/awscluster/cassandra-cf.json | 315 +++++++++++++++++++
stack/awscluster/pom.xml | 139 ++++++++
.../src/main/dist/conf/Priam.properties | 21 ++
.../src/main/dist/init_instance/create_raid0.sh | 32 ++
.../main/dist/init_instance/init_instance.sh | 54 ++++
.../dist/init_instance/install_cassandra.sh | 56 ++++
.../dist/init_instance/install_elasticsearch.sh | 24 ++
.../dist/init_instance/install_oraclejdk.sh | 31 ++
.../src/main/dist/lib/priam-agent-1.2.24.jar | Bin 0 -> 33020 bytes
.../dist/lib/priam-cass-extensions-1.2.24.jar | Bin 0 -> 5478 bytes
.../src/main/dist/webapps/priam-web-1.2.24.war | Bin 0 -> 31272443 bytes
.../src/main/groovy/configure_cassandra.groovy | 113 +++++++
.../main/groovy/configure_elasticsearch.groovy | 47 +++
.../src/main/groovy/configure_priam.groovy | 41 +++
.../src/main/groovy/registry_clear.groovy | 20 ++
.../src/main/groovy/registry_list.groovy | 24 ++
.../src/main/groovy/registry_register.groovy | 38 +++
.../src/main/groovy/tag_instance.groovy | 28 ++
.../src/main/groovy/wait_for_instances.groovy | 44 +++
22 files changed, 1142 insertions(+)
----------------------------------------------------------------------
[26/50] [abbrv] Fixes to improve backward-compatibility. Fixed
password update functionality.
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/52f0e028/sdks/html5-javascript/usergrid.min.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/usergrid.min.js b/sdks/html5-javascript/usergrid.min.js
index 458734f..31c8682 100644
--- a/sdks/html5-javascript/usergrid.min.js
+++ b/sdks/html5-javascript/usergrid.min.js
@@ -1,3 +1,3 @@
/*! usergrid@0.0.0 2014-02-11 */
-function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){ret
urn a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event
]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error
","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.set
LogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(contex
t,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwri
ttenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function()
{xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var
p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([req
uest,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise;this.logger=new global.Logger(name),this.success=!0,this.err=err,this.data={};var data;try{data=JSON.parse(response.responseText)}catch(e){this.logger.error("Caught error ",e.message),data={}}finally{this.data=data}switch(this.status=parseInt(response.status),this.statusGroup=this.status-this.status%100,this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(this.data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&this.data.entities&&(entities=this.data.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),funct
ion(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+a
ppName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&
&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(se
rializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.data.entities])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){doCallback(callback,[err,entity
])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localSto
rage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={},data=response.data;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)}doCallback(callback,[err,data,user])})},Usergrid.Cl
ient.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};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),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),
organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid
.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){var data=response.data;if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT
"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj
)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===type||"user"===type)&&nameProperties.unshift("username");va
r names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});if(0===names.length)throw new UsergridError("Cannot infer an UUID or type from the entity","no_name_specified");return name=names.shift(),[type,name].join("/")},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),options={method:method,endpoint:type};console.log("SAVE DATA #1",entityId,entityData),entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){data[key]=entityData[key]}),console.log("SAVE DATA #2",data),options.body=data,this._client.request(options,function(err,response){console.log("SAVE DATA #3",response);var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,self])})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=t
his;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),console.log("AFTER FETCH",err,self.get(),entity,response),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"
==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console
.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activit
ies",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err
,data,data.entities)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&
&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback)
{var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterato
r||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();c
ollection.hasNextEntity();){var user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._js
on=JSON.stringify(entityData,null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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 th
is._list.splice(key,1)}return!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){var listItem=this._list[key];
-if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getP
revEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(op
tions){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{},entityOptions={typ
e:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=this,endpoint="groups/"+this
._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Counter.prototype.reset=function(
options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].jo
in("=")});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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self
.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new UsergridError(data)],self);e
lse{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},callback)}}else doCallback(callback,[!0,{error_description:"No asset specified"}],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sDat
a){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;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)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.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("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,callback)})}else doCallback(callback,[!0,new UsergridError("folder not specified")],self)},Usergrid.Asset.prototype.upload=function(data,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self);var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[!0,new UsergridError("The File APIs are not fully supported by your browser.")],self)},xhr.onload=function(){xhr.status>=300?doCallback(callback,[!0,new UsergridError(JSON.parse(xhr.responseText))],self):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)},1e3)},fr.readAsBinaryString(data)},Usergrid.Asset.prototype.download=function(callback){var self=this,endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr=new XMLHttpRequest;xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;doCallback(callback,[!1,blob],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[!0,new UsergridError(err)],self)},xhr.send()},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.except
ion=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.times
tamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);
\ No newline at end of file
+function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;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{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){ret
urn a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event
]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error
","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.set
LogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.create=function(){return new Promise},Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(contex
t,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwri
ttenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4^this.readyState||(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function()
{xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name];Usergrid.isValidEndpoint=function(){return!0};var VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.Request=function(method,endpoint,query_params,data,callback){var
p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),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);return Promise.chain([req
uest,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data
),this),p},Usergrid.Response.prototype.getEntities=function(){var entities=[];return this.success&&(entities=this.data?this.data.entities:this.entities),entities},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1,this._callTimeout=options.callTimeout||3e4,this._callTimeoutCallback=options.callTimeoutCallback||null,this.logoutCallback=options.logoutCallback||null},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"G
ET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),logoutCallback=function(){return"function"==typeof this.logoutCallback?this.logoutCallback(!0,"no_org_or_app_name_specified"):void 0}.bind(this);if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken());new Usergrid.Request(method,uri,qs,body,function(err,response){return-1!==["auth_expired_session_token","auth_missing_credentials","auth_unverified_oath","expired_token","unauthorized","auth_invalid"].indexOf(response.error)?logoutCallback():void doCallback(callback,[err,response])})},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodePa
rams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var getOnExist=options.getOnExist||!1;options={path:options.path,client:this,data:options};var group=new Usergrid.Group(options);group.fetch(function(err,data){var okToSave=err&&-1!==["service_resource_not_found","no_name_specified","null_pointer"].indexOf(err.name)||!err&&getOnExist;okToSave?group.save(function(err,data){doCallback(callback,[err,group,data])}):doCallback(callback,[null,group,data])})},Usergrid.Client.prototype.createEntity=function(options,callback){var getOnExist=options.getOnExist||!1;delete options.getOnExist;var entity_data={client:this,data:options},entity=new Usergrid.Entity(entity_data);entity.fetch(function(err,data){var common_errors=["service_resource_not_found","no_name_specified","null_pointer"],okToSave=!err&&getOnExist||err&&err.name&&-1!==common_errors.indexOf(err.name);okToSave?(entity.set(entity_data.data),entity
.save(function(err,data){doCallback(callback,[err,entity,data])})):doCallback(callback,[null,entity,data])})},Usergrid.Client.prototype.getEntity=function(options,callback){var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.fetch(function(err,data){doCallback(callback,[err,entity,data])})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCollection=function(options,callback){options.client=this;var collection=new Usergrid.Collection(options,function(err,data){doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",
endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities";var options={client:this,data:options},entity=new Usergrid.Entity(options);entity.save(function(err){doCallback(callback,[err,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),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)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype
.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):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,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=thi
s,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.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)}doCallback(callback,[err,data,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full a
uthenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}"function"==typeof callback&&callback(err,data,user,organizations,applications)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){va
r self=this,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)}"function"==typeof callback&&callback(err,data,user)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){if(this.getToken()){var self=this,options={method:"GET",endpoint:"users/me"};this.request(options,function(err,data){if(err)self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,null);else{var options={client:self,data:data.entities[0]},user=new Usergrid.Entity(options);"function"==typeof callback&&callback(null,data,user)}})}else callback(!0,null,null)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.lo
gout=function(){this.setToken()},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_S
YSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){options&&(this._data=options.data||{},this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?nul
l===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");("users"===type||"user"===type)&&nameProperties.unshift("username");var names=this.get(nameProperties).filter(function(x){return"undefined"!=typeof x});return 0===names.length?type:(name=names.shift(),[type,name].join("/"))},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),data={},entityData=this.get(),password=this.get("password"),oldpassword=this.get("oldpassword"),newpassword=this.get("newpassword"),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).forEach(function(key){dat
a[key]=entityData[key]}),options.body=data,this._client.request(options,function(err,response){var entity=response.getEntity();if(entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),self.set("password",null),self.set("oldpassword",null),self.set("newpassword",null),err&&self._client.logging)console.log("could not save entity"),doCallback(callback,[err,response,self]);else if(/^users?/.test(self.get("type"))&&oldpassword&&newpassword){var options={method:"PUT",endpoint:type+"/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),password:password,oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not update user"),self.set({password:null,oldpassword:null,newpassword:null}),doCallback(callback,[err,data,self])})}else doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.fetch=function(
callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,entity,self])})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err||self.set(null),"function"==typeof callback&&doCallback(callback,[err,data])})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){var error,self=this,connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Er
ror in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id=!1;return isUUID(entity.get("uuid"))?id=entity.get("uuid"):"users"===this.get("type")?id=entity.get("username"):entity.get("name")&&(id=entity.get("name")),id},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be con
nected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];"function"==typeof callback&&callback(err,data,data.entities)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),callback(!0,error)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",en
dpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Userg
rid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,"function"==typeof callback&&callback(err,data,data.entit
ies)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){var error,self=this,connecte
eType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)return void("function"==typeof callback&&(error="Error trying to delete object - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)return void("function"==typeof callback&&(error="Error in connect - no uuid specified.",self._client.logging&&console.log(error),callback(!0,error)));var endpoint=connectorType+"/"+connector+"/"+connection+"/"+connecteeType+"/"+connectee,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be disconnected"),"function"==typeof callback&&callback(err,data)})},Usergrid.Collection=function(options,callback){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.
previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}callback&&this.fetch(callback)},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){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;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.addCollection=function(collectionName,options,callback){self=this,options.client=this._client;var collection=new Usergrid.Collection(options,function(err){if("function"==typeof callback){for(collection.resetEntityPointer();collection.hasNextEntity();){v
ar user=collection.getNextEntity(),image=(user.get("email"),self._client.getDisplayImage(user.get("email"),user.get("picture")));user._portal_image_icon=image}self[collectionName]=collection,callback(err,collection)}})},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor: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{var cursor=data.cursor||null;if(self.saveCursor(cursor),data.entities){self.resetEntityPointer();var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entities[i]||{};self._baseType=data.entities[i].type,entityData.type=self._type;var entityOptions={type:self._type,client:self._client,uuid:uuid,data:entityData},ent=new Usergrid.Entity(entityOptions);ent._json=JSON.stringify(entityData,
null,2);var ct=self._list.length;self._list[ct]=ent}}}}"function"==typeof callback&&callback(err,data)
+})},Usergrid.Collection.prototype.addEntity=function(options,callback){var self=this;options.type=this._type,this._client.createEntity(options,function(err,entity){if(!err){var count=self._list.length;self._list[count]=entity}"function"==typeof callback&&callback(err,entity)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,data){err?(self._client.logging&&console.log("could not destroy entity"),"function"==typeof callback&&callback(err,data)):self.fetch(callback)}),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!1},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){for(var key in this._list){v
ar listItem=this._list[key];if(listItem.get("uuid")===uuid)return callback(null,listItem)}var options={data:{type:this._type,uuid:uuid},client:this._client},entity=new Usergrid.Entity(options);entity.fetch(callback)},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergr
id.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))
},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,data){if(err)self._client.logging&&console.log("error getting group"),"function"==typeof callback&&callback(err,data);else if(data.entities&&data.entities.length){var groupData=data.entities[0];self._data=groupData||{},self._client.request(memberOptions,function(err,data){if(err&&self._client.logging)console.log("error getting group users");else if(data.entities){var count=data.entities.length;self._list=[];for(var i=0;count>i;i++){var uuid=data.entities[i].uuid;if(uuid){var entityData=data.entiti
es[i]||{},entityOptions={type:entityData.type,client:self._client,uuid:uuid,data:entityData},entity=new Usergrid.Entity(entityOptions);self._list.push(entity)}}}"function"==typeof callback&&callback(err,data,self._list)})}})},Usergrid.Group.prototype.members=function(callback){"function"==typeof callback&&callback(null,this._list)},Usergrid.Group.prototype.add=function(options,callback){var self=this,options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data,data.entities):self.fetch(callback)})},Usergrid.Group.prototype.remove=function(options,callback){var self=this,options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")};this._client.request(options,function(error,data){error?"function"==typeof callback&&callback(error,data):self.fetch(callback)})},Usergrid.Group.prototype.feed=function(callback){var self=
this,endpoint="groups/"+this._path+"/feed",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self.logging&&console.log("error trying to log user in"),"function"==typeof callback&&callback(err,data,data.entities)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var user=options.user;options={client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}};var entity=new Usergrid.Entity(options);entity.save(function(err){"function"==typeof callback&&callback(err,entity)})},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,t
his._data.type="events",this._data.counters=options.counters||{},"function"==typeof callback&&callback.call(self,!1,self)};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;if(name){if(!isNaN(value))return self._data.counters[name]=parseInt(value)||1,self.save(callback);if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")}else if("function"==typeof callback)return callback.call(self,!0,"'value' for increment, decrement must be a number")},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)},Usergrid.Count
er.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},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(-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),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,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComp
onent(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){data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),"function"==typeof callback&&callback.call(self,err,data)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[!0,new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")],self):void self.save(function(err,data){err?doCallback(callback,[!0,new Usergrid.Error(data)],self):(data&&data.entities
&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[!1,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[!0,new UsergridError(data)],self):self.getAssets(function(err,data){err?doCallback(callback,[!0,new UsergridError(data)],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[err,new
UsergridError(data)],self)
<TRUNCATED>
[37/50] [abbrv] Missed a couple of package-rename spots in
query-validator, there still one compilation problem in QueryValidatorRunner.
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
new file mode 100644
index 0000000..4637ec5
--- /dev/null
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryValidatorRunner.java
@@ -0,0 +1,207 @@
+/*******************************************************************************
+ * Copyright 2013 baas.io
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.query.validator;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.model.InitializationError;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.cassandra.DataControl;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.utils.JsonUtils;
+
+import java.io.IOException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import org.apache.cassandra.transport.Server;
+
+/**
+ * @author Sung-ju Jin(realbeast)
+ */
+public class QueryValidatorRunner extends CassandraRunner {
+
+ private static Logger logger = LoggerFactory.getLogger(QueryValidatorRunner.class);
+ private boolean enableLocalServer;
+ private static StandaloneServer standaloneServer;
+ private Properties properties;
+ private static QueryValidator validator;
+ private static boolean initialize = false;
+
+ public QueryValidatorRunner(Class<?> klass) throws InitializationError {
+ super(klass);
+ }
+
+ @Override
+ protected DataControl preTest(RunNotifier notifier) {
+ DataControl control = super.preTest(notifier);
+ try {
+ setup();
+ } catch (InitializationError initializationError) {
+ initializationError.printStackTrace();
+ }
+ return control;
+ }
+
+ public static QueryValidator getValidator() {
+ return validator;
+ }
+
+ public synchronized void setup() throws InitializationError {
+ if(initialize)
+ return;
+
+ try {
+ logger.info("Loading initialize...");
+ Thread.sleep(20*1000);
+ } catch (InterruptedException e) {}
+
+ validator = CassandraRunner.getBean(QueryValidator.class);
+ properties = CassandraRunner.getBean("properties",Properties.class);
+
+ if( validator == null || properties == null) {
+ throw new InitializationError("Application context not loaded.");
+ }
+
+ String enableString = (String)properties.get("usergrid.query.validator.api.enablelocal");
+ enableLocalServer = StringUtils.endsWithIgnoreCase("true", enableString);
+ if( enableLocalServer ) {
+ startStandaloneServer();
+ try {
+ logger.info("Loading standalone server...");
+ Thread.sleep(20*1000);
+ } catch (InterruptedException e) {}
+ }
+ initialize = true;
+
+ String endpoint = (String)properties.get("usergrid.query.validator.api.endpoint");
+ String organization = (String)properties.get("usergrid.query.validator.api.organization");
+ String app = (String)properties.get("usergrid.query.validator.api.app");
+ String email = (String)properties.get("usergrid.query.validator.api.authorize.email");
+ String password = (String)properties.get("usergrid.query.validator.api.authorize.password");
+
+ String collection = "user";
+ List<Entity> entities = loadEntities(collection);
+ QueryValidationConfiguration configuration = new QueryValidationConfiguration();
+ configuration.setEndpointUri(endpoint);
+ configuration.setOrg(organization);
+ configuration.setEmail(email);
+ configuration.setPassword(password);
+ configuration.setApp(app);
+ configuration.setCollection(collection);
+ configuration.setEntities(entities);
+ validator.setConfiguration(configuration);
+ validator.setup();
+
+ }
+
+ private List<Entity> loadEntities(String collection) {
+ String json = null;
+ try {
+ URL url = Thread.currentThread().getContextClassLoader().getResource(collection + ".json");
+ json = FileUtils.readFileToString(FileUtils.toFile(url), Charset.forName("UTF-8"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ List<Entity> entities = new ArrayList<Entity>();
+ List<Map<String, Object>> datas = (List<Map<String, Object>>) JsonUtils.parse(json);
+ for(Map<String, Object> data : datas) {
+ Entity entity = new QueryEntity();
+ entity.setType(collection);
+ entity.setProperties(data);
+ entity.setCreated(System.currentTimeMillis());
+ entity.setModified(entity.getCreated());
+ entities.add(entity);
+ }
+ return entities;
+ }
+
+ private void startStandaloneServer() {
+ standaloneServer = new StandaloneServer();
+ try {
+ Thread thread = new Thread(standaloneServer);
+ thread.start();
+ } catch (Exception ex) {
+ logger.error("Could not schedule standalone server runner", ex);
+ }
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override
+ public void run() {
+ try {
+ logger.error("In shutdownHook");
+ stopServer();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ });
+ boolean loaded = false;
+ while (!loaded) {
+ if( standaloneServer.server.isRunning() ) {
+ if( standaloneServer.server.getManagementService() != null ) {
+ loaded = true;
+ continue;
+ }
+ }
+ try {
+ logger.info("Loding application context...");
+ Thread.sleep(2*1000);
+ } catch (InterruptedException e) {
+ continue;
+ }
+ }
+
+ if(loaded) {
+ ManagementService managementService = standaloneServer.server.getManagementService();
+ try {
+ managementService.setup();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ logger.info("Finish start standalone server.");
+ }
+
+ static class StandaloneServer implements Runnable {
+ public static Server server;
+
+ public StandaloneServer() {
+ server = new Server();
+ }
+
+ @Override
+ public void run() {
+ server.setInitializeDatabaseOnStart(true);
+ server.setDaemon(false);
+ server.startServer();
+ }
+
+ public void stop() {
+ server.stopServer();
+ }
+ }
+
+ private void stopServer() {
+ standaloneServer.stop();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidationTest.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidationTest.java b/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidationTest.java
deleted file mode 100644
index 5054e45..0000000
--- a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidationTest.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.Assert;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-@RunWith(QueryValidatorRunner.class)
-public class QueryValidationTest {
-
- private QueryValidator validator;
-
- @Before
- public void setup() {
- validator = QueryValidatorRunner.getValidator();
- }
-
- @Test
- public void sexEqualAndNameEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and name = 'judekim' LIMIT 10";
- String api = "SELECT * WHERE sex = 'male' AND name = 'judekim'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameEqualAndSexEqual() {
- String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 10";
- String api = "select * where name = 'judekim' and sex = 'male'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameEqualAndSexEqual_limitL20() {
- String sqlite = "SELECT * FROM users WHERE name = 'judekim' and sex = 'male' LIMIT 20";
- String api = "select * where name = 'judekim' and sex = 'male'";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndNameEqualExtra1() {
- String sqlite = "SELECT * FROM users WHERE sex = 'female' and name = 'curioe' LIMIT 10";
- String api = "select * where sex = 'female' and name = 'curioe'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualOrNameEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'female' or name = 'curioe' LIMIT 10";
- String api = "select * where sex = 'female' or name = 'curioe'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_sortAddressAscNameDesc_limitL4() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 35 or sex = 'female' ORDER BY address asc, name desc LIMIT 4";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 35 or sex = 'female' order by address asc, name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqual_sortAgeDescExtra1() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqual_sortAgeDescExtra2() {
- String sqlite = " SELECT * FROM users WHERE sex = 'female' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'female' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal() {
- String sqlite = " SELECT * FROM users WHERE sex = 'male' and age >= 35 LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAgeDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAgeDesc_limitL100() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY age desc LIMIT 100";
- String api = "select * where sex = 'male' and age >= 35 order by age desc";
- int limit = 100;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void qlSexEqualAndAgeGreaterthanequal_sortNameDesc_limitL100() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY name desc LIMIT 100";
- String api = "select * where sex = 'male' and age >= 35 order by name desc";
- int limit = 100;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortAgeDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY age desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by age desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void limitL12() {
- String sqlite = "SELECT * FROM users LIMIT 12";
- String api = null;
- int limit = 12;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 10";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequalOrSexEqual_sortNameDesc_limitL100() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 or sex = 'female' ORDER BY name desc LIMIT 100";
- String api = "select * where sex = 'male' and age >= 35 or sex = 'female' order by name desc";
- int limit = 100;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void limitL11() {
- String sqlite = "SELECT * FROM users LIMIT 11";
- String api = null;
- int limit = 11;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 10";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void nameBeginswithAndSexEqualAndAgeGreaterthanequalOrSexEqual_limitL20() {
- String sqlite = "SELECT * FROM users WHERE name LIKE 'a%' and sex = 'male' and age >= 20 or sex = 'female' LIMIT 20";
- String api = "select * where name = 'a*' and sex = 'male' and age >= 20 or sex = 'female'";
- int limit = 20;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-
- @Test
- public void sexEqualAndAgeGreaterthanequal_sortAddressDesc_limitL100() {
- String sqlite = "SELECT * FROM users WHERE sex = 'male' and age >= 35 ORDER BY address desc LIMIT 100";
- String api = "select * where sex = 'male' and age >= 35 order by address desc";
- int limit = 100;
-
- QueryRequest request = new QueryRequest();
- request.setDbQuery(sqlite);
- request.getApiQuery().setQuery(api);
- request.getApiQuery().setLimit(limit);
- QueryResponse response = validator.execute(request);
- Assert.assertTrue(response.toString(), response.result());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidatorRunner.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidatorRunner.java b/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidatorRunner.java
deleted file mode 100644
index bf264e9..0000000
--- a/stack/query-validator/src/test/java/org/usergrid/query/validator/QueryValidatorRunner.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*******************************************************************************
- * Copyright 2013 baas.io
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.usergrid.query.validator;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.junit.runner.notification.RunNotifier;
-import org.junit.runners.model.InitializationError;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.cassandra.CassandraRunner;
-import org.apache.usergrid.cassandra.DataControl;
-import org.apache.usergrid.management.ManagementService;
-import org.apache.usergrid.persistence.Entity;
-import org.apache.usergrid.standalone.Server;
-import org.apache.usergrid.utils.JsonUtils;
-
-import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * @author Sung-ju Jin(realbeast)
- */
-public class QueryValidatorRunner extends CassandraRunner {
-
- private static Logger logger = LoggerFactory.getLogger(QueryValidatorRunner.class);
- private boolean enableLocalServer;
- private static StandaloneServer standaloneServer;
- private Properties properties;
- private static QueryValidator validator;
- private static boolean initialize = false;
-
- public QueryValidatorRunner(Class<?> klass) throws InitializationError {
- super(klass);
- }
-
- @Override
- protected DataControl preTest(RunNotifier notifier) {
- DataControl control = super.preTest(notifier);
- try {
- setup();
- } catch (InitializationError initializationError) {
- initializationError.printStackTrace();
- }
- return control;
- }
-
- public static QueryValidator getValidator() {
- return validator;
- }
-
- public synchronized void setup() throws InitializationError {
- if(initialize)
- return;
-
- try {
- logger.info("Loading initialize...");
- Thread.sleep(20*1000);
- } catch (InterruptedException e) {}
-
- validator = CassandraRunner.getBean(QueryValidator.class);
- properties = CassandraRunner.getBean("properties",Properties.class);
-
- if( validator == null || properties == null) {
- throw new InitializationError("Application context not loaded.");
- }
-
- String enableString = (String)properties.get("usergrid.query.validator.api.enablelocal");
- enableLocalServer = StringUtils.endsWithIgnoreCase("true", enableString);
- if( enableLocalServer ) {
- startStandaloneServer();
- try {
- logger.info("Loading standalone server...");
- Thread.sleep(20*1000);
- } catch (InterruptedException e) {}
- }
- initialize = true;
-
- String endpoint = (String)properties.get("usergrid.query.validator.api.endpoint");
- String organization = (String)properties.get("usergrid.query.validator.api.organization");
- String app = (String)properties.get("usergrid.query.validator.api.app");
- String email = (String)properties.get("usergrid.query.validator.api.authorize.email");
- String password = (String)properties.get("usergrid.query.validator.api.authorize.password");
-
- String collection = "user";
- List<Entity> entities = loadEntities(collection);
- QueryValidationConfiguration configuration = new QueryValidationConfiguration();
- configuration.setEndpointUri(endpoint);
- configuration.setOrg(organization);
- configuration.setEmail(email);
- configuration.setPassword(password);
- configuration.setApp(app);
- configuration.setCollection(collection);
- configuration.setEntities(entities);
- validator.setConfiguration(configuration);
- validator.setup();
-
- }
-
- private List<Entity> loadEntities(String collection) {
- String json = null;
- try {
- URL url = Thread.currentThread().getContextClassLoader().getResource(collection + ".json");
- json = FileUtils.readFileToString(FileUtils.toFile(url), Charset.forName("UTF-8"));
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- List<Entity> entities = new ArrayList<Entity>();
- List<Map<String, Object>> datas = (List<Map<String, Object>>) JsonUtils.parse(json);
- for(Map<String, Object> data : datas) {
- Entity entity = new QueryEntity();
- entity.setType(collection);
- entity.setProperties(data);
- entity.setCreated(System.currentTimeMillis());
- entity.setModified(entity.getCreated());
- entities.add(entity);
- }
- return entities;
- }
-
- private void startStandaloneServer() {
- standaloneServer = new StandaloneServer();
- try {
- Thread thread = new Thread(standaloneServer);
- thread.start();
- } catch (Exception ex) {
- logger.error("Could not schedule standalone server runner", ex);
- }
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- try {
- logger.error("In shutdownHook");
- stopServer();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- });
- boolean loaded = false;
- while (!loaded) {
- if( standaloneServer.server.isRunning() ) {
- if( standaloneServer.server.getManagementService() != null ) {
- loaded = true;
- continue;
- }
- }
- try {
- logger.info("Loding application context...");
- Thread.sleep(2*1000);
- } catch (InterruptedException e) {
- continue;
- }
- }
-
- if(loaded) {
- ManagementService managementService = standaloneServer.server.getManagementService();
- try {
- managementService.setup();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- logger.info("Finish start standalone server.");
- }
-
- static class StandaloneServer implements Runnable {
- public static Server server;
-
- public StandaloneServer() {
- server = new Server();
- }
-
- @Override
- public void run() {
- server.setInitializeDatabaseOnStart(true);
- server.setDaemon(false);
- server.startServer();
- }
-
- public void stop() {
- server.stopServer();
- }
- }
-
- private void stopServer() {
- standaloneServer.stop();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/482c5cef/stack/rest/pom.xml
----------------------------------------------------------------------
diff --git a/stack/rest/pom.xml b/stack/rest/pom.xml
index 22c3c93..901b009 100644
--- a/stack/rest/pom.xml
+++ b/stack/rest/pom.xml
@@ -560,8 +560,6 @@
<scope>test</scope>
</dependency>
-
-
<dependency>
<groupId>org.usergrid</groupId>
<artifactId>usergrid-java-client</artifactId>
@@ -575,5 +573,7 @@
<scope>test</scope>
<classifier>tests</classifier>
</dependency>
+
</dependencies>
+
</project>
[29/50] [abbrv] git commit: Added invalid input tests. Jukito does
not seem to work correctly need to investigate
Posted by sn...@apache.org.
Added invalid input tests. Jukito does not seem to work correctly need to investigate
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/85ffe7b3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/85ffe7b3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/85ffe7b3
Branch: refs/heads/optimistic-tx-semantics
Commit: 85ffe7b314cc81c60a263714b6ff90ec82a0d6c7
Parents: e578bb6
Author: Todd Nine <tn...@apigee.com>
Authored: Tue Feb 11 14:14:36 2014 -0700
Committer: Todd Nine <tn...@apigee.com>
Committed: Tue Feb 11 17:34:52 2014 -0700
----------------------------------------------------------------------
.../collection/cassandra/CassandraRule.java | 2 +
.../persistence/graph/EdgeManagerIT.java | 135 +++++++++++++------
2 files changed, 98 insertions(+), 39 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/85ffe7b3/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/CassandraRule.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/CassandraRule.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/CassandraRule.java
index 8e26834..03264cf 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/CassandraRule.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/CassandraRule.java
@@ -4,6 +4,8 @@ package org.apache.usergrid.persistence.collection.cassandra;
import java.io.File;
import java.io.IOException;
+import org.jukito.JukitoModule;
+import org.jukito.JukitoRunner;
import org.safehaus.guicyfig.Env;
import org.safehaus.guicyfig.EnvironResource;
import org.safehaus.guicyfig.GuicyFigModule;
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/85ffe7b3/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/EdgeManagerIT.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/EdgeManagerIT.java b/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/EdgeManagerIT.java
index 0bb38d2..f2528b8 100644
--- a/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/EdgeManagerIT.java
+++ b/stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/EdgeManagerIT.java
@@ -20,9 +20,10 @@ package org.apache.usergrid.persistence.graph;
import java.util.Iterator;
-import java.util.List;
import java.util.UUID;
+import org.jukito.All;
+import org.jukito.JukitoModule;
import org.jukito.JukitoRunner;
import org.jukito.UseModules;
import org.junit.Before;
@@ -53,18 +54,16 @@ import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.crea
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
@RunWith( JukitoRunner.class )
-@UseModules( { TestGraphModule.class } )
+@UseModules( { TestGraphModule.class} )
+//@UseModules( { TestGraphModule.class, EdgeManagerIT.InvalidInput.class } )
public class EdgeManagerIT {
-
@ClassRule
public static CassandraRule rule = new CassandraRule();
@@ -238,16 +237,15 @@ public class EdgeManagerIT {
final Id sourceId = createId( "source" );
-
- Edge edge1 = createEdge( sourceId, "test", createId("target") );
+ Edge edge1 = createEdge( sourceId, "test", createId( "target" ) );
em.writeEdge( edge1 ).toBlockingObservable().singleOrDefault( null );
- Edge edge2 = createEdge( sourceId, "test", createId("target") );
+ Edge edge2 = createEdge( sourceId, "test", createId( "target" ) );
em.writeEdge( edge2 ).toBlockingObservable().singleOrDefault( null );
- Edge edge3 = createEdge( sourceId, "test", createId("target") );
+ Edge edge3 = createEdge( sourceId, "test", createId( "target" ) );
em.writeEdge( edge3 ).toBlockingObservable().singleOrDefault( null );
@@ -263,10 +261,10 @@ public class EdgeManagerIT {
Iterator<Edge> returned = edges.toBlockingObservable().getIterator();
- //we have 3 edges, but we specified our first edge as the max, we shouldn't get any more results than the first
+ //we have 3 edges, but we specified our first edge as the max, we shouldn't get any more results than the first
assertEquals( "Correct edge returned", edge1, returned.next() );
- assertFalse("No more edges", returned.hasNext());
+ assertFalse( "No more edges", returned.hasNext() );
search = createSearchByEdge( edge1.getSourceNode(), edge1.getType(), edge3.getVersion(), edge2 );
@@ -290,15 +288,15 @@ public class EdgeManagerIT {
final Id targetId = createId( "target" );
- Edge edge1 = createEdge( createId("source"), "test", targetId );
+ Edge edge1 = createEdge( createId( "source" ), "test", targetId );
em.writeEdge( edge1 ).toBlockingObservable().singleOrDefault( null );
- Edge edge2 = createEdge( createId("source"), "test", targetId );
+ Edge edge2 = createEdge( createId( "source" ), "test", targetId );
em.writeEdge( edge2 ).toBlockingObservable().singleOrDefault( null );
- Edge edge3 = createEdge( createId("source"), "test", targetId );
+ Edge edge3 = createEdge( createId( "source" ), "test", targetId );
em.writeEdge( edge3 ).toBlockingObservable().singleOrDefault( null );
@@ -318,7 +316,7 @@ public class EdgeManagerIT {
assertEquals( "Correct edge returned", edge1, returned.next() );
- assertFalse("No more edges", returned.hasNext());
+ assertFalse( "No more edges", returned.hasNext() );
search = createSearchByEdge( edge1.getTargetNode(), edge1.getType(), edge3.getVersion(), edge2 );
@@ -537,7 +535,7 @@ public class EdgeManagerIT {
Edge test2TargetEdge = new SimpleEdge( sourceId, "test2", targetId1, UUIDGenerator.newTimeUUID() );
- em.writeEdge( test2TargetEdge).toBlockingObservable().singleOrDefault( null );
+ em.writeEdge( test2TargetEdge ).toBlockingObservable().singleOrDefault( null );
//get our 2 edge types
@@ -552,7 +550,7 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now test sub edges
@@ -562,20 +560,20 @@ public class EdgeManagerIT {
results = edges.toBlockingObservable().getIterator();
- assertEquals( "Types correct", targetId1.getType(), results.next());
+ assertEquals( "Types correct", targetId1.getType(), results.next() );
- assertEquals( "Types correct", targetId2.getType() , results.next() );
+ assertEquals( "Types correct", targetId2.getType(), results.next() );
- assertFalse( "No results", results.hasNext());
+ assertFalse( "No results", results.hasNext() );
//now get types for test2
edges = em.getIdTypesFromSource( new SimpleSearchIdType( testTargetEdge.getSourceNode(), "test2", null ) );
results = edges.toBlockingObservable().getIterator();
- assertEquals( "Types correct", targetId1.getType(), results.next( ) );
+ assertEquals( "Types correct", targetId1.getType(), results.next() );
- assertFalse( "No results", results.hasNext());
+ assertFalse( "No results", results.hasNext() );
//now delete our edges, we shouldn't get anything back
em.deleteEdge( testTargetEdge );
@@ -587,7 +585,7 @@ public class EdgeManagerIT {
results = edges.toBlockingObservable().getIterator();
- assertFalse( "No results", results.hasNext());
+ assertFalse( "No results", results.hasNext() );
}
@@ -626,9 +624,9 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test", results.next() );
- assertEquals( "Edges correct","test2", results.next());
+ assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now test sub edges
@@ -637,12 +635,11 @@ public class EdgeManagerIT {
results = edges.toBlockingObservable().getIterator();
- assertEquals( "Types correct", sourceId1.getType(), results.next());
-
- assertEquals( "Types correct", sourceId2.getType(), results.next());
+ assertEquals( "Types correct", sourceId1.getType(), results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertEquals( "Types correct", sourceId2.getType(), results.next() );
+ assertFalse( "No more edges", results.hasNext() );
//now get types for test2
@@ -653,8 +650,7 @@ public class EdgeManagerIT {
assertEquals( "Types correct", sourceId1.getType(), results.next() );
- assertFalse("No more edges", results.hasNext());
-
+ assertFalse( "No more edges", results.hasNext() );
em.deleteEdge( testTargetEdge );
@@ -666,7 +662,7 @@ public class EdgeManagerIT {
results = edges.toBlockingObservable().getIterator();
- assertEquals( "No results",results.hasNext() );
+ assertEquals( "No results", results.hasNext() );
}
@@ -706,7 +702,7 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test", results.next() );
assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now load the next page
@@ -719,7 +715,7 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now test sub edges
@@ -731,7 +727,7 @@ public class EdgeManagerIT {
assertEquals( "Types correct", targetId1.getType(), results.next() );
assertEquals( "Types correct", targetId2.getType(), results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now get the next page
@@ -784,7 +780,7 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test", results.next() );
assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now load the next page
@@ -800,7 +796,7 @@ public class EdgeManagerIT {
assertEquals( "Edges correct", "test2", results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now test sub edges
@@ -813,7 +809,7 @@ public class EdgeManagerIT {
assertEquals( "Types correct", sourceId2.getType(), results.next() );
- assertFalse("No more edges", results.hasNext());
+ assertFalse( "No more edges", results.hasNext() );
//now get the next page
@@ -829,7 +825,68 @@ public class EdgeManagerIT {
}
- //TODO invalid input testing with Jukito
+ @Test( expected = NullPointerException.class )
+ public void invalidEdgeTypesWrite( @All Edge edge) {
+ final EdgeManager em = emf.createEdgeManager( scope );
+
+ em.writeEdge( edge );
+ }
+
+
+ @Test( expected = NullPointerException.class )
+ public void invalidEdgeTypesDelete(@All Edge edge) {
+ final EdgeManager em = emf.createEdgeManager( scope );
+
+ em.deleteEdge( edge);
+ }
+
+
+ public static class InvalidInput extends JukitoModule {
+
+ @Override
+ protected void configureTest() {
+ //create all edge types of junk input
+//
+// final UUID version = UUIDGenerator.newTimeUUID();
+//
+// Id nullUuid = mock( Id.class );
+// when( nullUuid.getUuid() ).thenReturn( null );
+//
+//
+// Id nullType = mock( Id.class );
+// when( nullType.getType() ).thenReturn( "type" );
+//
+// Edge[] edges = new Edge[] {
+// mockEdge( nullUuid, "test", createId( "target" ), version ),
+//
+// mockEdge( nullType, "test", createId( "target" ), version ),
+//
+// mockEdge( createId( "source" ), null, createId( "target" ), version ),
+//
+// mockEdge( createId( "source" ), "test", nullUuid, version ),
+//
+// mockEdge( createId( "source" ), "test", nullType, version ),
+//
+// mockEdge( createId( "source" ), "test", createId( "target" ), null )
+// };
+//
+//
+// bindManyInstances( Edge.class, edges );
+
+ }
+
+
+ private Edge mockEdge( final Id sourceId, final String type, final Id targetId, final UUID version ) {
+ Edge edge = mock( Edge.class );
+
+ when( edge.getSourceNode() ).thenReturn( sourceId );
+ when( edge.getType() ).thenReturn( type );
+ when( edge.getTargetNode() ).thenReturn( targetId );
+ when( edge.getVersion() ).thenReturn( version );
+
+ return edge;
+ }
+ }
}
[39/50] [abbrv] git commit: Merge branch 'master' of
https://github.com/usergrid/usergrid
Posted by sn...@apache.org.
Merge branch 'master' of https://github.com/usergrid/usergrid
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/eb46ac7f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/eb46ac7f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/eb46ac7f
Branch: refs/heads/optimistic-tx-semantics
Commit: eb46ac7fc724f16eb7b2fdced660e0cd1116ced8
Parents: 482c5ce 7aa369f
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 08:34:06 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 08:34:06 2014 -0500
----------------------------------------------------------------------
.gitignore | 5 +-
README.md | 29 +
sdks/html5-javascript/Gruntfile.js | 169 +-
sdks/html5-javascript/lib/Client.js | 865 ------
sdks/html5-javascript/lib/Collection.js | 446 ---
sdks/html5-javascript/lib/Counter.js | 186 --
sdks/html5-javascript/lib/Entity.js | 646 -----
sdks/html5-javascript/lib/Group.js | 233 --
sdks/html5-javascript/lib/Module.js | 34 +
sdks/html5-javascript/lib/Usergrid.js | 283 +-
sdks/html5-javascript/lib/modules/Asset.js | 149 +
sdks/html5-javascript/lib/modules/Client.js | 749 +++++
sdks/html5-javascript/lib/modules/Collection.js | 459 +++
sdks/html5-javascript/lib/modules/Counter.js | 186 ++
sdks/html5-javascript/lib/modules/Entity.js | 659 +++++
sdks/html5-javascript/lib/modules/Error.js | 125 +
sdks/html5-javascript/lib/modules/Folder.js | 167 ++
sdks/html5-javascript/lib/modules/Group.js | 233 ++
sdks/html5-javascript/lib/modules/util/Ajax.js | 74 +
sdks/html5-javascript/lib/modules/util/Event.js | 33 +
.../html5-javascript/lib/modules/util/Logger.js | 68 +
.../lib/modules/util/Promise.js | 83 +
sdks/html5-javascript/tests/mocha/test.js | 1036 +++++--
.../tests/resources/js/blanket_mocha.min.js | 2 +-
sdks/html5-javascript/usergrid.js | 2673 +++++++++++-------
sdks/html5-javascript/usergrid.min.js | 5 +-
stack/README.md | 4 +-
27 files changed, 5983 insertions(+), 3618 deletions(-)
----------------------------------------------------------------------
[17/50] [abbrv] rebasing from usergrid master
Posted by sn...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/7b9048ca/.gitignore
----------------------------------------------------------------------
diff --cc .gitignore
index 535c19d,3684d76..70161ee
--- a/.gitignore
+++ b/.gitignore
@@@ -13,7 -13,9 +13,10 @@@ Ico
.Spotlight-V100
.Trashes
/portal/performance/
--
/portal/node_modules/
+ /portal/dist
+ /portal/bower_components
+ /portal/.idea
-/stack/corepersistence/priamcluster/aws.properties
++/stack/corepersistence/priamcluster/aws.properties
+#Webstorm artifacts
+.idea/
[46/50] [abbrv] git commit: Fixing merge issues in query validator,
still one test failure present
Posted by sn...@apache.org.
Fixing merge issues in query validator, still one test failure present
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/528afe5a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/528afe5a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/528afe5a
Branch: refs/heads/optimistic-tx-semantics
Commit: 528afe5ad9cee94a6821276dbf0a6f59479d0afa
Parents: 3dc1e9f
Author: Dave Johnson <dm...@apigee.com>
Authored: Thu Feb 13 10:00:00 2014 -0500
Committer: Dave Johnson <dm...@apigee.com>
Committed: Thu Feb 13 10:00:00 2014 -0500
----------------------------------------------------------------------
stack/query-validator/pom.xml | 8 ++++++++
.../org/apache/usergrid/query/validator/QueryITSuite.java | 3 ++-
.../src/test/resources/usergrid-test-context.xml | 4 ++--
3 files changed, 12 insertions(+), 3 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/528afe5a/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/pom.xml b/stack/query-validator/pom.xml
index fda8466..0ebdcda 100644
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@ -209,6 +209,14 @@
<version>0.0.3</version>
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.usergrid</groupId>
+ <artifactId>usergrid-rest</artifactId>
+ <version>0.0.29-SNAPSHOT</version>
+ <scope>test</scope>
+ <classifier>tests</classifier>
+ <type>jar</type>
+ </dependency>
</dependencies>
</project>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/528afe5a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
index 8f92fc3..fd88cf2 100644
--- a/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
+++ b/stack/query-validator/src/test/java/org/apache/usergrid/query/validator/QueryITSuite.java
@@ -35,5 +35,6 @@ public class QueryITSuite {
//TODO Detecting current path
@ClassRule
- public static ITSetup serverResource = new ITSetup( cassandraResource, "../rest/src/main/webapp" );
+ public static ITSetup serverResource = new ITSetup( cassandraResource );
+ //public static ITSetup serverResource = new ITSetup( cassandraResource, "../rest/src/main/webapp" );
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/528afe5a/stack/query-validator/src/test/resources/usergrid-test-context.xml
----------------------------------------------------------------------
diff --git a/stack/query-validator/src/test/resources/usergrid-test-context.xml b/stack/query-validator/src/test/resources/usergrid-test-context.xml
index b07cc2d..d1f50e5 100644
--- a/stack/query-validator/src/test/resources/usergrid-test-context.xml
+++ b/stack/query-validator/src/test/resources/usergrid-test-context.xml
@@ -22,13 +22,13 @@
<import resource="usergrid-rest-context.xml"/>
- <bean id="traceTagManager" class="org.usergrid.persistence.cassandra.util.TraceTagManager">
+ <bean id="traceTagManager" class="org.apache.usergrid.persistence.cassandra.util.TraceTagManager">
<property name="reportUnattached" value="false"/>
<property name="traceEnabled" value="false"/>
</bean>
- <bean id="binaryStore" class="org.usergrid.services.assets.data.LocalFileBinaryStore"/>
+ <bean id="binaryStore" class="org.apache.usergrid.services.assets.data.LocalFileBinaryStore"/>
<bean id="setup" class="org.apache.usergrid.persistence.cassandra.Setup">
<constructor-arg ref="entityManagerFactory"/>