You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by sf...@apache.org on 2014/10/10 17:50:41 UTC

[34/43] git commit: Changed index creation to only happen on application creation and EMF setup to avoid hammering the creating a master node choke point when creating index managers

Changed index creation to only happen on application creation and EMF setup to avoid hammering the creating a master node choke point when creating index managers


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

Branch: refs/heads/two-dot-o-events
Commit: d824ee21ca80f37726e3f3ed9af4958041143241
Parents: 72ef74b
Author: Todd Nine <to...@apache.org>
Authored: Thu Oct 9 17:20:53 2014 -0600
Committer: Todd Nine <to...@apache.org>
Committed: Thu Oct 9 17:20:53 2014 -0600

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  26 ++-
 .../corepersistence/CpEntityManagerFactory.java | 191 +++++++++++-----
 .../usergrid/persistence/EntityManager.java     |   5 +
 .../cassandra/EntityManagerImpl.java            |   7 +
 .../org/apache/usergrid/CoreApplication.java    |   1 +
 .../collection/EntityCollectionManagerIT.java   |   1 +
 .../usergrid/persistence/index/EntityIndex.java |   6 +
 .../index/impl/EsEntityIndexImpl.java           | 216 ++++++++++---------
 .../persistence/index/impl/EntityIndexTest.java |   5 +
 .../cassandra/ManagementServiceImpl.java        |  38 ++--
 10 files changed, 313 insertions(+), 183 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
index cf6aa94..3aea391 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
@@ -142,6 +142,7 @@ import org.apache.usergrid.persistence.map.impl.MapScopeImpl;
 import org.apache.usergrid.persistence.model.entity.Id;
 import org.apache.usergrid.persistence.model.entity.SimpleId;
 import org.apache.usergrid.persistence.model.field.Field;
+import org.apache.usergrid.persistence.model.field.StringField;
 import org.apache.usergrid.persistence.model.util.UUIDGenerator;
 import org.apache.usergrid.persistence.schema.CollectionInfo;
 import org.apache.usergrid.utils.ClassUtils;
@@ -825,10 +826,22 @@ public class CpEntityManager implements EntityManager {
     private Iterable<EntityRef> getEntityRefsForUniqueProperty( 
             EntityRef ownerRef, String collName, String propName, String alias ) throws Exception {
 
-        Results results = getRelationManager( ownerRef ).searchCollection( 
-                collName, Query.fromQL( "select * where " + propName + " = '" + alias + "'" ) );
 
-        return results.getRefs();
+        final CollectionScope collectionScope = new CollectionScopeImpl(
+                applicationScope.getApplication(),
+                new SimpleId(ownerRef.getUuid(), ownerRef.getType()),
+                collName );
+
+
+        final EntityCollectionManager ecm = managerCache.getEntityCollectionManager( collectionScope );
+
+        final Id results = ecm.getIdField( new StringField(propName, alias) ).toBlocking().lastOrDefault( null );
+
+        if(results == null){
+            return Collections.emptyList();
+        }
+
+        return Collections.<EntityRef>singleton( new SimpleEntityRef( results.getType(),  results.getUuid() ));
     }
 
 
@@ -2780,6 +2793,13 @@ public class CpEntityManager implements EntityManager {
     }
 
 
+    @Override
+    public void createIndex() {
+        EntityIndex ei = managerCache.getEntityIndex( applicationScope );
+        ei.initializeIndex();
+    }
+
+
     public static org.apache.usergrid.persistence.model.entity.Entity 
         entityToCpEntity( Entity entity, UUID importId ) {
 

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java
index 17b33e4..72763e8 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java
@@ -21,11 +21,17 @@ import com.google.common.cache.LoadingCache;
 import com.google.inject.Injector;
 import com.yammer.metrics.annotation.Metered;
 import static java.lang.String.CASE_INSENSITIVE_ORDER;
+
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.TreeMap;
 import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+
 import org.apache.commons.lang.StringUtils;
 
 import org.apache.usergrid.corepersistence.util.CpNamingUtils;
@@ -35,6 +41,7 @@ import org.apache.usergrid.persistence.Entity;
 import org.apache.usergrid.persistence.EntityFactory;
 import org.apache.usergrid.persistence.EntityManager;
 import org.apache.usergrid.persistence.EntityManagerFactory;
+import org.apache.usergrid.persistence.EntityRef;
 import org.apache.usergrid.persistence.Results;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
 import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
@@ -53,6 +60,7 @@ import org.apache.usergrid.persistence.graph.GraphManager;
 import org.apache.usergrid.persistence.graph.GraphManagerFactory;
 import org.apache.usergrid.persistence.graph.SearchByEdgeType;
 import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdgeType;
+import org.apache.usergrid.persistence.index.EntityIndex;
 import org.apache.usergrid.persistence.index.EntityIndexFactory;
 import org.apache.usergrid.persistence.index.query.Query;
 import org.apache.usergrid.persistence.map.MapManagerFactory;
@@ -85,15 +93,17 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     public static final Class<DynamicEntity> APPLICATION_ENTITY_CLASS = DynamicEntity.class;
 
     // The System Application where we store app and org metadata
-    public static final UUID SYSTEM_APP_ID = 
+    public static final UUID SYSTEM_APP_ID =
             UUID.fromString("b6768a08-b5d5-11e3-a495-10ddb1de66c3");
 
-    public static final  UUID MANAGEMENT_APPLICATION_ID = 
+    public static final  UUID MANAGEMENT_APPLICATION_ID =
             UUID.fromString("b6768a08-b5d5-11e3-a495-11ddb1de66c8");
 
-    public static final  UUID DEFAULT_APPLICATION_ID = 
+    public static final  UUID DEFAULT_APPLICATION_ID =
             UUID.fromString("b6768a08-b5d5-11e3-a495-11ddb1de66c9");
 
+    private static AtomicBoolean INIT_SYSTEM = new AtomicBoolean(  );
+
 
     // cache of already instantiated entity managers
     private LoadingCache<UUID, EntityManager> entityManagers
@@ -125,7 +135,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         }
 
     }
-    
+
 
     private void init() {
 
@@ -136,7 +146,8 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
                 logger.info("Creating system application");
                 Map sysAppProps = new HashMap<String, Object>();
                 sysAppProps.put( PROPERTY_NAME, "systemapp");
-                em.create(SYSTEM_APP_ID, TYPE_APPLICATION, sysAppProps );
+                em.create( SYSTEM_APP_ID, TYPE_APPLICATION, sysAppProps );
+                em.createIndex();
                 em.getApplication();
                 em.refreshIndex();
             }
@@ -175,7 +186,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         return IMPLEMENTATION_DESCRIPTION;
     }
 
-    
+
     @Override
     public EntityManager getEntityManager(UUID applicationId) {
         try {
@@ -187,14 +198,14 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         return _getEntityManager( applicationId );
     }
 
-    
+
     private EntityManager _getEntityManager( UUID applicationId ) {
         EntityManager em = new CpEntityManager();
         em.init( this, applicationId );
         return em;
     }
 
-    
+
     @Override
     public UUID createApplication(String organizationName, String name) throws Exception {
         return createApplication( organizationName, name, null );
@@ -215,14 +226,14 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
 
         applicationId = UUIDGenerator.newTimeUUID();
 
-        logger.debug( "New application orgName {} name {} id {} ", 
+        logger.debug( "New application orgName {} name {} id {} ",
                 new Object[] { orgName, name, applicationId.toString() } );
 
         initializeApplication( orgName, applicationId, appName, properties );
         return applicationId;
     }
 
-    
+
     private String buildAppName( String organizationName, String name ) {
         return StringUtils.lowerCase( name.contains( "/" ) ? name : organizationName + "/" + name );
     }
@@ -232,9 +243,13 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     public UUID initializeApplication( String organizationName, UUID applicationId, String name,
                                        Map<String, Object> properties ) throws Exception {
 
-        
+
         EntityManager em = getEntityManager(SYSTEM_APP_ID);
 
+        //create our ES index since we're initializing this application
+        em.createIndex();
+
+
         final String appName = buildAppName( organizationName, name );
 
         // check for pre-existing application
@@ -285,12 +300,12 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     public ApplicationScope getApplicationScope( UUID applicationId ) {
 
         // We can always generate a scope, it doesn't matter if  the application exists yet or not.
-        final ApplicationScopeImpl scope = 
+        final ApplicationScopeImpl scope =
                 new ApplicationScopeImpl( generateApplicationId( applicationId ) );
 
         return scope;
     }
-    
+
 
     @Override
     public UUID importApplication(
@@ -300,19 +315,35 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         throw new UnsupportedOperationException("Not supported yet.");
     }
 
-    
-    public UUID lookupOrganization( String name) throws Exception {
+
+    public UUID lookupOrganization( String name ) throws Exception {
         init();
 
-        Query q = Query.fromQL(PROPERTY_NAME + " = '" + name + "'");
+
+        //        Query q = Query.fromQL(PROPERTY_NAME + " = '" + name + "'");
         EntityManager em = getEntityManager( SYSTEM_APP_ID );
-        Results results = em.searchCollection( em.getApplicationRef(), "organizations", q );
 
-        if ( results.isEmpty() ) {
-            return null; 
-        } 
 
-        return results.iterator().next().getUuid();
+        final EntityRef alias = em.getAlias( "organizations", name );
+
+        if ( alias == null ) {
+            return null;
+        }
+
+        final Entity entity = em.get( alias );
+
+        if ( entity == null ) {
+            return null;
+        }
+
+        return entity.getUuid();
+        //        Results results = em.searchCollection( em.getApplicationRef(), "organizations", q );
+        //
+        //        if ( results.isEmpty() ) {
+        //            return null;
+        //        }
+        //
+        //        return results.iterator().next().getUuid();
     }
 
 
@@ -320,21 +351,41 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     public UUID lookupApplication( String name ) throws Exception {
         init();
 
-        Query q = Query.fromQL( PROPERTY_NAME + " = '" + name + "'");
+        EntityManager em = getEntityManager( SYSTEM_APP_ID );
 
-        EntityManager em = getEntityManager(SYSTEM_APP_ID);
-        Results results = em.searchCollection( em.getApplicationRef(), "appinfos", q);
 
-        if ( results.isEmpty() ) {
-            return null; 
-        } 
+        final EntityRef alias = em.getAlias( "appinfos", name );
+
+        if ( alias == null ) {
+            return null;
+        }
+
+        final Entity entity = em.get( alias );
 
-        Entity entity = results.iterator().next();
-        Object uuidObject = entity.getProperty("applicationUuid"); 
-        if ( uuidObject instanceof UUID ) {
-            return (UUID)uuidObject;
+        if ( entity == null ) {
+            return null;
         }
-        return UUIDUtils.tryExtractUUID( entity.getProperty("applicationUuid").toString() );
+
+        return entity.getUuid();
+
+
+        //        Query q = Query.fromQL( PROPERTY_NAME + " = '" + name + "'");
+        //
+        //        EntityManager em = getEntityManager(SYSTEM_APP_ID);
+        //
+        //
+        //        Results results = em.searchCollection( em.getApplicationRef(), "appinfos", q);
+        //
+        //        if ( results.isEmpty() ) {
+        //            return null;
+        //        }
+        //
+        //        Entity entity = results.iterator().next();
+        //        Object uuidObject = entity.getProperty("applicationUuid");
+        //        if ( uuidObject instanceof UUID ) {
+        //            return (UUID)uuidObject;
+        //        }
+        //        return UUIDUtils.tryExtractUUID( entity.getProperty("applicationUuid").toString() );
     }
 
 
@@ -353,13 +404,13 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
 
         String edgeType = CpNamingUtils.getEdgeTypeFromCollectionName( "appinfos" );
 
-        logger.debug("getApplications(): Loading edges of edgeType {} from {}:{}", 
+        logger.debug("getApplications(): Loading edges of edgeType {} from {}:{}",
             new Object[] { edgeType, fromEntityId.getType(), fromEntityId.getUuid() } );
 
-        Observable<Edge> edges = gm.loadEdgesFromSource( new SimpleSearchByEdgeType( 
-                fromEntityId, edgeType, Long.MAX_VALUE, 
+        Observable<Edge> edges = gm.loadEdgesFromSource( new SimpleSearchByEdgeType(
+                fromEntityId, edgeType, Long.MAX_VALUE,
                 SearchByEdgeType.Order.DESCENDING, null ));
-        
+
         Iterator<Edge> iter = edges.toBlockingObservable().getIterator();
         while ( iter.hasNext() ) {
 
@@ -367,8 +418,8 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
             Id targetId = edge.getTargetNode();
 
             logger.debug("getApplications(): Processing edge from {}:{} to {}:{}", new Object[] {
-                edge.getSourceNode().getType(), edge.getSourceNode().getUuid(), 
-                edge.getTargetNode().getType(), edge.getTargetNode().getUuid() 
+                edge.getSourceNode().getType(), edge.getSourceNode().getUuid(),
+                edge.getTargetNode().getType(), edge.getTargetNode().getUuid()
             });
 
             CollectionScope collScope = new CollectionScopeImpl(
@@ -376,25 +427,25 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
                     appScope.getApplication(),
                     CpNamingUtils.getCollectionScopeNameFromCollectionName( "appinfos" ));
 
-            org.apache.usergrid.persistence.model.entity.Entity e = 
+            org.apache.usergrid.persistence.model.entity.Entity e =
                     managerCache.getEntityCollectionManager( collScope ).load( targetId )
                         .toBlockingObservable().lastOrDefault(null);
 
-            appMap.put( 
-                (String)e.getField( PROPERTY_NAME ).getValue(), 
+            appMap.put(
+                (String)e.getField( PROPERTY_NAME ).getValue(),
                 (UUID)e.getField( "applicationUuid" ).getValue());
         }
 
         return appMap;
     }
 
-    
+
     @Override
     public void setup() throws Exception {
         getSetup().init();
     }
 
-    
+
     @Override
     public Map<String, String> getServiceProperties() {
 
@@ -421,7 +472,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         return props;
     }
 
-    
+
     @Override
     public boolean updateServiceProperties(Map<String, String> properties) {
 
@@ -462,7 +513,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         return true;
     }
 
-    
+
     @Override
     public boolean setServiceProperty(final String name, final String value) {
         return updateServiceProperties( new HashMap<String, String>() {{
@@ -475,6 +526,8 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     public boolean deleteServiceProperty(String name) {
 
         EntityManager em = getEntityManager(SYSTEM_APP_ID);
+
+
         Query q = Query.fromQL("select *");
         Results results = null;
         try {
@@ -536,7 +589,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
 
     @Override
     public UUID getDefaultAppId() {
-        return DEFAULT_APPLICATION_ID; 
+        return DEFAULT_APPLICATION_ID;
     }
 
 
@@ -556,22 +609,44 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     }
 
 
+    /**
+     * TODO, these 3 methods are super janky.  During refactoring we should clean this model up
+     */
     public void refreshIndex() {
 
-        // refresh special indexes without calling EntityManager refresh because stack overflow 
-       
+        // refresh special indexes without calling EntityManager refresh because stack overflow
+        maybeCreateIndexes();
         // system app
 
-        managerCache.getEntityIndex( new ApplicationScopeImpl( new SimpleId( SYSTEM_APP_ID, "application" ) ) )
-                    .refresh();
+        for ( EntityIndex index : getManagementIndexes() ) {
+            index.refresh();
+        }
+    }
+
+
+    private void maybeCreateIndexes() {
+        // system app
+        if ( INIT_SYSTEM.getAndSet( true ) ) {
+            return;
+        }
+
+        for ( EntityIndex index : getManagementIndexes() ) {
+            index.initializeIndex();
+        }
+    }
+
 
-        // default app
-        managerCache.getEntityIndex( new ApplicationScopeImpl( new SimpleId( getManagementAppId(), "application" ) ) )
-                    .refresh();
+    private List<EntityIndex> getManagementIndexes() {
+        return Arrays.asList(
+                managerCache.getEntityIndex( new ApplicationScopeImpl( new SimpleId( SYSTEM_APP_ID, "application" ) ) ),
 
-        // management app
-        managerCache.getEntityIndex( new ApplicationScopeImpl( new SimpleId( getDefaultAppId(), "application" ) ) )
-                    .refresh();
+                // default app
+                managerCache.getEntityIndex(
+                        new ApplicationScopeImpl( new SimpleId( getManagementAppId(), "application" ) ) ),
+
+                // management app
+                managerCache.getEntityIndex(
+                        new ApplicationScopeImpl( new SimpleId( getDefaultAppId(), "application" ) ) ) );
     }
 
 
@@ -589,7 +664,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
             rebuildApplicationIndexes( appUuid, po );
         }
     }
-   
+
 
     @Override
     public void rebuildInternalIndexes(ProgressObserver po) throws Exception {
@@ -599,7 +674,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
 
     @Override
     public void rebuildApplicationIndexes( UUID appId, ProgressObserver po ) throws Exception {
-        
+
         EntityManager em = getEntityManager( appId );
         Application app = em.getApplication();
 

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java b/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
index cf53e50..289f4bd 100644
--- a/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
@@ -684,6 +684,11 @@ public interface EntityManager {
      */
     void refreshIndex();
 
+    /**
+     * Create the index, should ONLY ever be called the first time an application is created
+     */
+    void createIndex();
+
     public void init( EntityManagerFactory emf, UUID applicationId);
 
     /** For testing purposes */

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/EntityManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/EntityManagerImpl.java b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/EntityManagerImpl.java
index df201f9..d8afb17 100644
--- a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/EntityManagerImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/EntityManagerImpl.java
@@ -2907,6 +2907,13 @@ public class EntityManagerImpl implements EntityManager {
         // no action necessary
     }
 
+
+    @Override
+    public void createIndex() {
+        //no op
+    }
+
+
     @Override
     public EntityRef getGroupRoleRef( UUID ownerId, String roleName) throws Exception {
         return new SimpleEntityRef( Role.ENTITY_TYPE, SimpleRoleRef.getIdForGroupIdAndRoleName( ownerId, roleName ));

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/core/src/test/java/org/apache/usergrid/CoreApplication.java
----------------------------------------------------------------------
diff --git a/stack/core/src/test/java/org/apache/usergrid/CoreApplication.java b/stack/core/src/test/java/org/apache/usergrid/CoreApplication.java
index fd8ca9b..c790f64 100644
--- a/stack/core/src/test/java/org/apache/usergrid/CoreApplication.java
+++ b/stack/core/src/test/java/org/apache/usergrid/CoreApplication.java
@@ -151,6 +151,7 @@ public class CoreApplication implements Application, TestRule {
         assertNotNull( id );
 
         em = setup.getEmf().getEntityManager( id );
+        em.createIndex();
         assertNotNull( em );
 
         LOG.info( "Created new application {} in organization {}", appName, orgName );

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
index 6afad33..b014d51 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
@@ -302,6 +302,7 @@ public class EntityCollectionManagerIT {
 
         Id id = manager.getIdField(field).toBlocking().lastOrDefault(null);
         assertNotNull(id);
+        assertEquals(newEntity.getId(), id);
 
         Field fieldNull = new StringField("testFieldNotThere", "uniquely", true);
         id = manager.getIdField(fieldNull).toBlocking().lastOrDefault(null);

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndex.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndex.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndex.java
index 64a3e10..44ad05c 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndex.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndex.java
@@ -30,6 +30,12 @@ import org.apache.usergrid.persistence.model.entity.Id;
 public interface EntityIndex {
 
     /**
+     * This should ONLY ever be called once on application create.  Otherwise we're introducing slowness into our system
+     *
+     */
+    public void initializeIndex();
+
+    /**
      * Create the index batch
      * @return
      */

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexImpl.java
index 8e53e5c..e55f7e0 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexImpl.java
@@ -17,18 +17,24 @@
  */
 package org.apache.usergrid.persistence.index.impl;
 
+
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
 import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
+import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
+import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
 import org.elasticsearch.action.search.SearchRequestBuilder;
 import org.elasticsearch.action.search.SearchResponse;
 import org.elasticsearch.action.search.SearchScrollRequestBuilder;
 import org.elasticsearch.client.AdminClient;
 import org.elasticsearch.client.Client;
 import org.elasticsearch.common.xcontent.XContentBuilder;
+import org.elasticsearch.common.xcontent.XContentFactory;
 import org.elasticsearch.index.query.FilterBuilder;
 import org.elasticsearch.index.query.QueryBuilder;
 import org.elasticsearch.indices.IndexAlreadyExistsException;
@@ -54,16 +60,12 @@ import org.apache.usergrid.persistence.model.entity.SimpleId;
 
 import com.google.inject.Inject;
 import com.google.inject.assistedinject.Assisted;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicBoolean;
 
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.BOOLEAN_PREFIX;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.DOC_ID_SEPARATOR_SPLITTER;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.ENTITYID_FIELDNAME;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.NUMBER_PREFIX;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.STRING_PREFIX;
-import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
-import org.elasticsearch.common.xcontent.XContentFactory;
 
 
 /**
@@ -71,9 +73,9 @@ import org.elasticsearch.common.xcontent.XContentFactory;
  */
 public class EsEntityIndexImpl implements EntityIndex {
 
-    private static final Logger log = LoggerFactory.getLogger(EsEntityIndexImpl.class);
+    private static final Logger log = LoggerFactory.getLogger( EsEntityIndexImpl.class );
 
-    private static final AtomicBoolean mappingsCreated = new AtomicBoolean(false);
+    private static final AtomicBoolean mappingsCreated = new AtomicBoolean( false );
 
     private final String indexName;
 
@@ -85,110 +87,115 @@ public class EsEntityIndexImpl implements EntityIndex {
 
     private final IndexFig config;
 
-    @Inject
-    public EsEntityIndexImpl(
-            @Assisted final ApplicationScope appScope, 
-            final IndexFig config, 
-            final EsProvider provider) {
-
-        ValidationUtils.validateApplicationScope(appScope);
 
-        try {
-            this.applicationScope = appScope;
-            this.client = provider.getClient();
-            this.config = config;
-            this.cursorTimeout = config.getQueryCursorTimeout();
-            this.indexName = IndexingUtils.createIndexName(config.getIndexPrefix(), appScope);
+    @Inject
+    public EsEntityIndexImpl( @Assisted final ApplicationScope appScope, final IndexFig config,
+                              final EsProvider provider ) {
 
-            initIndex();
+        ValidationUtils.validateApplicationScope( appScope );
 
-        } catch ( IOException ex ) {
-            throw new RuntimeException("Error initializing ElasticSearch mappings or index", ex);
-        }
+        this.applicationScope = appScope;
+        this.client = provider.getClient();
+        this.config = config;
+        this.cursorTimeout = config.getQueryCursorTimeout();
+        this.indexName = IndexingUtils.createIndexName( config.getIndexPrefix(), appScope );
     }
 
 
-    private void initIndex() throws IOException {
+    @Override
+    public void initializeIndex() {
 
         try {
-            if ( !mappingsCreated.getAndSet(true) ) {
+            if ( !mappingsCreated.getAndSet( true ) ) {
                 createMappings();
             }
 
             AdminClient admin = client.admin();
-            CreateIndexResponse cir = admin.indices().prepareCreate(indexName).execute().actionGet();
-            log.debug("Created new Index Name [{}] ACK=[{}]", indexName, cir.isAcknowledged());
-
-            admin.indices().prepareRefresh(indexName).execute().actionGet();
+            CreateIndexResponse cir = admin.indices().prepareCreate( indexName ).execute().actionGet();
+            log.debug( "Created new Index Name [{}] ACK=[{}]", indexName, cir.isAcknowledged() );
 
-            try {
-                // TODO: figure out what refresh above is not enough to ensure index is ready
-                Thread.sleep(500);
-            } catch (InterruptedException ex) {}
+            RefreshResponse response;
 
-        } catch ( IndexAlreadyExistsException expected ) {
-            // this is expected to happen if index already exists
+            do {
+                response = admin.indices().prepareRefresh( indexName ).execute().actionGet();
+            }
+            while ( response.getFailedShards() != 0 );
+            //
+            //            response.getFailedShards();
+            //
+            //            try {
+            //                // TODO: figure out what refresh above is not enough to ensure index is ready
+            //                Thread.sleep( 500 );
+            //            }
+            //            catch ( InterruptedException ex ) {
+            //            }
+        }
+        catch ( IndexAlreadyExistsException expected ) {
+            // this is expected to happen if index already exists, it's a no-op and swallow
+        }
+        catch ( IOException e ) {
+            throw new RuntimeException( "Unable to initialize index", e );
         }
     }
 
 
     /**
-     * Setup ElasticSearch type mappings as a template that applies to all new indexes.
-     * Applies to all indexes that start with our prefix.
+     * Setup ElasticSearch type mappings as a template that applies to all new indexes. Applies to all indexes that
+     * start with our prefix.
      */
     private void createMappings() throws IOException {
 
-        XContentBuilder xcb = IndexingUtils.createDoubleStringIndexMapping(
-            XContentFactory.jsonBuilder(), "_default_");
+        XContentBuilder xcb =
+                IndexingUtils.createDoubleStringIndexMapping( XContentFactory.jsonBuilder(), "_default_" );
 
-        PutIndexTemplateResponse pitr = client.admin().indices()
-            .preparePutTemplate("usergrid_template")
-            .setTemplate(config.getIndexPrefix() + "*") 
-            .addMapping("_default_", xcb) // set mapping as the default for all types
-            .execute()
-            .actionGet();
+        PutIndexTemplateResponse pitr = client.admin().indices().preparePutTemplate( "usergrid_template" )
+                                              .setTemplate( config.getIndexPrefix() + "*" ).addMapping( "_default_",
+                        xcb ) // set mapping as the default for all types
+                .execute().actionGet();
     }
 
 
     @Override
     public EntityIndexBatch createBatch() {
-        return new EsEntityIndexBatchImpl(applicationScope, client, config, 1000);
+        return new EsEntityIndexBatchImpl( applicationScope, client, config, 1000 );
     }
 
+
     @Override
-    public CandidateResults search(final IndexScope indexScope, final Query query) {
+    public CandidateResults search( final IndexScope indexScope, final Query query ) {
 
-        final String indexType = IndexingUtils.createCollectionScopeTypeName(indexScope);
+        final String indexType = IndexingUtils.createCollectionScopeTypeName( indexScope );
 
         QueryBuilder qb = query.createQueryBuilder();
 
-        if (log.isDebugEnabled()) {
-            log.debug("Searching index {}\n   type {}\n   query {} limit {}", new Object[]{
-                this.indexName, indexType, qb.toString().replace("\n", " "), query.getLimit()
-            });
+        if ( log.isDebugEnabled() ) {
+            log.debug( "Searching index {}\n   type {}\n   query {} limit {}", new Object[] {
+                    this.indexName, indexType, qb.toString().replace( "\n", " " ), query.getLimit()
+            } );
         }
 
         SearchResponse searchResponse;
-        if (query.getCursor() == null) {
+        if ( query.getCursor() == null ) {
 
-            SearchRequestBuilder srb
-                    = client.prepareSearch(indexName).setTypes(indexType).setScroll(cursorTimeout + "m")
-                    .setQuery(qb);
+            SearchRequestBuilder srb =
+                    client.prepareSearch( indexName ).setTypes( indexType ).setScroll( cursorTimeout + "m" )
+                          .setQuery( qb );
 
             FilterBuilder fb = query.createFilterBuilder();
-            if (fb != null) {
-                log.debug("   Filter: {} ", fb.toString());
-                srb = srb.setPostFilter(fb);
+            if ( fb != null ) {
+                log.debug( "   Filter: {} ", fb.toString() );
+                srb = srb.setPostFilter( fb );
             }
 
-            srb = srb.setFrom(0).setSize(query.getLimit());
+            srb = srb.setFrom( 0 ).setSize( query.getLimit() );
 
-            for (Query.SortPredicate sp : query.getSortPredicates()) {
+            for ( Query.SortPredicate sp : query.getSortPredicates() ) {
 
                 final SortOrder order;
-                if (sp.getDirection().equals(Query.SortDirection.ASCENDING)) {
+                if ( sp.getDirection().equals( Query.SortDirection.ASCENDING ) ) {
                     order = SortOrder.ASC;
-                } else {
+                }
+                else {
                     order = SortOrder.DESC;
                 }
 
@@ -197,91 +204,94 @@ public class EsEntityIndexImpl implements EntityIndex {
                 // that you can order by: string, number and boolean and we ask ElasticSearch 
                 // to ignore any fields that are not present.
                 final String stringFieldName = STRING_PREFIX + sp.getPropertyName();
-                final FieldSortBuilder stringSort
-                        = SortBuilders.fieldSort(stringFieldName).order(order).ignoreUnmapped(true);
-                srb.addSort(stringSort);
-                log.debug("   Sort: {} order by {}", stringFieldName, order.toString());
+                final FieldSortBuilder stringSort =
+                        SortBuilders.fieldSort( stringFieldName ).order( order ).ignoreUnmapped( true );
+                srb.addSort( stringSort );
+                log.debug( "   Sort: {} order by {}", stringFieldName, order.toString() );
 
                 final String numberFieldName = NUMBER_PREFIX + sp.getPropertyName();
-                final FieldSortBuilder numberSort
-                        = SortBuilders.fieldSort(numberFieldName).order(order).ignoreUnmapped(true);
-                srb.addSort(numberSort);
-                log.debug("   Sort: {} order by {}", numberFieldName, order.toString());
+                final FieldSortBuilder numberSort =
+                        SortBuilders.fieldSort( numberFieldName ).order( order ).ignoreUnmapped( true );
+                srb.addSort( numberSort );
+                log.debug( "   Sort: {} order by {}", numberFieldName, order.toString() );
 
                 final String booleanFieldName = BOOLEAN_PREFIX + sp.getPropertyName();
-                final FieldSortBuilder booleanSort
-                        = SortBuilders.fieldSort(booleanFieldName).order(order).ignoreUnmapped(true);
-                srb.addSort(booleanSort);
-                log.debug("   Sort: {} order by {}", booleanFieldName, order.toString());
+                final FieldSortBuilder booleanSort =
+                        SortBuilders.fieldSort( booleanFieldName ).order( order ).ignoreUnmapped( true );
+                srb.addSort( booleanSort );
+                log.debug( "   Sort: {} order by {}", booleanFieldName, order.toString() );
             }
 
             searchResponse = srb.execute().actionGet();
-        } else {
+        }
+        else {
             String scrollId = query.getCursor();
-            if (scrollId.startsWith("\"")) {
-                scrollId = scrollId.substring(1);
+            if ( scrollId.startsWith( "\"" ) ) {
+                scrollId = scrollId.substring( 1 );
             }
-            if (scrollId.endsWith("\"")) {
-                scrollId = scrollId.substring(0, scrollId.length() - 1);
+            if ( scrollId.endsWith( "\"" ) ) {
+                scrollId = scrollId.substring( 0, scrollId.length() - 1 );
             }
-            log.debug("Executing query with cursor: {} ", scrollId);
+            log.debug( "Executing query with cursor: {} ", scrollId );
 
-            SearchScrollRequestBuilder ssrb = 
-                    client.prepareSearchScroll(scrollId).setScroll(cursorTimeout + "m");
+            SearchScrollRequestBuilder ssrb = client.prepareSearchScroll( scrollId ).setScroll( cursorTimeout + "m" );
             searchResponse = ssrb.execute().actionGet();
         }
 
         SearchHits hits = searchResponse.getHits();
-        log.debug("   Hit count: {} Total hits: {}", hits.getHits().length, hits.getTotalHits());
+        log.debug( "   Hit count: {} Total hits: {}", hits.getHits().length, hits.getTotalHits() );
 
         List<CandidateResult> candidates = new ArrayList<CandidateResult>();
 
-        for (SearchHit hit : hits.getHits()) {
+        for ( SearchHit hit : hits.getHits() ) {
 
-            String[] idparts = hit.getId().split(DOC_ID_SEPARATOR_SPLITTER);
+            String[] idparts = hit.getId().split( DOC_ID_SEPARATOR_SPLITTER );
             String id = idparts[0];
             String type = idparts[1];
             String version = idparts[2];
 
-            Id entityId = new SimpleId(UUID.fromString(id), type);
+            Id entityId = new SimpleId( UUID.fromString( id ), type );
 
-            candidates.add(new CandidateResult(entityId, UUID.fromString(version)));
+            candidates.add( new CandidateResult( entityId, UUID.fromString( version ) ) );
         }
 
-        CandidateResults candidateResults = new CandidateResults(query, candidates);
+        CandidateResults candidateResults = new CandidateResults( query, candidates );
 
-        if (candidates.size() >= query.getLimit()) {
-            candidateResults.setCursor(searchResponse.getScrollId());
-            log.debug("   Cursor = " + searchResponse.getScrollId());
+        if ( candidates.size() >= query.getLimit() ) {
+            candidateResults.setCursor( searchResponse.getScrollId() );
+            log.debug( "   Cursor = " + searchResponse.getScrollId() );
         }
 
         return candidateResults;
     }
 
+
     public void refresh() {
-        client.admin().indices().prepareRefresh(indexName).execute().actionGet();
-        log.debug("Refreshed index: " + indexName);
+        client.admin().indices().prepareRefresh( indexName ).execute().actionGet();
+        log.debug( "Refreshed index: " + indexName );
     }
 
+
     @Override
-    public CandidateResults getEntityVersions(final IndexScope scope, final Id id) {
+    public CandidateResults getEntityVersions( final IndexScope scope, final Id id ) {
         Query query = new Query();
-        query.addEqualityFilter(ENTITYID_FIELDNAME, id.getUuid().toString());
-        CandidateResults results = search(scope, query);
+        query.addEqualityFilter( ENTITYID_FIELDNAME, id.getUuid().toString() );
+        CandidateResults results = search( scope, query );
         return results;
     }
 
+
     /**
      * For testing only.
      */
     public void deleteIndex() {
         AdminClient adminClient = client.admin();
-        DeleteIndexResponse response = adminClient.indices().prepareDelete(indexName).get();
-        if (response.isAcknowledged()) {
-            log.info("Deleted index: " + indexName);
-        } else {
-            log.info("Failed to delete index " + indexName);
+        DeleteIndexResponse response = adminClient.indices().prepareDelete( indexName ).get();
+        if ( response.isAcknowledged() ) {
+            log.info( "Deleted index: " + indexName );
+        }
+        else {
+            log.info( "Failed to delete index " + indexName );
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/corepersistence/queryindex/src/test/java/org/apache/usergrid/persistence/index/impl/EntityIndexTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/test/java/org/apache/usergrid/persistence/index/impl/EntityIndexTest.java b/stack/corepersistence/queryindex/src/test/java/org/apache/usergrid/persistence/index/impl/EntityIndexTest.java
index 78cb1ae..6a82c65 100644
--- a/stack/corepersistence/queryindex/src/test/java/org/apache/usergrid/persistence/index/impl/EntityIndexTest.java
+++ b/stack/corepersistence/queryindex/src/test/java/org/apache/usergrid/persistence/index/impl/EntityIndexTest.java
@@ -101,6 +101,7 @@ public class EntityIndexTest extends BaseIT {
 
 
         EntityIndex entityIndex = cif.createEntityIndex( applicationScope );
+        entityIndex.initializeIndex();
 
         InputStream is = this.getClass().getResourceAsStream( "/sample-large.json" );
         ObjectMapper mapper = new ObjectMapper();
@@ -155,6 +156,7 @@ public class EntityIndexTest extends BaseIT {
         IndexScope indexScope = new IndexScopeImpl( appId, "fastcars" );
 
         EntityIndex entityIndex = cif.createEntityIndex( applicationScope );
+        entityIndex.initializeIndex();
 
         Map entityMap = new HashMap() {{
             put( "name", "Ferrari 212 Inter" );
@@ -283,6 +285,7 @@ public class EntityIndexTest extends BaseIT {
 
 
         EntityIndex entityIndex = cif.createEntityIndex( applicationScope );
+        entityIndex.initializeIndex();
 
         final String middleName = "middleName" + UUIDUtils.newTimeUUID();
         Map<String, Object> properties = new LinkedHashMap<String, Object>();
@@ -332,6 +335,7 @@ public class EntityIndexTest extends BaseIT {
         IndexScope appScope = new IndexScopeImpl( ownerId, "user" );
 
         EntityIndex ei = cif.createEntityIndex( applicationScope );
+        ei.initializeIndex();
 
         final String middleName = "middleName" + UUIDUtils.newTimeUUID();
 
@@ -375,6 +379,7 @@ public class EntityIndexTest extends BaseIT {
         IndexScope appScope = new IndexScopeImpl( ownerId, "user" );
 
         EntityIndex ei = cif.createEntityIndex( applicationScope );
+        ei.createBatch();
 
         // Bill has favorites as string, age as string and retirement goal as number
         Map billMap = new HashMap() {{

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d824ee21/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
----------------------------------------------------------------------
diff --git 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
index 293e65a..34925b0 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
@@ -451,7 +451,7 @@ public class ManagementServiceImpl implements ManagementService {
                                                              String email, String password, boolean activated,
                                                              boolean disabled ) throws Exception {
         logger.debug("createOwnerAndOrganization2");
-        return createOwnerAndOrganization( organizationName, username, name, email, password, 
+        return createOwnerAndOrganization( organizationName, username, name, email, password,
                 activated, disabled, null, null );
     }
 
@@ -497,7 +497,7 @@ public class ManagementServiceImpl implements ManagementService {
             else {
                 user = createAdminUserInternal( username, name, email, password, activated, disabled, userProperties );
             }
-            
+
             logger.debug("User created");
             organization = createOrganizationInternal( organizationName, user, true, organizationProperties );
         }
@@ -575,7 +575,7 @@ public class ManagementServiceImpl implements ManagementService {
             logger.debug("user = null");
             return null;
         }
-        
+
         Lock groupLock =
                 getUniqueUpdateLock( lockManager, smf.getManagementAppId(), organizationName, "groups", PROPERTY_PATH );
         EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
@@ -828,13 +828,13 @@ public class ManagementServiceImpl implements ManagementService {
 
         writeUserMongoPassword( smf.getManagementAppId(), user, mongoPassword );
 
-        UserInfo userInfo = new UserInfo( 
+        UserInfo userInfo = new UserInfo(
             smf.getManagementAppId(), user.getUuid(), user.getUsername(), user.getName(),
             user.getEmail(), user.getConfirmed(), user.getActivated(), user.getDisabled(),
             user.getDynamicProperties(), true );
 
         // special case for sysadmin and test account only
-        if (    !user.getEmail().equals( properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL ) ) 
+        if (    !user.getEmail().equals( properties.getProperty( PROPERTIES_SYSADMIN_LOGIN_EMAIL ) )
              && !user.getEmail().equals( properties .getProperty( PROPERTIES_TEST_ACCOUNT_ADMIN_USER_EMAIL ) ) ) {
             this.startAdminUserActivationFlow( userInfo );
         }
@@ -947,7 +947,7 @@ public class ManagementServiceImpl implements ManagementService {
                 entity.getName(), ( String ) entity.getProperty( "email" ),
                 ConversionUtils.getBoolean( entity.getProperty( "confirmed" ) ),
                 ConversionUtils.getBoolean( entity.getProperty( "activated" ) ),
-                ConversionUtils.getBoolean( entity.getProperty( "disabled" ) ), 
+                ConversionUtils.getBoolean( entity.getProperty( "disabled" ) ),
                 entity.getDynamicProperties(),
                 ConversionUtils.getBoolean( entity.getProperty( "admin" )));
     }
@@ -1239,7 +1239,7 @@ public class ManagementServiceImpl implements ManagementService {
         int size = 0;
         EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
 
-        Results orgResults = em.getCollection( new SimpleEntityRef( User.ENTITY_TYPE, userId ), 
+        Results orgResults = em.getCollection( new SimpleEntityRef( User.ENTITY_TYPE, userId ),
                 "groups", null, 10000, Level.REFS, false );
 
         logger.debug( "    orgResults.size() = " +  orgResults.size() );
@@ -1410,11 +1410,11 @@ public class ManagementServiceImpl implements ManagementService {
 
     public Entity getEntityFromPrincipal( AuthPrincipalInfo principal ) throws Exception {
 
-        EntityManager em = emf.getEntityManager( 
-            principal.getApplicationId() != null 
+        EntityManager em = emf.getEntityManager(
+            principal.getApplicationId() != null
                 ? principal.getApplicationId() : smf.getManagementAppId() );
 
-        Entity entity = em.get( new SimpleEntityRef( 
+        Entity entity = em.get( new SimpleEntityRef(
                 principal.getType().getEntityType(), principal.getUuid()));
 
         return entity;
@@ -1430,7 +1430,7 @@ public class ManagementServiceImpl implements ManagementService {
 
     /*
    * (non-Javadoc)
-   * 
+   *
    * @see
    * org.apache.usergrid.management.ManagementService#revokeAccessTokensForAdminUser
    * (java.util.UUID)
@@ -1687,8 +1687,8 @@ public class ManagementServiceImpl implements ManagementService {
 
         EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
 
-        Results r = em.getConnectingEntities( 
-                new SimpleEntityRef(APPLICATION_INFO, applicationInfoId), 
+        Results r = em.getConnectingEntities(
+                new SimpleEntityRef(APPLICATION_INFO, applicationInfoId),
                 "owns", "group", Level.ALL_PROPERTIES );
 
         Entity entity = r.getEntity();
@@ -1709,8 +1709,8 @@ public class ManagementServiceImpl implements ManagementService {
         final BiMap<UUID, String> applications = HashBiMap.create();
         final EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
 
-        final Results results = em.getConnectedEntities( 
-                new SimpleEntityRef(Group.ENTITY_TYPE, organizationGroupId), 
+        final Results results = em.getConnectedEntities(
+                new SimpleEntityRef(Group.ENTITY_TYPE, organizationGroupId),
                 "owns", APPLICATION_INFO, Level.ALL_PROPERTIES );
 
         final PagingResultsIterator itr = new PagingResultsIterator( results );
@@ -1852,7 +1852,7 @@ public class ManagementServiceImpl implements ManagementService {
 
     public String getSecret( UUID applicationId, AuthPrincipalType type, UUID entityId ) throws Exception {
 
-        if ( AuthPrincipalType.ORGANIZATION.equals( type )) {  
+        if ( AuthPrincipalType.ORGANIZATION.equals( type )) {
             UUID ownerId = smf.getManagementAppId();
             return getCredentialsSecret( readUserToken( ownerId, entityId, Group.ENTITY_TYPE ) );
 
@@ -2440,7 +2440,7 @@ public class ManagementServiceImpl implements ManagementService {
 
     /*
    * (non-Javadoc)
-   * 
+   *
    * @see
    * org.apache.usergrid.management.ManagementService#revokeAccessTokensForAappUser
    * (java.util.UUID, java.util.UUID)
@@ -2798,7 +2798,7 @@ public class ManagementServiceImpl implements ManagementService {
 
     /*
    * (non-Javadoc)
-   * 
+   *
    * @see
    * org.apache.usergrid.management.ManagementService#setOrganizationProps(java.util
    * .UUID, java.util.Map)
@@ -2821,7 +2821,7 @@ public class ManagementServiceImpl implements ManagementService {
 
     /*
    * (non-Javadoc)
-   * 
+   *
    * @see
    * org.apache.usergrid.management.ManagementService#getOrganizationProps(java.util
    * .UUID)