You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by gr...@apache.org on 2016/04/08 22:20:48 UTC

[01/36] usergrid git commit: Adding in beginning test.

Repository: usergrid
Updated Branches:
  refs/heads/release-2.1.1 29d7660ee -> 74de4bca3


Adding in beginning test.


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

Branch: refs/heads/release-2.1.1
Commit: 56e03718a911a6a1215fa75522b54ad694c4b566
Parents: b9e8088
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 3 08:20:30 2016 -0800
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:05:30 2016 -0700

----------------------------------------------------------------------
 .../persistence/cassandra/ApplicationCF.java    |  7 +-
 .../rest/applications/ServiceResource.java      | 32 +++++++++
 .../collection/CollectionsResourceIT.java       | 69 +++++++++++++++-----
 3 files changed, 91 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/56e03718/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
index 5dbe4b5..ad72717 100644
--- a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
+++ b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
@@ -44,7 +44,12 @@ public enum ApplicationCF implements CFEnum {
     APPLICATION_AGGREGATE_COUNTERS( "Application_Aggregate_Counters", "LongType", COUNTERTYPE.getClassName() ),
 
     /** Entity counters */
-    ENTITY_COUNTERS( "Entity_Counters", "BytesType", COUNTERTYPE.getClassName() ),;
+    ENTITY_COUNTERS( "Entity_Counters", "BytesType", COUNTERTYPE.getClassName() );
+
+    /**
+     * Collection Schema
+     */
+    COL_SCHEMA( "")
 
     private final String cf;
     private final String comparator;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/56e03718/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
index 4c92fef..2843417 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
@@ -353,6 +353,38 @@ public class ServiceResource extends AbstractContextResource {
     }
 
 
+    /**
+     * THE BEGINNINGS OF AN ENDPOINT THAT WILL ALLOW TO DEFINE WHAT TO
+     * STORE IN ELASTICSEARCH.
+     * @param ui
+     * @param callback
+     * @return
+     * @throws Exception
+     */
+    @POST
+    @Path("_indexes")
+    @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executePostOnIndexes( @Context UriInfo ui,
+                                   @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.executePostOnIndexes" );
+        }
+
+        ApiResponse response = createApiResponse();
+
+        response.setAction( "post" );
+        response.setApplication( services.getApplication() );
+        response.setParams( ui.getQueryParameters() );
+
+        executeServiceRequest( ui, response, ServiceAction.POST, null );
+
+        return response;
+    }
+
     @SuppressWarnings({ "unchecked" })
     public ServicePayload getPayload( Object json ) {
         ServicePayload payload = null;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/56e03718/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 9752035..ca5360d 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -38,6 +38,8 @@ import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Set;
+import java.util.ArrayList;
+
 
 import static org.junit.Assert.*;
 
@@ -112,33 +114,68 @@ public class CollectionsResourceIT extends AbstractRestIT {
     }
 
 
+    /**
+     * Create test collection
+     * Give collection an indexing schema
+     * Give collection a new entity and ensure it only indexes wht is in the schema
+     * Reindex and make sure old entity with full text indexing is reindexed with the schema.
+     *
+     * @throws Exception
+     */
     @Test
     public void postToReservedField() throws Exception {
+
+        //Create test collection with test entity that is full text indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", "12/31/9999" );
+        //this field shouldn't persist after reindexing.
+        testEntity.put( "two","2015-04-20T17:41:38.035Z" );
+
+        //TODO: add arrays to the indexing test
+        //testEntity.put("array","array stuff here");
+
+        Entity returnedEntity = this.app().collection( "testCollection" ).post( testEntity );
+
+        //Creating schema.
+        //this could be changed to a hashmap.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "one" );
+
+        //TODO: add indexing array to the backend/test once you finish the regular selective indexing.
+        //indexingArray.add( "field.three.index.array" );
+
+        //field "fields" is required.
         Entity payload = new Entity();
-        payload.put( "term_date", "12/31/9999" );
-        payload.put( "effective_date","2015-04-20T17:41:38.035Z" );
-        payload.put("junk","TEST");
+        payload.put( "fields", indexingArray);
 
-        this.app().collection( "testCollection" ).post( payload );
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
-        Thread.sleep( 1000 );
 
-        Collection collection = this.app().collection( "testCollection" ).get();
+        //Below is what needs to be implemented along with the index call above
 
-        assertNotEquals(0, collection.getNumOfEntities() );
+        //Get the collection schema and verify that it contains the same schema as posted above.
+        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
 
-        payload = new Entity();
-        payload.put( "term_date","1991-17-10" );
-        payload.put( "effective_date","HELLO WORLD!" );
-        payload.put("junk","TEST");
+        Entity testCollectionSchema = (Entity)collection.getResponse().getEntity();
+        //the below will have to be replaced by the values that I deem correct.
+        assertEquals( "lastUpdated", testCollectionSchema.get( "lastUpdated" ));
+        assertEquals( "lastUpdatedBy",testCollectionSchema.get( "lastUpdatedBy" ) );
+        assertEquals( "lastReindex",testCollectionSchema.get( "lastReindex" ) );
 
-        this.app().collection( "testCollection" ).post( payload );
-        refreshIndex();
-        Thread.sleep( 1000 );
 
-        collection = this.app().collection( "testCollection" ).get();
+        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+        assertEquals( "one",schema.get( 0 ) );
+
+        //Reindex and verify that the entity only has field one index.
+        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+
+        refreshIndex();
 
-        assertEquals( 2, collection.getNumOfEntities() );
+        Entity reindexedEntity = this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
+        assertEquals( "12/31/9999",reindexedEntity.get( "one" ) );
+        assertNull( reindexedEntity.get( "two" ) );
+        //not sure if this should have some kind of sleep here because this reindex will be heavily throttled.
 
     }
 


[33/36] usergrid git commit: Merge branch 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid into selectiveIndexingCherryPicked

Posted by gr...@apache.org.
Merge branch 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid into selectiveIndexingCherryPicked

# By Michael Russo (2) and Mike Dunker (1)
# Via Michael Russo
* 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid:
  Fix cache invalidation issues.
  Introduce an in-memory cache for Shiro.
  Remove extra update of token access time in OAuth2AccessTokenSecurityFilter.


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

Branch: refs/heads/release-2.1.1
Commit: e5ae2a57d15a5bae44d96ff41e167a70df353790
Parents: fc312bd 43d8559
Author: George Reyes <gr...@apache.org>
Authored: Fri Apr 1 12:28:48 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Fri Apr 1 12:28:48 2016 -0700

----------------------------------------------------------------------
 .../main/resources/usergrid-default.properties  | 10 +++
 .../rest/applications/ServiceResource.java      |  5 +-
 .../OAuth2AccessTokenSecurityFilter.java        |  3 +-
 .../rest/applications/ApplicationCreateIT.java  |  3 +-
 .../collection/users/PermissionsResourceIT.java |  2 +
 .../rest/test/resource/AbstractRestIT.java      |  1 +
 .../cassandra/ManagementServiceImpl.java        | 16 +++-
 .../usergrid/security/shiro/ShiroCache.java     | 41 ++++++++--
 .../security/shiro/ShiroCacheManager.java       | 15 +++-
 .../security/shiro/utils/LocalShiroCache.java   | 80 ++++++++++++++++++++
 .../usergrid/security/tokens/TokenService.java  |  3 +
 .../tokens/cassandra/TokenServiceImpl.java      | 40 ++++++----
 .../usergrid/services/AbstractService.java      |  3 +
 .../usergrid/services/groups/GroupsService.java |  4 +
 .../usergrid/services/roles/RolesService.java   |  2 +
 .../usergrid/services/users/UsersService.java   |  2 +
 .../services/users/roles/RolesService.java      |  4 +
 .../resources/usergrid-services-context.xml     | 11 ++-
 .../resources/usergrid-custom-test.properties   |  1 +
 19 files changed, 209 insertions(+), 37 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/e5ae2a57/stack/config/src/main/resources/usergrid-default.properties
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/usergrid/blob/e5ae2a57/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/usergrid/blob/e5ae2a57/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
----------------------------------------------------------------------


[09/36] usergrid git commit: Added most recent changes and a test that exposes potential issue when selective indexing properties.

Posted by gr...@apache.org.
Added most recent changes and a test that exposes potential issue when selective indexing properties.


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

Branch: refs/heads/release-2.1.1
Commit: 14912644ac3d2c5098a0a512cba9f638666db155
Parents: c0b96a5
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 18 09:52:21 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:32 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 148 +++++++++----------
 .../collection/CollectionsResourceIT.java       |  54 +++++++
 2 files changed, 120 insertions(+), 82 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/14912644/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 8d7a541..6722dbe 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -196,14 +196,16 @@ public class IndexServiceImpl implements IndexService {
 
         MapManager mm = mapManagerFactory.createMapManager( ms );
 
-        String jsonMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
+        //determines is the map manager has a collection schema associated with it.
+        String jsonSchemaMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
 
         Set<String> defaultProperties = null;
         ArrayList fieldsToKeep = null;
 
-        if(jsonMap != null) {
+        //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
+        if(jsonSchemaMap != null) {
 
-            Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
+            Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
             Schema schema = Schema.getDefaultSchema();
             defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
             //TODO: additional logic to
@@ -213,105 +215,87 @@ public class IndexServiceImpl implements IndexService {
         else
             return null;
 
+
         Map<String, Object> map = indexOperation.convertedEntityToBeIndexed( applicationScope,indexEdge,entity );
         HashSet mapFields = ( HashSet ) map.get( "fields" );
 
         if(defaultProperties!=null) {
             final Set<String> finalDefaultProperties = defaultProperties;
+            //the iterator is based off of this valu
             Iterator collectionIterator = mapFields.iterator();
+
+            //TODO:I think there is a bug when we modify it and continue iterating then it fails
+            //Loop that goes through all the fields that the passed in entity contains
             while ( collectionIterator.hasNext() ) {
                 EntityField testedField = ( EntityField ) collectionIterator.next();
                 String fieldName = ( String ) (testedField).get( "name" );
 
-                //TODO: need to change the logic here such that default properties does a check against each every field.
-                //it is very likely that the below does O(n) comparisons anyways so doing it for each value in a loop
-                //would be the right equivalent here. Even if it isn't very efficient.
-                //maybe if it was a hashmap, and if the hashmap didn't contain the value then we remove the field.
-                //but now for each hash value we have to do a check to see it doesn't start with a certain value.
-                //making this an O(n) operation anyways.
-
-                //so for each value in the finalDefaultProperties check to see if it matches the current property
-                //then if it doesn't do a split of the properties and see if any of them match for the split
-                //if they do match then allow in, otherwise don't allow.
-
                 //will only enter the loop for properties that aren't default properties so we only need to check
                 //the properties that the user imposed.
                 if ( !finalDefaultProperties.contains( fieldName ) ) {
+                    innerLoop( fieldsToKeep, mapFields, testedField, fieldName );
+                }
+            }
+        }
+        return map;
+    }
 
-                    //loop through and string split it all and if they still dont' match after that loop then remove them.
-                    boolean toRemoveFlag = true;
-                    String[] flattedStringArray = fieldName.split( "\\." );
-                    Iterator fieldIterator = fieldsToKeep.iterator();
-                    while(fieldIterator.hasNext()) {
-                        String requiredInclusionString = ( String ) fieldIterator.next();
-                        String[] flattedRequirementString = new String[0];
-
-                        if(!requiredInclusionString.contains( "." )){
-                            flattedRequirementString = new String[]{requiredInclusionString};
-                        }
-                        else {
-                             flattedRequirementString= requiredInclusionString.split( "\\." );
-                        }
-
-                        //what we're aiming to do here is check the entire length of the string against
-                        //
-                        for ( int index = 0; index < flattedRequirementString.length;index++){
-                            //if the array contains a string that it is equals to then set the remove flag to true
-                            //otherwise remain false.
-
-                            //TODO: document that whatever comes first in the index will be filtered out in the way specified
-                            //so if the filtering spec had to filter one and one.two.three. and there is a value of
-                            // one.three. Then it will be filtered out because the rule one.two.three is applied
-                            //without a reference or care that one exists.
-                            if(flattedStringArray.length <= index){
-                                toRemoveFlag = true;
-                                break;
-                            }
-                            //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
-                            if(flattedRequirementString[index].equals( flattedStringArray[index] )){
-                                toRemoveFlag=false;
-                            }
-                            else{
-                                toRemoveFlag=true;
-                            }
-                        }
-                        if(toRemoveFlag==false){
-                            break;
-                        }
-                    }
 
-                    if(toRemoveFlag){
-                        mapFields.remove( testedField );
-                    }
+    private void innerLoop( final ArrayList fieldsToKeep, final HashSet mapFields, final EntityField testedField,
+                            final String fieldName ) {//loop through and string split it all and if they still dont' match after that loop then remove them.
+        boolean toRemoveFlag = true;
+        String[] flattedStringArray = null;
 
-                }
+        if(!fieldName.contains( "." )){
+            //create a single array that is made of a the single value.
+            flattedStringArray = new String[]{fieldName};
+        }
+        else {
+            flattedStringArray= fieldName.split( "\\." );
+        }
 
+        Iterator fieldIterator = fieldsToKeep.iterator();
 
-//                Iterator iterator = finalDefaultProperties.iterator();
-//                while(iterator.hasNext()){
-//                    String includedFieldName = ( String ) iterator.next();
-//                    //if the field name
-//                    if(!includedFieldName.equals( fieldName )){
-//
-//                    }
-//
-//                }
-
-//                for(int index = 0; index < finalDefaultProperties.size();index++){
-//                    finalDefaultProperties.
-//
-//                }
-
-//
-//                if ( !finalDefaultProperties.contains( fieldName ) ) {
-//                    mapFields.remove( testedField );
-//                }
-//                else{
-//
-//                }
+        //goes through a loop of all the fields ( excluding default ) that we want to query on
+        while(fieldIterator.hasNext()) {
+            String requiredInclusionString = ( String ) fieldIterator.next();
+            String[] flattedRequirementString;
+
+            //in the case you only have a filter that is a single field.Otherwise split it.
+            if(!requiredInclusionString.contains( "." )){
+                flattedRequirementString = new String[]{requiredInclusionString};
+            }
+            else {
+                 flattedRequirementString= requiredInclusionString.split( "\\." );
+            }
+
+
+            //loop each split array value to see if it matches an equivalent value
+            //in the field.
+            for ( int index = 0; index < flattedRequirementString.length;index++){
+                //if the array contains a string that it is equals to then set the remove flag to true
+                //otherwise remain false.
+
+                if(flattedStringArray.length <= index){
+                    toRemoveFlag = true;
+                    break;
+                }
+                //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
+                if(flattedRequirementString[index].equals( flattedStringArray[index] )){
+                    toRemoveFlag=false;
+                }
+                else{
+                    toRemoveFlag=true;
+                }
+            }
+            if(toRemoveFlag==false){
+                break;
             }
         }
-        return map;
+
+        if(toRemoveFlag){
+            mapFields.remove( testedField );
+        }
     }
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/14912644/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 7e29016..6d8a5e6 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -327,6 +327,60 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
     }
 
+    @Test
+    public void postToCollectionSchemaArrayWithSelectiveTopLevelIndexing() throws Exception {
+
+        //Include the property labeled two to be index.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "two" );
+        //this should work such that one.key and one.anotherKey should work.
+        indexingArray.add( "one.key" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        Map<String,Object> arrayFieldsForTestingSelectiveIndexing = new HashMap<>();
+
+        arrayFieldsForTestingSelectiveIndexing.put( "wowMoreKeys","value" );
+        arrayFieldsForTestingSelectiveIndexing.put( "thisShouldBeQueryableToo","value2");
+
+        Map<String,Object> arrayFieldsForTesting = new HashMap<>();
+
+        arrayFieldsForTesting.put( "key",arrayFieldsForTestingSelectiveIndexing );
+        arrayFieldsForTesting.put( "anotherKey","value2");
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", arrayFieldsForTesting );
+        testEntity.put( "two","query" );
+
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "one.key.wowMoreKeys = 'value'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "value2",((Map)reindexedEntity.get( "one" )).get( "anotherKey" ) );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        //TODO: check that the below gets indexed as well. although the above should prove that at least one thing is getting indexed.
+        query = "one.anotherKey = 'value2'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+    }
+
 
 
 


[22/36] usergrid git commit: Added first instances of using a cache for access index schema values

Posted by gr...@apache.org.
Added first instances of using a cache for access index schema values


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

Branch: refs/heads/release-2.1.1
Commit: 7e180af9469f2ef2dc31cba8aa67867acd514b42
Parents: bc1fdef
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 16:26:46 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 16:26:46 2016 -0700

----------------------------------------------------------------------
 .../usergrid/corepersistence/CoreModule.java    |   6 ++
 .../corepersistence/CpEntityManager.java        |  22 ++--
 .../corepersistence/CpEntityManagerFactory.java |   4 +
 .../corepersistence/CpManagerCache.java         |  17 ++++
 .../usergrid/corepersistence/ManagerCache.java  |   4 +
 .../corepersistence/index/IndexSchemaCache.java |  45 ++++++++
 .../index/IndexSchemaCacheFactory.java          |  44 ++++++++
 .../index/IndexSchemaCacheFig.java              |  39 +++++++
 .../index/IndexSchemaCacheImpl.java             | 102 +++++++++++++++++++
 .../usergrid/persistence/EntityManager.java     |   1 +
 .../persistence/map/impl/MapManagerImpl.java    |   6 ++
 .../index/impl/EntityToMapConverter.java        |   2 +-
 12 files changed, 285 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/CoreModule.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CoreModule.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CoreModule.java
index 5ac7faf..2d57131 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CoreModule.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CoreModule.java
@@ -16,6 +16,9 @@
 package org.apache.usergrid.corepersistence;
 
 
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFig;
 import org.apache.usergrid.locking.guice.LockModule;
 import org.apache.usergrid.persistence.cache.guice.CacheModule;
 import java.util.concurrent.ThreadPoolExecutor;
@@ -128,6 +131,7 @@ public class CoreModule extends AbstractModule {
 
         bind( ManagerCache.class ).to( CpManagerCache.class );
         bind( ApplicationIdCacheFactory.class );
+        bind( IndexSchemaCacheFactory.class );
 
 
         /**
@@ -177,6 +181,8 @@ public class CoreModule extends AbstractModule {
 
         install( new GuicyFigModule( ApplicationIdCacheFig.class ) );
 
+        install( new GuicyFigModule( IndexSchemaCacheFig.class ) );
+
         install( new GuicyFigModule( EntityManagerFig.class ) );
 
         install( new GuicyFigModule( AsyncEventsSchedulerFig.class ) );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/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 78e52ef..d1f28be 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
@@ -38,8 +38,8 @@ import java.util.TreeMap;
 import java.util.TreeSet;
 import java.util.UUID;
 
-import com.google.common.base.Optional;
 
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
 import org.apache.usergrid.corepersistence.service.CollectionService;
 import org.apache.usergrid.corepersistence.service.ConnectionService;
 import org.apache.usergrid.persistence.index.EntityIndex;
@@ -106,6 +106,7 @@ import org.apache.usergrid.persistence.model.util.UUIDGenerator;
 
 import com.codahale.metrics.Meter;
 import com.codahale.metrics.Timer;
+import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 
 import me.prettyprint.hector.api.Keyspace;
@@ -236,7 +237,10 @@ public class CpEntityManager implements EntityManager {
      * @param metricsFactory
      * @param applicationId
      */
-    public CpEntityManager( final CassandraService cass, final CounterUtils counterUtils, final AsyncEventService indexService, final ManagerCache managerCache,
+    public CpEntityManager( final CassandraService cass,
+                            final CounterUtils counterUtils,
+                            final AsyncEventService indexService,
+                            final ManagerCache managerCache,
                             final MetricsFactory metricsFactory,
                             final EntityManagerFig entityManagerFig,
                             final GraphManagerFactory graphManagerFactory,
@@ -1754,9 +1758,9 @@ public class CpEntityManager implements EntityManager {
         schemaMap.put("lastUpdateBy",owner);
 
 
-        //TODO: please add a check to get the previous reindex time.
         MapManager mm = getMapManagerForTypes();
 
+        //TODO: add a cache around
         String jsonSchemaMap = mm.getString( collectionName );
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
@@ -1778,10 +1782,16 @@ public class CpEntityManager implements EntityManager {
     @Override
     public Object getCollectionSchema( String collectionName ){
         MapManager mm = getMapManagerForTypes();
-        String jsonMap = mm.getString( collectionName );
 
-        Object obj = JsonUtils.parse( jsonMap );
-        return obj;
+
+        java.util.Optional<String> collectionIndexingSchema =  managerCache.getIndexSchema( mm,collectionName );
+
+        if(collectionIndexingSchema.isPresent()){
+            return JsonUtils.parse( collectionIndexingSchema.get() );
+        }
+        else{
+            return null;
+        }
     }
 
         @Override

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/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 0462ac6..4e7f90f 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
@@ -31,6 +31,8 @@ import org.springframework.context.ApplicationContextAware;
 import org.apache.commons.lang.StringUtils;
 
 import org.apache.usergrid.corepersistence.asyncevents.AsyncEventService;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
 import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilder;
 import org.apache.usergrid.corepersistence.index.ReIndexService;
 import org.apache.usergrid.corepersistence.service.CollectionService;
@@ -110,6 +112,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         });
 
     private final ApplicationIdCache applicationIdCache;
+    //private final IndexSchemaCache indexSchemaCache;
 
     private ManagerCache managerCache;
 
@@ -139,6 +142,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         this.connectionService = injector.getInstance( ConnectionService.class );
 
         //this line always needs to be last due to the temporary cicular dependency until spring is removed
+
         this.applicationIdCache = injector.getInstance(ApplicationIdCacheFactory.class).getInstance(
             getManagementEntityManager() );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
index 0b7bb43..dfbab00 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
@@ -16,7 +16,13 @@
 package org.apache.usergrid.corepersistence;
 
 
+import java.util.Optional;
+
+import org.safehaus.guicyfig.Overrides;
+
 import org.apache.usergrid.corepersistence.index.IndexLocationStrategyFactory;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
 import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 import org.apache.usergrid.persistence.collection.EntityCollectionManagerFactory;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -44,6 +50,7 @@ public class CpManagerCache implements ManagerCache {
     private final EntityIndexFactory eif;
     private final GraphManagerFactory gmf;
     private final MapManagerFactory mmf;
+    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
     private final IndexLocationStrategyFactory indexLocationStrategyFactory;
     private final IndexProducer indexProducer;
 
@@ -55,6 +62,7 @@ public class CpManagerCache implements ManagerCache {
                            final EntityIndexFactory eif,
                            final GraphManagerFactory gmf,
                            final MapManagerFactory mmf,
+                           final IndexSchemaCacheFactory indexSchemaCacheFactory,
                            final IndexLocationStrategyFactory indexLocationStrategyFactory,
                            final IndexProducer indexProducer
     ) {
@@ -63,6 +71,7 @@ public class CpManagerCache implements ManagerCache {
         this.eif = eif;
         this.gmf = gmf;
         this.mmf = mmf;
+        this.indexSchemaCacheFactory = indexSchemaCacheFactory;
         this.indexLocationStrategyFactory = indexLocationStrategyFactory;
         this.indexProducer = indexProducer;
     }
@@ -94,6 +103,14 @@ public class CpManagerCache implements ManagerCache {
         return mmf.createMapManager( mapScope );
     }
 
+    //could be called an index schema manager.
+
+    @Override
+    public Optional<String> getIndexSchema( MapManager mapManager, String collectionName ) {
+        return indexSchemaCacheFactory.getInstance( mapManager ).getCollectionSchema( collectionName );
+    }
+
+
     @Override
     public IndexProducer getIndexProducer() {
         return indexProducer;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
index 1dee80a..e0a8257 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
@@ -20,6 +20,8 @@
 package org.apache.usergrid.corepersistence;
 
 
+import java.util.Optional;
+
 import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.graph.GraphManager;
@@ -66,6 +68,8 @@ public interface ManagerCache {
      */
     MapManager getMapManager(MapScope mapScope);
 
+    Optional<String> getIndexSchema( MapManager mapManager, String collectionName );
+
     /**
      * gets index producer
      * @return

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
new file mode 100644
index 0000000..5a9e95d
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
@@ -0,0 +1,45 @@
+/*
+ * 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.corepersistence.index;
+
+
+import java.util.Map;
+import java.util.Optional;
+
+
+public interface IndexSchemaCache {
+
+    /**
+     * Get the collection schema from the cache.
+     * @param collectionName
+     * @return
+     */
+    public Optional<String> getCollectionSchema(String collectionName);
+
+    /**
+     * Evict the collection schema from the cache.
+     * @param collectionName
+     */
+    public void evictCollectionSchema(String collectionName);
+
+    /**
+     * Evict everything from the cache.
+     */
+    public void evictCache();
+
+
+}

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFactory.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFactory.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFactory.java
new file mode 100644
index 0000000..6f72103
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFactory.java
@@ -0,0 +1,44 @@
+/*
+ * 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.corepersistence.index;
+
+
+import org.apache.usergrid.persistence.map.MapManager;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+
+
+/**
+ * This can only be implemented after we have the impl for the application cache.
+ */
+@Singleton
+public class IndexSchemaCacheFactory {
+    private final IndexSchemaCacheFig fig;
+
+    @Inject
+    public IndexSchemaCacheFactory(IndexSchemaCacheFig fig){
+        this.fig = fig;
+    }
+
+    public IndexSchemaCache getInstance(MapManager mapManager ){
+        return new IndexSchemaCacheImpl( mapManager,fig );
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFig.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFig.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFig.java
new file mode 100644
index 0000000..0953abd
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheFig.java
@@ -0,0 +1,39 @@
+package org.apache.usergrid.corepersistence.index;/*
+ * 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.
+ */
+
+
+import org.safehaus.guicyfig.Default;
+import org.safehaus.guicyfig.FigSingleton;
+import org.safehaus.guicyfig.GuicyFig;
+import org.safehaus.guicyfig.Key;
+
+
+/**
+ * Index schema configuration.
+ */
+@FigSingleton
+public interface IndexSchemaCacheFig extends GuicyFig {
+
+    @Key( "usergrid.index_schema_cache_size" )
+    @Default( "5000" )
+    int getCacheSize();
+
+    @Key( "usergrid.index_schema_cache_timeout_ms" )
+    @Default( "60000" )
+    int getCacheTimeout();
+
+}

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
new file mode 100644
index 0000000..d818ce0
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -0,0 +1,102 @@
+/*
+ * 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.corepersistence.index;
+
+
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.usergrid.corepersistence.ManagerCache;
+import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.utils.JsonUtils;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+
+
+/**
+ * Cache the calls to update and get the map manager so we don't overload cassandra when we update
+ * after each call?
+ */
+public class IndexSchemaCacheImpl implements IndexSchemaCache {
+    private static final Logger logger = LoggerFactory.getLogger(IndexSchemaCacheImpl.class );
+
+    private final LoadingCache<String,Optional<String>> indexSchemaCache;
+    private final MapManager mapManager;
+
+
+    public IndexSchemaCacheImpl(MapManager mapManager,IndexSchemaCacheFig indexSchemaCacheFig){
+        this.mapManager = mapManager;
+        indexSchemaCache = CacheBuilder.newBuilder()
+            .maximumSize( indexSchemaCacheFig.getCacheSize() )
+            //.expireAfterWrite( indexSchemaCacheFig.getCacheTimeout(), TimeUnit.MILLISECONDS ) <-- I don't think we want this to expire that quickly.
+            .build( new CacheLoader<String, Optional<String>>() {
+                @Override
+                public Optional<String> load( final String collectionName ) throws Exception {
+                    return Optional.ofNullable( retrieveCollectionSchema( collectionName ) );
+                }
+            } );
+    }
+
+    private String retrieveCollectionSchema( final String collectionName ){
+        return mapManager.getString( collectionName );
+    }
+
+
+    @Override
+    public Optional<String> getCollectionSchema( final String collectionName ) {
+        try {
+            Optional<String> optionalCollectionSchema = indexSchemaCache.get( collectionName );
+            if(!optionalCollectionSchema.isPresent()){
+                indexSchemaCache.invalidate( collectionName );
+                return Optional.empty();
+            }
+            return optionalCollectionSchema;
+        }catch(Exception e){
+            if(logger.isDebugEnabled()){
+                logger.debug( "Returning for collection name: {} "
+                    + "resulted in the following failure: {}",collectionName,e );
+            }
+        }
+        return null;
+    }
+
+
+    @Override
+    public void evictCollectionSchema( final String collectionName ) {
+        indexSchemaCache.invalidate( collectionName );
+        if(logger.isDebugEnabled() ){
+            logger.debug( "Invalidated key {}",collectionName );
+        }
+
+    }
+
+
+    @Override
+    public void evictCache() {
+        indexSchemaCache.invalidateAll();
+        if(logger.isDebugEnabled()){
+            logger.debug( "Invalidated all keys" );
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/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 13fb098..f5b398a 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
@@ -525,6 +525,7 @@ public interface EntityManager {
     public Set<String> getRolePermissions( String roleName ) throws Exception;
 
     public void deleteRole( String roleName ) throws Exception;
+
     public void deleteRole( String roleName, final Optional<EntityRef> roleRef ) throws Exception;
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/impl/MapManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/impl/MapManagerImpl.java b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/impl/MapManagerImpl.java
index 501ade7..965f5f9 100644
--- a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/impl/MapManagerImpl.java
+++ b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/impl/MapManagerImpl.java
@@ -25,6 +25,9 @@ import java.util.UUID;
 import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapScope;
 
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
 import com.google.inject.Inject;
 import com.google.inject.assistedinject.Assisted;
 ;
@@ -38,6 +41,9 @@ public class MapManagerImpl implements MapManager {
     private final MapScope scope;
     private final MapSerialization mapSerialization;
 
+    //Maybe this should go in front of the mapSerialization stuff because thats where we actually make the calls
+    //to cassandra. Then the parsing could be done through an interface.
+
 
     @Inject
     public MapManagerImpl( @Assisted final MapScope scope, final MapSerialization mapSerialization) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/7e180af9/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 885f66e..e9a2075 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -17,7 +17,6 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -199,6 +198,7 @@ public class EntityToMapConverter {
         }
 
         if ( toRemoveFlag ) {
+            //Removes the value if it doesn't match anything
             collectionIterator.remove();
         }
     }


[06/36] usergrid git commit: no message

Posted by gr...@apache.org.
no message


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

Branch: refs/heads/release-2.1.1
Commit: a2ec1dfaf8ea76e7e660f7103ebfabeded57cff0
Parents: 3c98c2d
Author: George Reyes <gr...@apache.org>
Authored: Mon Mar 14 12:28:35 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:13:21 2016 -0700

----------------------------------------------------------------------
 .../rest/applications/CollectionResource.java     | 18 +-----------------
 .../apache/usergrid/services/ServiceManager.java  |  3 +--
 2 files changed, 2 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/a2ec1dfa/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index 856bce0..b7f5f93 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -113,7 +113,7 @@ public class CollectionResource extends ServiceResource {
     @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
     @RequireApplicationAccess
     @JSONP
-    public ApiResponse executeGetOnIndex( @Context UriInfo ui, String body,
+    public ApiResponse executeGetOnIndex( @Context UriInfo ui,
                                           @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
@@ -121,29 +121,13 @@ public class CollectionResource extends ServiceResource {
             logger.trace( "CollectionResource.executeGetOnIndex" );
         }
 
-        Object json;
-        if ( StringUtils.isEmpty( body ) ) {
-            json = null;
-        } else {
-            json = readJsonToObject( body );
-        }
-
         ApiResponse response = createApiResponse();
-
-
-
         response.setAction( "get" );
         response.setApplication( services.getApplication() );
         response.setParams( ui.getQueryParameters() );
 
         executeServiceGetRequestForSchema( ui,response,ServiceAction.GET,null );
 
-        ///ServicePayload payload = getPayload( json );
-
-        ///emf.getEntityManager( getApplicationId() ).get
-
-        //executeServiceRequest( ui, response, ServiceAction.GET, payload );
-
         return response;
     }
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/a2ec1dfa/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java b/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
index 0507818..9089ab7 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
@@ -290,12 +290,11 @@ public class ServiceManager {
             if ( ( cls != null ) && !Modifier.isAbstract( cls.getModifiers() ) ) {
                 return cls;
             }
-        }
+        } //TODO:Find a different way to express this exception. The real exception is returned above. This just needs to be handled some way.
         catch ( ClassNotFoundException e1 ) {
             if(logger.isTraceEnabled()){
                 logger.trace("Could not find class", e1);
             }
-
         }
         return null;
     }


[17/36] usergrid git commit: Working lower level selective indexing. Working field updates when we do reindexing and stuff. Added test proving that it works.

Posted by gr...@apache.org.
Working lower level selective indexing.
Working field updates when we do reindexing and stuff.
Added test proving that it works.


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

Branch: refs/heads/release-2.1.1
Commit: b5d81ac0334fc5aeb204f137bfcbd500c7c1086c
Parents: 82ff53b
Author: George Reyes <gr...@apache.org>
Authored: Tue Mar 29 14:11:56 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Tue Mar 29 14:11:56 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  18 ++-
 .../corepersistence/index/IndexServiceImpl.java |  52 ++------
 .../index/ReIndexServiceImpl.java               |  26 +++-
 .../persistence/index/EntityIndexBatch.java     |  13 +-
 .../index/impl/EntityToMapConverter.java        | 133 ++++++++++++++++++-
 .../index/impl/EsEntityIndexBatchImpl.java      |  27 ++--
 .../persistence/index/impl/IndexOperation.java  |  20 +--
 .../persistence/index/impl/EntityIndexTest.java |   4 +-
 .../collection/CollectionsResourceIT.java       |  25 +++-
 .../test/resource/endpoints/NamedResource.java  |  22 +++
 10 files changed, 242 insertions(+), 98 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/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 bb3abcb..2c97bc6 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
@@ -1737,7 +1737,6 @@ public class CpEntityManager implements EntityManager {
     @Override
     public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties ){
 
-
         //haven't decided which one I should base off of which, maybe from epoch to utc
 
         //TODO: change timeservice as below then use timeservice.
@@ -1753,10 +1752,23 @@ public class CpEntityManager implements EntityManager {
         //this needs the method that can extract the user from the token no matter the token.
         //Possible values are app credentials, org credentials, or the user email(Admin tokens).
         schemaMap.put("lastUpdateBy",owner);
-        schemaMap.put("lastReindexed",0);
-        schemaMap.putAll( properties );
 
+
+        //TODO: please add a check to get the previous reindex time.
         MapManager mm = getMapManagerForTypes();
+
+        String jsonSchemaMap = mm.getString( collectionName );
+
+        //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
+        if ( jsonSchemaMap != null ) {
+            Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+            schemaMap.put( "lastReindexed", jsonMapData.get( "lastReindexed" ) );
+        }
+        else {
+            schemaMap.put( "lastReindexed", 0 );
+        }
+        schemaMap.putAll( properties );
+
         mm.putString( collectionName,JsonUtils.mapToJsonString( schemaMap ) );
 
         return schemaMap;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 5f50a32..c3d5361 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
@@ -134,14 +135,9 @@ public class IndexServiceImpl implements IndexService {
                         logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
                     }
 
-                    final Map map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+                    final Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
 
-                    if(map!=null){
-                        batch.index( indexEdge, entity ,map);
-                    }
-                    else{
-                        batch.index( indexEdge,entity );
-                    }
+                    batch.index( indexEdge, entity ,fieldsToIndex);
                 } )
                     //return the future from the batch execution
                 .map( batch -> batch.build() ) );
@@ -172,14 +168,9 @@ public class IndexServiceImpl implements IndexService {
                 logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
             }
 
-            Map map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+            Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
 
-            if(map!=null){
-                batch.index( indexEdge, entity ,map);
-            }
-            else{
-                batch.index( indexEdge,entity );
-            }
+            batch.index( indexEdge, entity ,fieldsToIndex);
 
 
             return batch.build();
@@ -202,9 +193,11 @@ public class IndexServiceImpl implements IndexService {
      * @return This returns a filtered map that contains the flatted properties of the entity. If there isn't a schema
      * associated with the collection then return null ( and index the entity in its entirety )
      */
-    private Map getFilteredStringObjectMap( final ApplicationScope applicationScope,
+    private Optional<Set<String>> getFilteredStringObjectMap( final ApplicationScope applicationScope,
                                             final Entity entity, final IndexEdge indexEdge ) {
 
+
+        //TODO: THIS IS THE FIRST THING TO BE LOOKED AT TOMORROW.
         //look into this.
         IndexOperation indexOperation = new IndexOperation();
 
@@ -233,35 +226,10 @@ public class IndexServiceImpl implements IndexService {
             defaultProperties.addAll( fieldsToKeep );
         }
         else {
-            return null;
-        }
-
-        //Returns the flattened map of the entity.
-        //TODO: maybe instead pass the fields to keep to the flattening.
-        Map map = indexOperation.convertedEntityToBeIndexed( applicationScope, indexEdge, entity );
-
-        HashSet mapFields = ( HashSet ) map.get( "fields" );
-        Iterator collectionIterator = mapFields.iterator();
-
-        //Loop through all of the fields of the flatted entity and check to see if they should be filtered out.
-        while ( collectionIterator.hasNext() ) {
-            EntityField testedField = ( EntityField ) collectionIterator.next();
-            String fieldName = ( String ) ( testedField ).get( "name" );
-
-            //Checks to see if the fieldname is a default property. If it is then keep it, otherwise send it to
-            //be verified the aptly named method
-
-            //one.two.three
-            //one.two.four
-            //one.two3.five
-            //one.two
-            //fields { one.two }
-            if ( !defaultProperties.contains( fieldName ) ) {
-                iterateThroughMapForFieldsToBeIndexed( fieldsToKeep, collectionIterator, fieldName );
-            }
+            return Optional.empty();
         }
 
-        return map;
+        return Optional.of(defaultProperties);
     }
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 558a18c..42067f5 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -20,7 +20,9 @@
 package org.apache.usergrid.corepersistence.index;
 
 
+import java.time.Instant;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
 
@@ -42,7 +44,10 @@ import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapManagerFactory;
 import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.map.impl.MapScopeImpl;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
 import org.apache.usergrid.persistence.model.util.UUIDGenerator;
+import org.apache.usergrid.utils.InflectionUtils;
+import org.apache.usergrid.utils.JsonUtils;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.google.common.base.Optional;
@@ -76,6 +81,7 @@ public class ReIndexServiceImpl implements ReIndexService {
     private final AllEntityIdsObservable allEntityIdsObservable;
     private final IndexProcessorFig indexProcessorFig;
     private final MapManager mapManager;
+    private final MapManagerFactory mapManagerFactory;
     private final AsyncEventService indexService;
     private final EntityIndexFactory entityIndexFactory;
 
@@ -94,7 +100,7 @@ public class ReIndexServiceImpl implements ReIndexService {
         this.allApplicationsObservable = allApplicationsObservable;
         this.indexProcessorFig = indexProcessorFig;
         this.indexService = indexService;
-
+        this.mapManagerFactory = mapManagerFactory;
         this.mapManager = mapManagerFactory.createMapManager( RESUME_MAP_SCOPE );
     }
 
@@ -133,12 +139,30 @@ public class ReIndexServiceImpl implements ReIndexService {
             .buffer( indexProcessorFig.getReindexBufferSize());
 
         if(delayTimer.isPresent()){
+
+            if(reIndexRequestBuilder.getCollectionName().isPresent()) {
+                String collectionName =  InflectionUtils.pluralize( CpNamingUtils.getNameFromEdgeType(reIndexRequestBuilder.getCollectionName().get() ));
+                MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
+                String jsonSchemaMap = collectionMapStorage.getString( collectionName );
+
+
+                //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
+                if ( jsonSchemaMap != null ) {
+
+                    Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+
+                    jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
+                    collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
+                }
+
+            }
             if(timeUnitOptional.isPresent()){
                 runningReIndex = runningReIndex.delay( delayTimer.get(),timeUnitOptional.get() );
             }
             else{
                 runningReIndex = runningReIndex.delay( delayTimer.get(), TimeUnit.MILLISECONDS );
             }
+
         }
 
         runningReIndex = runningReIndex.doOnNext(edges -> {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
index e3a40f6..2e5ece6 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
@@ -20,6 +20,8 @@ package org.apache.usergrid.persistence.index;/*
 
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.index.impl.IndexOperationMessage;
@@ -30,13 +32,7 @@ import rx.Observable;
 
 public interface EntityIndexBatch {
 
-    /**
-     * Create index for Entity
-     *
-     * @param indexEdge  The edge to index the document into
-     * @param entity     Entity to be indexed.
-     */
-    EntityIndexBatch index( final IndexEdge indexEdge, final Entity entity );
+    EntityIndexBatch index( IndexEdge indexEdge, Entity entity );
 
     /**
      * Remove index of entity
@@ -54,7 +50,8 @@ public interface EntityIndexBatch {
      */
     EntityIndexBatch deindex( final SearchEdge searchEdge, final CandidateResult result );
 
-    EntityIndexBatch index( IndexEdge indexEdge, Entity entity, Map flattenedEntityMap );
+
+    EntityIndexBatch index( IndexEdge indexEdge, Entity entity, Optional<Set<String>> fieldsToIndex );
 
     /**
      * Remove index of entity.

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index b43f4bb..5a728a3 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -17,8 +17,12 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -48,6 +52,14 @@ import static org.apache.usergrid.persistence.index.impl.IndexingUtils.nodeId;
  * Convert a CP entity to an elasticsearch document
  */
 public class EntityToMapConverter {
+
+
+    public static Map<String, Object> convert(ApplicationScope applicationScope, final IndexEdge indexEdge,
+                                              final Entity entity) {
+
+        return convert( applicationScope, indexEdge, entity, Optional.empty() );
+    }
+
     /**
      * Set the entity as a map with the context
      *
@@ -55,7 +67,8 @@ public class EntityToMapConverter {
      * @param entity The entity
      * @param indexEdge The edge this entity is indexed on
      */
-    public static Map<String, Object> convert(ApplicationScope applicationScope, final IndexEdge indexEdge, final Entity entity) {
+    public static Map<String, Object> convert(ApplicationScope applicationScope, final IndexEdge indexEdge,
+                                              final Entity entity, Optional<Set<String>> fieldsToIndex) {
 
 
 
@@ -95,14 +108,128 @@ public class EntityToMapConverter {
         //now visit our entity
         final FieldParser parser = new EntityMappingParser();
 
-        final Set<EntityField> fieldsToIndex =   parser.parse( entityMap );
+        //TODO: to the parsing in the parse method below, that way we don't iterate twice and we filter things out as we see them.
+        final Set<EntityField> fieldsToBeFiltered =   parser.parse( entityMap );
 
 
         //add our fields
-        outputEntity.put( ENTITY_FIELDS, fieldsToIndex );
+        outputEntity.put( ENTITY_FIELDS, fieldsToBeFiltered );
+
+        if(fieldsToIndex.isPresent()){
+            Set<String> defaultProperties = fieldsToIndex.get();
+            //copy paste logic here.
+            HashSet mapFields = ( HashSet ) outputEntity.get( "fields" );
+            Iterator collectionIterator = mapFields.iterator();
+
+            //Loop through all of the fields of the flatted entity and check to see if they should be filtered out.
+            while ( collectionIterator.hasNext() ) {
+                EntityField testedField = ( EntityField ) collectionIterator.next();
+                String fieldName = ( String ) ( testedField ).get( "name" );
+
+                //Checks to see if the fieldname is a default property. If it is then keep it, otherwise send it to
+                //be verified the aptly named method
+
+                //one.two.three
+                //one.two.four
+                //one.two3.five
+                //one.two
+                //fields { one.two }
+                if ( !defaultProperties.contains( fieldName ) ) {
+                    iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
+                }
+            }
+        }
+
 
 
         return outputEntity;
     }
 
+    /**
+     * This method is crucial for selective top level indexing. Here we check to see if the flatted properties
+     * are in fact a top level exclusion e.g one.two.three and one.three.two can be allowed for querying by
+     * specifying one in the schema. If they are not a top level exclusion then they are removed from the iterator and
+     * the map.
+     *
+     * @param fieldsToKeep - contains a list of fields that the user defined in their schema.
+     * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field.
+     * @param fieldName - contains the name of the field that we want to keep.
+     */
+    private static void iterateThroughMapForFieldsToBeIndexed( final Set<String> fieldsToKeep,
+                                                               final Iterator collectionIterator,
+                                                               final String fieldName ) {
+        boolean toRemoveFlag = true;
+        String[] flattedStringArray = getStrings( fieldName );
+
+        Iterator fieldIterator = fieldsToKeep.iterator(); //fieldsToKeep.iterator();
+
+        //goes through a loop of all the fields ( excluding default ) that we want to keep.
+        //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to true and remove
+        //the property.
+        while ( fieldIterator.hasNext() ) {
+            String requiredInclusionString = ( String ) fieldIterator.next();
+            String[] flattedRequirementString = getStrings( requiredInclusionString );
+
+
+            //loop each split array value to see if it matches the equivalent value
+            //in the field. e.g in the example one.two.three and one.two.four we need to check that the schema
+            //matches in both one and two above. If instead it says to exclude one.twor then we would still exclude the above
+            //since it is required to be a hard match.
+
+            //The way the below works if we see that the current field isn't as fine grained as the schema rule
+            //( aka the array is shorter than the current index of the schema rule then there is no way the rule could apply
+            // to the index.
+
+            //Then if that check passes we go to check that both parts are equal. If they are ever not equal
+            // e.g one.two.three and one.three.two then it shouldn't be included
+            //TODO: regex.
+            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
+                //if the array contains a string that it is equals to then set the remove flag to true
+                //otherwise remain false.
+
+                //one.three
+                //one.two
+                //one
+                if ( flattedStringArray.length <= index ) {
+                    toRemoveFlag = true;
+                    break;
+                }
+
+                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
+                    toRemoveFlag = false;
+                }
+                else {
+                    toRemoveFlag = true;
+                    break;
+                }
+            }
+            if ( toRemoveFlag == false ) {
+                break;
+            }
+        }
+
+        if ( toRemoveFlag ) {
+            collectionIterator.remove();
+        }
+    }
+
+
+    /**
+     * Splits the string on the flattened period "." seperated values.
+     * @param fieldName
+     * @return
+     */
+    private static String[] getStrings( final String fieldName ) {
+        final String[] flattedStringArray;
+        if ( !fieldName.contains( "." ) ) {
+            //create a single array that is made of a the single value.
+            flattedStringArray = new String[] { fieldName };
+        }
+        else {
+            flattedStringArray = fieldName.split( "\\." );
+        }
+        return flattedStringArray;
+    }
+
 }
+

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
index 5296978..ed00f48 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
@@ -20,12 +20,16 @@ package org.apache.usergrid.persistence.index.impl;
 
 
 import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.index.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.cassandra.auth.IAuthenticator;
+
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.core.util.ValidationUtils;
 import org.apache.usergrid.persistence.index.utils.IndexValidationUtils;
@@ -65,24 +69,11 @@ public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
     @Override
     public EntityIndexBatch index( final IndexEdge indexEdge, final Entity entity ) {
-        IndexValidationUtils.validateIndexEdge(indexEdge);
-        ValidationUtils.verifyEntityWrite(entity);
-        ValidationUtils.verifyVersion( entity.getVersion() );
-
-        final String writeAlias = alias.getWriteAlias();
-
-        if ( logger.isDebugEnabled() ) {
-            logger.debug( "Indexing to alias {} with scope {} on edge {} with entity data {}",
-                    writeAlias, applicationScope, indexEdge, entity.getFieldMap().keySet() );
-        }
-
-        //add app id for indexing
-        container.addIndexRequest(new IndexOperation(writeAlias, applicationScope, indexEdge, entity));
-        return this;
+        return index( indexEdge,entity, Optional.empty() );
     }
 
     @Override
-    public EntityIndexBatch index ( final IndexEdge indexEdge, final Entity entity ,final Map flattenedEntityMap){
+    public EntityIndexBatch index( final IndexEdge indexEdge, final Entity entity, final Optional<Set<String>> fieldsToIndex ) {
         IndexValidationUtils.validateIndexEdge(indexEdge);
         ValidationUtils.verifyEntityWrite(entity);
         ValidationUtils.verifyVersion( entity.getVersion() );
@@ -91,16 +82,14 @@ public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
         if ( logger.isDebugEnabled() ) {
             logger.debug( "Indexing to alias {} with scope {} on edge {} with entity data {}",
-                writeAlias, applicationScope, indexEdge, flattenedEntityMap );
+                    writeAlias, applicationScope, indexEdge, entity.getFieldMap().keySet() );
         }
 
         //add app id for indexing
-        container.addIndexRequest(new IndexOperation(writeAlias, applicationScope,
-            indexEdge,entity.getId(),entity.getVersion(),flattenedEntityMap) );
+        container.addIndexRequest(new IndexOperation(writeAlias, applicationScope, indexEdge, entity,fieldsToIndex));
         return this;
     }
 
-
     @Override
     public EntityIndexBatch deindex( final SearchEdge searchEdge, final Id id, final UUID version ) {
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
index b51d0c7..8f925ed 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
@@ -21,6 +21,8 @@ package org.apache.usergrid.persistence.index.impl;
 
 
 import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -49,21 +51,13 @@ public class IndexOperation implements BatchOperation {
     public Map<String, Object> data;
 
     public IndexOperation( final String writeAlias, final ApplicationScope applicationScope, IndexEdge indexEdge,
-                           Entity entity ) {
-
-
-        this(writeAlias,IndexingUtils.createIndexDocId(applicationScope, entity,indexEdge)
-            ,EntityToMapConverter.convert(applicationScope,indexEdge, entity));
+                           Entity entity, Optional<Set<String>> fieldsToIndex ) {
 
+        this( writeAlias, IndexingUtils.createIndexDocId( applicationScope, entity, indexEdge ),
+            EntityToMapConverter.convert( applicationScope, indexEdge, entity, fieldsToIndex ) );
 
     }
 
-    public IndexOperation( final String writeAlias, final ApplicationScope applicationScope, IndexEdge indexEdge,
-                           Id entityId, UUID version, Map<String,Object> data ) {
-
-        this(writeAlias,IndexingUtils.createIndexDocId(applicationScope, entityId,version,indexEdge)
-            ,data);
-    }
 
     public IndexOperation( final String writeAlias, String documentId, Map<String, Object> data ) {
         this.writeAlias = writeAlias;
@@ -120,8 +114,4 @@ public class IndexOperation implements BatchOperation {
         result = 31 * result + data.hashCode();
         return result;
     }
-
-    public Map convertedEntityToBeIndexed(ApplicationScope applicationScope,IndexEdge indexEdge,Entity entity){
-        return EntityToMapConverter.convert(applicationScope,indexEdge, entity);
-    }
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/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 3978956..27f3afd 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
@@ -365,7 +365,7 @@ public class EntityIndexTest extends BaseIT {
         EntityUtils.setVersion(entity, UUIDGenerator.newTimeUUID() );
         entity.setField(new UUIDField(IndexingUtils.ENTITY_ID_FIELDNAME, UUID.randomUUID() ) );
 
-        indexProducer.put(entityIndex.createBatch().index( searchEdge, entity ).build()).subscribe();
+        indexProducer.put(entityIndex.createBatch().index( searchEdge, entity, null ).build()).subscribe();
         entityIndex.refreshAsync().toBlocking().first();
 
         CandidateResults candidateResults = entityIndex
@@ -412,7 +412,7 @@ public class EntityIndexTest extends BaseIT {
             IndexEdge searchEdge = new IndexEdgeImpl( appId, "mehCars", SearchEdge.NodeType.SOURCE, System.currentTimeMillis()*1000 );
 
             //index the new entity. This is where the loop will be set to create like 100 entities.
-            indexProducer.put(entityIndex.createBatch().index( searchEdge, entity[i]  ).build()).subscribe();
+            indexProducer.put(entityIndex.createBatch().index( searchEdge, entity[i], null  ).build()).subscribe();
 
         }
         entityIndex.refreshAsync().toBlocking().first();

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 109bb6f..7926e49 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -28,6 +28,7 @@ import org.apache.usergrid.rest.test.resource.model.Collection;
 import org.apache.usergrid.rest.test.resource.model.Entity;
 import org.apache.usergrid.rest.test.resource.model.QueryParameters;
 import org.apache.usergrid.rest.test.resource.model.Token;
+import org.apache.usergrid.services.ServiceParameter;
 
 import org.junit.Ignore;
 import org.junit.Test;
@@ -167,7 +168,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
 
         //Reindex and verify that the entity only has field one index.
-        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+        this.app().collection( "testCollection" ).collection( "_reindex" ).post(true,clientSetup.getSuperuserToken(),ApiResponse.class,null,null,false);
        // Thread.sleep( 10000 );
         //refreshIndex();
 
@@ -225,7 +226,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
         //TODO: the below will have to be replaced by the values that I deem correct.
         assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
         assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+        assertEquals( 0,testCollectionSchema.get( "lastReindexed" ) );
 
         //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
         ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
@@ -233,14 +234,28 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
 
         //Reindex and verify that the entity only has field one index.
-        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+        this.app().collection( "testCollection" ).collection( "_reindex" ).post(true,clientSetup.getSuperuserToken(),ApiResponse.class,null,null,false);
+
+
+        indexingArray.add( "one" );
+        indexingArray.add( "two" );
+
+
+        //field "fields" is required.
+        payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
 
         collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
 
+
+
         testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+        assertNotEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
         assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-        assertNotEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+        assertNotEquals( 0,testCollectionSchema.get( "lastReindexed" ) );
 
         schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
         assertEquals( "one",schema.get( 0 ) );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/b5d81ac0/stack/rest/src/test/java/org/apache/usergrid/rest/test/resource/endpoints/NamedResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/test/resource/endpoints/NamedResource.java b/stack/rest/src/test/java/org/apache/usergrid/rest/test/resource/endpoints/NamedResource.java
index 0254d18..a2377d4 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/test/resource/endpoints/NamedResource.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/test/resource/endpoints/NamedResource.java
@@ -272,6 +272,28 @@ public class NamedResource implements UrlResource {
             .post(javax.ws.rs.client.Entity.json(entity), gt);
     }
 
+    // Used for empty posts
+    public <T> T post(boolean useToken, Token tokenToUse , Class<T> type, Map entity,
+                      final QueryParameters queryParameters, boolean useBasicAuthentication) {
+
+        WebTarget resource = getTarget( useToken,tokenToUse );
+        resource = addParametersToResource(resource, queryParameters);
+
+        GenericType<T> gt = new GenericType<>((Class) type);
+
+        if (useBasicAuthentication) {
+            HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
+                                                                         .credentials("superuser", "superpassword").build();
+            return resource.register(feature).request()
+                           .accept(MediaType.APPLICATION_JSON)
+                           .post(javax.ws.rs.client.Entity.json(entity), gt);
+        }
+
+        return resource.request()
+                       .accept(MediaType.APPLICATION_JSON)
+                       .post(javax.ws.rs.client.Entity.json(entity), gt);
+    }
+
     //For edge cases like Organizations and Tokens without any payload
     public <T> T get(Class<T> type) {
         return get(type, null, true);


[14/36] usergrid git commit: Cleaned up the updating test to verify that a collection of 10 will be indexed.

Posted by gr...@apache.org.
Cleaned up the updating test to verify that a collection of 10 will be indexed.


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

Branch: refs/heads/release-2.1.1
Commit: e1d60b4c2111f9eea47bf6824becb1c09cc81d6c
Parents: 975616b
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 23 09:24:12 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:15:01 2016 -0700

----------------------------------------------------------------------
 .../collection/CollectionsResourceIT.java       | 56 ++++++++++++--------
 1 file changed, 34 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/e1d60b4c/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 11a1878..5900dd5 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -128,17 +128,13 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
         //Create test collection with test entity that is full text indexed.
         Entity testEntity = new Entity();
-        testEntity.put( "one", "value1" );
-        //this field shouldn't persist after reindexing.
-        testEntity.put( "two","valuetwo1" );
 
-        this.app().collection( "testCollection" ).post( testEntity );
-
-        testEntity.put( "one", "value2" );
-        //this field shouldn't persist after reindexing.
-        testEntity.put( "two","valuetwo2" );
 
-        this.app().collection( "testCollection" ).post( testEntity );
+        for(int i = 0; i < 10; i++){
+            testEntity.put( "one","value"+i );
+            testEntity.put( "two","valuetwo"+i );
+            this.app().collection( "testCollection" ).post( testEntity );
+        }
 
 
         //Creating schema.
@@ -155,25 +151,41 @@ public class CollectionsResourceIT extends AbstractRestIT {
         Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
+        //TODO: write a test to verify the data below.
+
+        //        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+        //
+        //        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+        //        //TODO: the below will have to be replaced by the values that I deem correct.
+        //        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+        //        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+        //        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+        //
+        //        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
+        //        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+        //        assertEquals( "one",schema.get( 0 ) );
+
+
         //Reindex and verify that the entity only has field one index.
         this.app().collection( "testCollection" ).collection( "_reindex" ).post();
-        Thread.sleep( 1000 );
+        Thread.sleep( 10000 );
         refreshIndex();
 
-        String query = "one ='value1'";
-        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+        for(int i = 0; i < 10; i++) {
+            String query = "one ='value"+ i + "'";
+            QueryParameters queryParameters = new QueryParameters().setQuery( query );
 
-        //having a name breaks it. Need to get rid of the stack trace and also
-        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
-        Entity reindexedEntity = tempEntity.getResponse().getEntity();
-        assertEquals( "value1",reindexedEntity.get( "one" ) );
-        tempEntity=null;
+            //having a name breaks it. Need to get rid of the stack trace and also
+            Collection tempEntity = this.app().collection( "testCollection" ).get( queryParameters, true );
+            Entity reindexedEntity = tempEntity.getResponse().getEntity();
+            assertEquals( "value"+i, reindexedEntity.get( "one" ) );
 
-        //Verify if you can query on an entity that was not indexed and that no entities are returned.
-        query = "two = 'valuetwo1'";
-        queryParameters = new QueryParameters().setQuery(query);
-        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
-        assertEquals(0,tempEntity.getResponse().getEntities().size());
+            //Verify if you can query on an entity that was not indexed and that no entities are returned.
+            query = "two = 'valuetwo1"+ i + "'";
+            queryParameters = new QueryParameters().setQuery( query );
+            tempEntity = this.app().collection( "testCollection" ).get( queryParameters, true );
+            assertEquals( 0, tempEntity.getResponse().getEntities().size() );
+        }
     }
 
     /**


[24/36] usergrid git commit: Merge branch 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid into selectiveIndexingCherryPicked

Posted by gr...@apache.org.
Merge branch 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid into selectiveIndexingCherryPicked

# By Michael Russo
# Via Michael Russo
* 'release-2.1.1' of https://git-wip-us.apache.org/repos/asf/usergrid:
  Add concurrency to re-index and fix de-serialization problems with Shiro cache, plus comments.
  Fix variable using within Observable path.
  Change scoped cache logging to debug.
  Fix StaleIndexCleanup test to match the current design for removing stale,  un-updated entities.
  Clean up older versions of entities from the index after an entity update.
  Fix spelling of bootstrap.
  Organize the /system/database/setup and /system/database/bootstrap flows.
  USERGRID-1192 - default to use TRANSPORT client for Elasticsearch SDK.
  Set connect timeout in Astyanax driver.
  Add connect timeout to Asytanax driver (set same as socket timeout for now).
  Add caching around getOrganizationConfigForApplication.
  Ignore new test that's not completely accurate yet.
  Fix issue with cursor paging when using the smart shard iterator.
  Fix graph cursor paging with new shard iterator.
  Fix legacy column parser for edge shards.

Conflicts:
	stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java


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

Branch: refs/heads/release-2.1.1
Commit: 0aa241d463c57fbae868e8abb0bf48ebc7aeb1cb
Parents: 12a3be9 f5daca5
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 17:07:59 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 17:07:59 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |   7 +-
 .../corepersistence/CpEntityManagerFactory.java |  34 ++--
 .../usergrid/corepersistence/CpSetup.java       | 100 ++++------
 .../asyncevents/AsyncEventService.java          |   7 +
 .../asyncevents/AsyncEventServiceImpl.java      |  33 +++-
 .../asyncevents/EventBuilder.java               |  12 +-
 .../asyncevents/EventBuilderImpl.java           |  36 +++-
 .../asyncevents/model/AsyncEvent.java           |   5 +-
 .../model/DeIndexOldVersionsEvent.java          |  50 +++++
 .../asyncevents/model/EdgeDeleteEvent.java      |   4 +-
 .../model/ElasticsearchIndexEvent.java          |   2 +-
 .../asyncevents/model/EntityDeleteEvent.java    |   3 +
 .../model/InitializeApplicationIndexEvent.java  |   2 +-
 .../index/IndexProcessorFig.java                |  11 +-
 .../index/ReIndexServiceImpl.java               |  42 ++---
 .../read/traverse/AbstractReadGraphFilter.java  |  18 +-
 .../persistence/EntityManagerFactory.java       |   2 +-
 .../persistence/cassandra/CassandraService.java |   2 -
 .../usergrid/persistence/cassandra/Setup.java   |  28 +--
 .../corepersistence/StaleIndexCleanupTest.java  | 185 +------------------
 .../usergrid/persistence/CoreSchemaManager.java |  14 +-
 .../impl/ScopedCacheSerializationImpl.java      |   9 +-
 .../core/astyanax/CassandraClusterImpl.java     |   4 +-
 .../astyanax/MultiRowShardColumnIterator.java   |  36 +++-
 .../persistence/core/shard/SmartShard.java      |  11 +-
 .../usergrid/persistence/graph/GraphFig.java    |   8 +
 .../graph/impl/GraphManagerImpl.java            |   2 +-
 .../impl/shard/impl/EdgeSearcher.java           |  33 +++-
 .../shard/impl/EdgeShardSerializationImpl.java  |  13 +-
 .../impl/ShardedEdgeSerializationImpl.java      |  42 ++++-
 .../impl/shard/impl/ShardsColumnIterator.java   |  31 +++-
 .../shard/impl/serialize/ShardSerializer.java   |  33 +---
 .../usergrid/persistence/index/IndexFig.java    |   2 +-
 .../usergrid/rest/system/DatabaseResource.java  |   4 +-
 .../collection/paging/PagingResourceIT.java     |  70 ++++++-
 .../resources/usergrid-custom-test.properties   |   4 +
 .../cassandra/ManagementServiceImpl.java        |  67 +++++--
 .../shiro/credentials/AdminUserAccessToken.java |   3 +
 .../ApplicationClientCredentials.java           |   5 +
 .../shiro/principals/AdminUserPrincipal.java    |   3 +
 .../principals/ApplicationGuestPrincipal.java   |   4 +-
 .../shiro/principals/ApplicationPrincipal.java  |   4 +-
 .../principals/ApplicationUserPrincipal.java    |   3 +
 .../shiro/principals/OrganizationPrincipal.java |   4 +-
 .../usergrid/cassandra/SchemaManager.java       |   3 -
 .../usergrid/cassandra/FakeSchemaManager.java   |   8 +-
 46 files changed, 559 insertions(+), 444 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/0aa241d4/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0aa241d4/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManagerFactory.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0aa241d4/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0aa241d4/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --cc stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 22ec9d9,b5f7d77..1b68712
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@@ -81,9 -75,8 +81,10 @@@ public class ReIndexServiceImpl impleme
      private final AllEntityIdsObservable allEntityIdsObservable;
      private final IndexProcessorFig indexProcessorFig;
      private final MapManager mapManager;
 +    private final MapManagerFactory mapManagerFactory;
      private final AsyncEventService indexService;
      private final EntityIndexFactory entityIndexFactory;
++    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
  
  
      @Inject
@@@ -93,6 -86,6 +94,7 @@@
                                 final MapManagerFactory mapManagerFactory,
                                 final AllApplicationsObservable allApplicationsObservable,
                                 final IndexProcessorFig indexProcessorFig,
++                               final IndexSchemaCacheFactory indexSchemaCacheFactory,
                                 final AsyncEventService indexService ) {
          this.entityIndexFactory = entityIndexFactory;
          this.indexLocationStrategyFactory = indexLocationStrategyFactory;
@@@ -100,7 -93,7 +102,8 @@@
          this.allApplicationsObservable = allApplicationsObservable;
          this.indexProcessorFig = indexProcessorFig;
          this.indexService = indexService;
 -
++        this.indexSchemaCacheFactory = indexSchemaCacheFactory;
 +        this.mapManagerFactory = mapManagerFactory;
          this.mapManager = mapManagerFactory.createMapManager( RESUME_MAP_SCOPE );
      }
  
@@@ -134,47 -122,19 +137,44 @@@
  
          // create an observable that loads a batch to be indexed
  
-         Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
-             reIndexRequestBuilder.getCollectionName(), cursorSeek.getSeekValue() )
-             .buffer( indexProcessorFig.getReindexBufferSize());
- 
-         //Check to see if we have a selective indexing schema, if we do then update its reindexing time, otherwise
-         //don't update or create anything.
 -        final Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
 +        if(reIndexRequestBuilder.getCollectionName().isPresent()) {
 +            String collectionName =  InflectionUtils.pluralize( CpNamingUtils.getNameFromEdgeType(reIndexRequestBuilder.getCollectionName().get() ));
 +            MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
-             String jsonSchemaMap = collectionMapStorage.getString( collectionName );
++            IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( collectionMapStorage );
++
++            java.util.Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 +
 +
++            String jsonSchemaMap =  null;
++
++            if(collectionIndexingSchema.isPresent()){
++                jsonSchemaMap = collectionIndexingSchema.get();
++            }
++
 +            //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
 +            if ( jsonSchemaMap != null ) {
 +
 +                Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
 +
 +                jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
 +                collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
 +            }
 +
 +        }
 +
-         if(delayTimer.isPresent()){
- 
-             if(timeUnitOptional.isPresent()){
-                 runningReIndex = runningReIndex.delay( delayTimer.get(),timeUnitOptional.get() );
-             }
-             else{
-                 runningReIndex = runningReIndex.delay( delayTimer.get(), TimeUnit.MILLISECONDS );
-             }
- 
-         }
++        Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
+             reIndexRequestBuilder.getCollectionName(), cursorSeek.getSeekValue() )
 +
-         runningReIndex = runningReIndex.doOnNext(edges -> {
-                 logger.info("Sending batch of {} to be indexed.", edges.size());
-                 indexService.indexBatch(edges, modifiedSince);
+             .buffer( indexProcessorFig.getReindexBufferSize())
+             .flatMap( edgeScopes -> Observable.just(edgeScopes)
+                 .doOnNext(edges -> {
  
-         });
+                     logger.info("Sending batch of {} to be indexed.", edges.size());
+                     indexService.indexBatch(edges, modifiedSince);
+                 })
+                 .subscribeOn( Schedulers.io() ), indexProcessorFig.getReindexConcurrencyFactor());
  
  
 -
          //start our sampler and state persistence
          //take a sample every sample interval to allow us to resume state with minimal loss
          //create our flushing collector and flush the edge scopes to it


[16/36] usergrid git commit: Comments with changes to make to selective indexing. Changes to reindexing to add a delay given the reindexing call.

Posted by gr...@apache.org.
Comments with changes to make to selective indexing.
Changes to reindexing to add a delay given the reindexing call.


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

Branch: refs/heads/release-2.1.1
Commit: 82ff53b145d84a7fbf198f0eb63153af0d2b6633
Parents: 1ba12b8
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 25 09:06:10 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Fri Mar 25 09:06:10 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  4 +-
 .../corepersistence/CpManagerCache.java         |  1 +
 .../corepersistence/index/IndexServiceImpl.java | 23 +++++-
 .../index/ReIndexRequestBuilder.java            |  7 ++
 .../index/ReIndexRequestBuilderImpl.java        | 32 ++++++++
 .../index/ReIndexServiceImpl.java               | 23 ++++--
 .../usergrid/persistence/map/MapManager.java    |  2 +
 .../rest/applications/CollectionResource.java   | 14 +++-
 .../collection/CollectionsResourceIT.java       | 77 +++++++++++++++++++-
 9 files changed, 169 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/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 1fbacbe..bb3abcb 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
@@ -1739,9 +1739,11 @@ public class CpEntityManager implements EntityManager {
 
 
         //haven't decided which one I should base off of which, maybe from epoch to utc
+
+        //TODO: change timeservice as below then use timeservice.
+        //TODO: only allow a single reindex in elasticsearch at a time. akka.
         Instant timeInstance = Instant.now();
 
-        Date date = Date.from(timeInstance);
         Long epoch = timeInstance.toEpochMilli();
 
         Map<String,Object> schemaMap = new HashMap<>(  );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
index 0408bbd..0b7bb43 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
@@ -37,6 +37,7 @@ import com.google.inject.Inject;
 /**
  * Cache for managing our other managers.  Now just a delegate.  Needs refactored away
  */
+
 public class CpManagerCache implements ManagerCache {
 
     private final EntityCollectionManagerFactory ecmf;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index c0f2e1b..5f50a32 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -121,8 +121,10 @@ public class IndexServiceImpl implements IndexService {
 
         //do our observable for batching
         //try to send a whole batch if we can
+
+        //TODO: extract the below and call a single method.
         final Observable<IndexOperationMessage>  batches =  sourceEdgesToIndex
-            .buffer(250, TimeUnit.MILLISECONDS, indexFig.getIndexBatchSize() )
+            .buffer(250, TimeUnit.MILLISECONDS, indexFig.getIndexBatchSize() ) //TODO: change to delay. maybe. at least to the before buffer.
 
             //map into batches based on our buffer size
             .flatMap( buffer -> Observable.from( buffer )
@@ -202,10 +204,9 @@ public class IndexServiceImpl implements IndexService {
      */
     private Map getFilteredStringObjectMap( final ApplicationScope applicationScope,
                                             final Entity entity, final IndexEdge indexEdge ) {
-        IndexOperation indexOperation = new IndexOperation();
-
 
-        indexEdge.getNodeId().getUuid();
+        //look into this.
+        IndexOperation indexOperation = new IndexOperation();
 
         Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
 
@@ -217,6 +218,7 @@ public class IndexServiceImpl implements IndexService {
         Set<String> defaultProperties;
         ArrayList fieldsToKeep;
 
+        //TODO: extract collection name using other classes than the split.
         String jsonSchemaMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
@@ -226,6 +228,8 @@ public class IndexServiceImpl implements IndexService {
             Schema schema = Schema.getDefaultSchema();
             defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1] );
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
+            //TODO: add method here to update the relevant fields in the map manager when it was accessed.
+
             defaultProperties.addAll( fieldsToKeep );
         }
         else {
@@ -233,6 +237,7 @@ public class IndexServiceImpl implements IndexService {
         }
 
         //Returns the flattened map of the entity.
+        //TODO: maybe instead pass the fields to keep to the flattening.
         Map map = indexOperation.convertedEntityToBeIndexed( applicationScope, indexEdge, entity );
 
         HashSet mapFields = ( HashSet ) map.get( "fields" );
@@ -245,6 +250,12 @@ public class IndexServiceImpl implements IndexService {
 
             //Checks to see if the fieldname is a default property. If it is then keep it, otherwise send it to
             //be verified the aptly named method
+
+            //one.two.three
+            //one.two.four
+            //one.two3.five
+            //one.two
+            //fields { one.two }
             if ( !defaultProperties.contains( fieldName ) ) {
                 iterateThroughMapForFieldsToBeIndexed( fieldsToKeep, collectionIterator, fieldName );
             }
@@ -290,10 +301,14 @@ public class IndexServiceImpl implements IndexService {
 
             //Then if that check passes we go to check that both parts are equal. If they are ever not equal
             // e.g one.two.three and one.three.two then it shouldn't be included
+            //TODO: regex.
             for ( int index = 0; index < flattedRequirementString.length; index++ ) {
                 //if the array contains a string that it is equals to then set the remove flag to true
                 //otherwise remain false.
 
+                //one.three
+                //one.two
+                //one
                 if ( flattedStringArray.length <= index ) {
                     toRemoveFlag = true;
                     break;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilder.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilder.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilder.java
index 0863a63..139f832 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilder.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilder.java
@@ -21,6 +21,7 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 
@@ -52,6 +53,8 @@ public interface ReIndexRequestBuilder {
     ReIndexRequestBuilder withCursor(final String cursor);
 
 
+    ReIndexRequestBuilder withDelay( int delayTimer, TimeUnit timeUnit );
+
     /**
      * Set the timestamp to re-index entities updated >= this timestamp
      * @param timestamp
@@ -60,6 +63,10 @@ public interface ReIndexRequestBuilder {
     ReIndexRequestBuilder withStartTimestamp(final Long timestamp);
 
 
+    Optional<Integer> getDelayTimer();
+
+    Optional<TimeUnit> getTimeUnitOptional();
+
     /**
      * Get the application scope
      * @return

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilderImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilderImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilderImpl.java
index e93ccf1..d3e7ecf 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilderImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexRequestBuilderImpl.java
@@ -21,6 +21,9 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.cassandra.auth.IAuthenticator;
 
 import org.apache.usergrid.corepersistence.util.CpNamingUtils;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -37,6 +40,8 @@ public class ReIndexRequestBuilderImpl implements ReIndexRequestBuilder {
     private Optional<String> withCollectionName = Optional.absent();
     private Optional<String> cursor = Optional.absent();
     private Optional<Long> updateTimestamp = Optional.absent();
+    private Optional<Integer> delayTimer = Optional.absent();
+    private Optional<TimeUnit> timeUnitOptional = Optional.absent();
 
 
     /***
@@ -81,6 +86,22 @@ public class ReIndexRequestBuilderImpl implements ReIndexRequestBuilder {
 
 
     /**
+     * Determines whether we should tack on a delay for reindexing and for how long if we do. Also
+     * allowed to specify how throttled back it should be.
+     * @param delayTimer
+     * @param timeUnit
+     * @return
+     */
+    @Override
+    public ReIndexRequestBuilder withDelay( final int delayTimer, final TimeUnit timeUnit ){
+        this.delayTimer = Optional.fromNullable( delayTimer );
+        this.timeUnitOptional = Optional.fromNullable( timeUnit );
+
+        return this;
+    }
+
+
+    /**
      * Set start timestamp in epoch time.  Only entities updated since this time will be processed for indexing
      * @param timestamp
      * @return
@@ -93,6 +114,17 @@ public class ReIndexRequestBuilderImpl implements ReIndexRequestBuilder {
 
 
     @Override
+    public Optional<Integer> getDelayTimer() {
+        return delayTimer;
+    }
+
+    @Override
+    public Optional<TimeUnit> getTimeUnitOptional() {
+        return timeUnitOptional;
+    }
+
+
+    @Override
     public Optional<ApplicationScope> getApplicationScope() {
 
         if ( this.withApplicationId.isPresent() ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index fc1c97f..558a18c 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -99,6 +99,7 @@ public class ReIndexServiceImpl implements ReIndexService {
     }
 
 
+    //TODO: optional delay, param.
     @Override
     public ReIndexStatus rebuildIndex( final ReIndexRequestBuilder reIndexRequestBuilder ) {
 
@@ -111,6 +112,10 @@ public class ReIndexServiceImpl implements ReIndexService {
 
         final Optional<ApplicationScope> appId = reIndexRequestBuilder.getApplicationScope();
 
+        final Optional<Integer> delayTimer = reIndexRequestBuilder.getDelayTimer();
+
+        final Optional<TimeUnit> timeUnitOptional = reIndexRequestBuilder.getTimeUnitOptional();
+
         Preconditions.checkArgument( !(cursor.isPresent() && appId.isPresent()),
             "You cannot specify an app id and a cursor.  When resuming with cursor you must omit the appid" );
 
@@ -123,16 +128,24 @@ public class ReIndexServiceImpl implements ReIndexService {
 
         // create an observable that loads a batch to be indexed
 
-        final Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
+        Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
             reIndexRequestBuilder.getCollectionName(), cursorSeek.getSeekValue() )
-            .buffer( indexProcessorFig.getReindexBufferSize())
-            //.delay( 50, TimeUnit.MILLISECONDS )
-            .doOnNext(edges -> {
+            .buffer( indexProcessorFig.getReindexBufferSize());
 
+        if(delayTimer.isPresent()){
+            if(timeUnitOptional.isPresent()){
+                runningReIndex = runningReIndex.delay( delayTimer.get(),timeUnitOptional.get() );
+            }
+            else{
+                runningReIndex = runningReIndex.delay( delayTimer.get(), TimeUnit.MILLISECONDS );
+            }
+        }
+
+        runningReIndex = runningReIndex.doOnNext(edges -> {
                 logger.info("Sending batch of {} to be indexed.", edges.size());
                 indexService.indexBatch(edges, modifiedSince);
 
-            });
+        });
 
 
         //start our sampler and state persistence

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
index 80e2d17..ca8fd9a 100644
--- a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
+++ b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
@@ -27,6 +27,8 @@ import java.util.UUID;
 /**
  * Generator of a map manager instance
  */
+//TODO: This should be a singleton, otherwise cache could be out of sync and would need to invalidated everywher
+    //TODO: make manager cache injectable everywhere.
 public interface MapManager {
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index b674ac4..fb660fa 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -19,6 +19,7 @@ package org.apache.usergrid.rest.applications;
 
 
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
@@ -47,6 +48,7 @@ import org.apache.usergrid.rest.AbstractContextResource;
 import org.apache.usergrid.rest.ApiResponse;
 import org.apache.usergrid.rest.RootResource;
 import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
+import org.apache.usergrid.rest.security.annotations.RequireSystemAccess;
 import org.apache.usergrid.services.AbstractCollectionService;
 import org.apache.usergrid.services.ServiceAction;
 import org.apache.usergrid.services.ServiceParameter;
@@ -91,6 +93,9 @@ public class CollectionResource extends ServiceResource {
         if(logger.isTraceEnabled()){
             logger.trace( "ServiceResource.executePostOnIndexes" );
         }
+        /**
+
+         */
 
         Object json;
         if ( StringUtils.isEmpty( body ) ) {
@@ -135,10 +140,12 @@ public class CollectionResource extends ServiceResource {
         return response;
     }
 
+    //TODO: this can't be controlled and until it can be controlled we should allow muggles to do this. So system access only.
+    //TODO: use scheduler here to get around people sending a reindex call 30 times.
     @POST
     @Path("_reindex")
     @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
-    @RequireApplicationAccess
+    @RequireSystemAccess
     @JSONP
     public ApiResponse executePostForReindexing( @Context UriInfo ui, String body,
                                              @QueryParam("callback") @DefaultValue("callback") String callback )
@@ -146,8 +153,8 @@ public class CollectionResource extends ServiceResource {
 
         final ReIndexRequestBuilder request =
             createRequest().withApplicationId( services.getApplicationId() ).withCollection(
-                String.valueOf( getServiceParameters().get( 0 ) ) );
-//
+                String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 1, TimeUnit.SECONDS );
+
         return executeAndCreateResponse( request, callback );
     }
 
@@ -170,6 +177,7 @@ public class CollectionResource extends ServiceResource {
     }
 
 
+    //TODO: change this to {itemName}/_indexes and that should do what we already have. Then we don't have this overriden method.
     @Override
     @Path("{itemName}")
     public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName )

http://git-wip-us.apache.org/repos/asf/usergrid/blob/82ff53b1/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 5900dd5..109bb6f 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -168,9 +168,84 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
         //Reindex and verify that the entity only has field one index.
         this.app().collection( "testCollection" ).collection( "_reindex" ).post();
-        Thread.sleep( 10000 );
+       // Thread.sleep( 10000 );
+        //refreshIndex();
+
+        for(int i = 0; i < 10; i++) {
+            String query = "one ='value"+ i + "'";
+            QueryParameters queryParameters = new QueryParameters().setQuery( query );
+
+            //having a name breaks it. Need to get rid of the stack trace and also
+            Collection tempEntity = this.app().collection( "testCollection" ).get( queryParameters, true );
+            Entity reindexedEntity = tempEntity.getResponse().getEntity();
+            assertEquals( "value"+i, reindexedEntity.get( "one" ) );
+
+            //Verify if you can query on an entity that was not indexed and that no entities are returned.
+            query = "two = 'valuetwo1"+ i + "'";
+            queryParameters = new QueryParameters().setQuery( query );
+            tempEntity = this.app().collection( "testCollection" ).get( queryParameters, true );
+            assertEquals( 0, tempEntity.getResponse().getEntities().size() );
+        }
+    }
+
+
+    @Test
+    public void postToCollectionSchemaAndVerifyFieldsAreUpdated() throws Exception {
+
+        //Create test collection with test entity that is full text indexed.
+        Entity testEntity = new Entity();
+
+
+        for(int i = 0; i < 10; i++){
+            testEntity.put( "one","value"+i );
+            testEntity.put( "two","valuetwo"+i );
+            this.app().collection( "testCollection" ).post( testEntity );
+        }
+
+
+        //Creating schema.
+        //this could be changed to a hashmap.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "one" );
+
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
+        //TODO: write a test to verify the data below.
+
+        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+
+        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+        //TODO: the below will have to be replaced by the values that I deem correct.
+        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+
+        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
+        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+        assertEquals( "one",schema.get( 0 ) );
+
+
+        //Reindex and verify that the entity only has field one index.
+        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+
+        collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+
+        testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+        assertNotEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+
+        schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+        assertEquals( "one",schema.get( 0 ) );
+
+
         for(int i = 0; i < 10; i++) {
             String query = "one ='value"+ i + "'";
             QueryParameters queryParameters = new QueryParameters().setQuery( query );


[35/36] usergrid git commit: Removed all instance of java.util.Optional from selective indexing.

Posted by gr...@apache.org.
Removed all instance of java.util.Optional from selective indexing.


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

Branch: refs/heads/release-2.1.1
Commit: d751ac1fa9ed4dc5eecc915db10d8ca65f0b8548
Parents: 9f3720e
Author: George Reyes <gr...@apache.org>
Authored: Mon Apr 4 11:08:16 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Mon Apr 4 11:08:16 2016 -0700

----------------------------------------------------------------------
 .../org/apache/usergrid/corepersistence/CpEntityManager.java  | 4 ++--
 .../org/apache/usergrid/corepersistence/ManagerCache.java     | 3 ---
 .../usergrid/corepersistence/index/IndexSchemaCache.java      | 3 ++-
 .../usergrid/corepersistence/index/IndexSchemaCacheImpl.java  | 6 +++---
 .../usergrid/corepersistence/index/IndexServiceImpl.java      | 6 +++---
 .../usergrid/corepersistence/index/ReIndexServiceImpl.java    | 2 +-
 .../apache/usergrid/persistence/index/EntityIndexBatch.java   | 7 +++----
 .../usergrid/persistence/index/impl/EntityToMapConverter.java | 5 +++--
 .../persistence/index/impl/EsEntityIndexBatchImpl.java        | 5 +++--
 .../usergrid/persistence/index/impl/IndexOperation.java       | 4 +---
 10 files changed, 21 insertions(+), 24 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/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 4ee497c..2e2d9d5 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
@@ -1767,7 +1767,7 @@ public class CpEntityManager implements EntityManager {
 
         IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
 
-        java.util.Optional<Map> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
+        Optional<Map> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
 
 
         //If there is an existing schema then take the lastReindexed time and keep it around.Otherwise initialize to 0.
@@ -1815,7 +1815,7 @@ public class CpEntityManager implements EntityManager {
 
         IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm ); //managerCache.getIndexSchema( mm );
 
-        java.util.Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
+        Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
         if(collectionIndexingSchema.isPresent()){
             return collectionIndexingSchema.get();

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
index ebfd5a4..60212df 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
@@ -20,14 +20,11 @@
 package org.apache.usergrid.corepersistence;
 
 
-import java.util.Optional;
 
-import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
 import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.graph.GraphManager;
 import org.apache.usergrid.persistence.index.EntityIndex;
-import org.apache.usergrid.persistence.index.IndexLocationStrategy;
 import org.apache.usergrid.persistence.index.impl.IndexProducer;
 import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapScope;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
index a56ffd6..0ef92e9 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
@@ -18,7 +18,8 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.Map;
-import java.util.Optional;
+
+import com.google.common.base.Optional;
 
 
 public interface IndexSchemaCache {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
index 3df31cc..fd0b676 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -19,7 +19,6 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.Map;
-import java.util.Optional;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -27,6 +26,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.utils.JsonUtils;
 
+import com.google.common.base.Optional;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
@@ -53,7 +53,7 @@ public class IndexSchemaCacheImpl implements IndexSchemaCache {
             .build( new CacheLoader<String, Optional<Map>>() {
                 @Override
                 public Optional<Map> load( final String collectionName ) throws Exception {
-                    return Optional.ofNullable( retrieveCollectionSchema( collectionName ) );
+                    return Optional.fromNullable( retrieveCollectionSchema( collectionName ) );
                 }
             } );
     }
@@ -75,7 +75,7 @@ public class IndexSchemaCacheImpl implements IndexSchemaCache {
             Optional<Map> optionalCollectionSchema = indexSchemaCache.get( collectionName );
             if(!optionalCollectionSchema.isPresent()){
                 indexSchemaCache.invalidate( collectionName );
-                return Optional.empty();
+                return Optional.absent();
             }
             return optionalCollectionSchema;
         }catch(Exception e){

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index c81c4ef..f3f48cc 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -23,7 +23,6 @@ package org.apache.usergrid.corepersistence.index;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Map;
-import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
@@ -61,6 +60,7 @@ import org.apache.usergrid.utils.JsonUtils;
 import org.apache.usergrid.utils.UUIDUtils;
 
 import com.codahale.metrics.Timer;
+import com.google.common.base.Optional;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
 
@@ -223,13 +223,13 @@ public class IndexServiceImpl implements IndexService {
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
 
             if(fieldsToKeep.contains( "*" )){
-                return Optional.empty();
+                return Optional.absent();
             }
 
             defaultProperties.addAll( fieldsToKeep );
         }
         else {
-            return Optional.empty();
+            return Optional.absent();
         }
 
         return Optional.of(defaultProperties);

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 0aa0f60..250e7fc 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -141,7 +141,7 @@ public class ReIndexServiceImpl implements ReIndexService {
             MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
             IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( collectionMapStorage );
 
-            java.util.Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
+            Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
             //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
             if ( collectionIndexingSchema.isPresent() ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
index 274aea5..c551083 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
@@ -18,16 +18,15 @@ package org.apache.usergrid.persistence.index;/*
  */
 
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+
 import java.util.Set;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.index.impl.IndexOperationMessage;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
-import rx.Observable;
+
+import com.google.common.base.Optional;
 
 
 public interface EntityIndexBatch {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 8eb9f48..bc26ae9 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -21,7 +21,6 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
-import java.util.Optional;
 import java.util.Set;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -30,6 +29,8 @@ import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.EntityMap;
 import org.apache.usergrid.persistence.model.entity.Id;
 
+import com.google.common.base.Optional;
+
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.APPLICATION_ID_FIELDNAME;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.EDGE_NAME_FIELDNAME;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.EDGE_NODE_ID_FIELDNAME;
@@ -56,7 +57,7 @@ public class EntityToMapConverter {
     public static Map<String, Object> convert(ApplicationScope applicationScope, final IndexEdge indexEdge,
                                               final Entity entity) {
 
-        return convert( applicationScope, indexEdge, entity, Optional.empty() );
+        return convert( applicationScope, indexEdge, entity, Optional.absent() );
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
index 0375841..1bb97b3 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
@@ -19,7 +19,6 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
-import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 
@@ -39,6 +38,8 @@ import org.apache.usergrid.persistence.index.utils.IndexValidationUtils;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
 
+import com.google.common.base.Optional;
+
 
 public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
@@ -70,7 +71,7 @@ public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
     @Override
     public EntityIndexBatch index( final IndexEdge indexEdge, final Entity entity ) {
-        return index( indexEdge,entity, Optional.empty() );
+        return index( indexEdge,entity, Optional.absent() );
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/usergrid/blob/d751ac1f/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
index 8f925ed..f8560ba 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
@@ -21,20 +21,18 @@ package org.apache.usergrid.persistence.index.impl;
 
 
 import java.util.Map;
-import java.util.Optional;
 import java.util.Set;
-import java.util.UUID;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.index.IndexEdge;
 import org.apache.usergrid.persistence.model.entity.Entity;
-import org.apache.usergrid.persistence.model.entity.Id;
 
 import org.elasticsearch.action.bulk.BulkRequestBuilder;
 import org.elasticsearch.action.index.IndexRequestBuilder;
 import org.elasticsearch.client.Client;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Optional;
 
 
 /**


[11/36] usergrid git commit: Added comments explaining what the selective indexing does and how it is accomplished.

Posted by gr...@apache.org.
Added comments explaining what the selective indexing does and how it is accomplished.


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

Branch: refs/heads/release-2.1.1
Commit: 2562e9702a19236ad713bdc02402e8b1486cb08c
Parents: 859d6bf
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 18 13:39:12 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:44 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 240 +++++++++----------
 1 file changed, 110 insertions(+), 130 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/2562e970/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 74776ac..a753dba 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -21,7 +21,6 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
@@ -37,7 +36,6 @@ import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapManagerFactory;
 import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.model.entity.SimpleId;
-import org.apache.usergrid.persistence.model.field.Field;
 import org.apache.usergrid.utils.JsonUtils;
 import org.apache.usergrid.utils.UUIDUtils;
 import org.slf4j.Logger;
@@ -67,7 +65,6 @@ import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createSearc
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.generateScopeFromSource;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.generateScopeFromTarget;
 import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
-import static org.apache.usergrid.persistence.Schema.getDefaultSchema;
 
 
 /**
@@ -165,7 +162,7 @@ public class IndexServiceImpl implements IndexService {
                 logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
             }
 
-            Map<String, Object> map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+            Map map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
 
             if(map!=null){
                 batch.index( indexEdge, entity ,map);
@@ -180,174 +177,157 @@ public class IndexServiceImpl implements IndexService {
 
         return ObservableTimer.time( batches, addTimer  );
 
-
     }
 
 
-    private Map<String, Object> getFilteredStringObjectMap( final ApplicationScope applicationScope, final Entity entity,
-                                                    final IndexEdge indexEdge ) {IndexOperation indexOperation = new IndexOperation(  );
+    /**
+     * This method takes in an entity and flattens it out then begins the process to filter out
+     * properties that we do not want to index. Once flatted we parse through each property
+     * and verify that we want it to be indexed on. The set of default properties that will always be indexed are as follows.
+     * UUID - TYPE - MODIFIED - CREATED. Depending on the schema this may change. For instance, users will always require
+     * NAME, but the above four will always be taken in.
+     * @param applicationScope
+     * @param entity
+     * @param indexEdge
+     * @return This returns a filtered map that contains the flatted properties of the entity. If there isn't a schema
+     * associated with the collection then return null ( and index the entity in its entirety )
+     */
+    private Map getFilteredStringObjectMap( final ApplicationScope applicationScope,
+                                            final Entity entity, final IndexEdge indexEdge ) {
+        IndexOperation indexOperation = new IndexOperation();
 
 
         indexEdge.getNodeId().getUuid();
 
         Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
 
-        final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
+        //TODO: this needs to be cached
+        final MapScope ms = CpNamingUtils.getEntityTypeMapScope( mapOwner );
 
         MapManager mm = mapManagerFactory.createMapManager( ms );
 
-        //determines is the map manager has a collection schema associated with it.
-        String jsonSchemaMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
+        Set<String> defaultProperties;
+        ArrayList fieldsToKeep;
 
-        Set<String> defaultProperties = null;
-        ArrayList fieldsToKeep = null;
+        String jsonSchemaMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
-        if(jsonSchemaMap != null) {
+        if ( jsonSchemaMap != null ) {
 
             Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
             Schema schema = Schema.getDefaultSchema();
-            defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
-            //TODO: additional logic to
+            defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1] );
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
             defaultProperties.addAll( fieldsToKeep );
         }
-        else
+        else {
             return null;
+        }
 
+        //Returns the flattened map of the entity.
+        Map map = indexOperation.convertedEntityToBeIndexed( applicationScope, indexEdge, entity );
 
-        Map<String, Object> map = indexOperation.convertedEntityToBeIndexed( applicationScope,indexEdge,entity );
         HashSet mapFields = ( HashSet ) map.get( "fields" );
+        Iterator collectionIterator = mapFields.iterator();
 
-        if(defaultProperties!=null) {
-            final Set<String> finalDefaultProperties = defaultProperties;
-            Iterator collectionIterator = mapFields.iterator();
-
-            //TODO:I think there is a bug when we modify it and continue iterating then it fails
-            //Loop that goes through all the fields that the passed in entity contains
-            while ( collectionIterator.hasNext() ) {
-                EntityField testedField = ( EntityField ) collectionIterator.next();
-                String fieldName = ( String ) (testedField).get( "name" );
-
-                //will only enter the loop for properties that aren't default properties so we only need to check
-                //the properties that the user imposed.
-                if ( !finalDefaultProperties.contains( fieldName ) ) {
-                    boolean toRemoveFlag = true;
-                    String[] flattedStringArray = getStrings( fieldName );
-
-                    Iterator fieldIterator = fieldsToKeep.iterator();
-
-                    //goes through a loop of all the fields ( excluding default ) that we want to keep.
-                    //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to false
-                    while(fieldIterator.hasNext()) {
-                        String requiredInclusionString = ( String ) fieldIterator.next();
-                        String[] flattedRequirementString = getStrings( requiredInclusionString );
-
-
-                        //loop each split array value to see if it matches an equivalent value
-                        //in the field.
-                        for ( int index = 0; index < flattedRequirementString.length;index++){
-                            //if the array contains a string that it is equals to then set the remove flag to true
-                            //otherwise remain false.
-
-                            if(flattedStringArray.length <= index){
-                                toRemoveFlag = true;
-                                break;
-                            }
-                            //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
-                            if(flattedRequirementString[index].equals( flattedStringArray[index] )){
-                                toRemoveFlag=false;
-                            }
-                            else{
-                                toRemoveFlag=true;
-                            }
-                        }
-                        if(toRemoveFlag==false){
-                            break;
-                        }
-                    }
+        //Loop through all of the fields of the flatted entity and check to see if they should be filtered out.
+        while ( collectionIterator.hasNext() ) {
+            EntityField testedField = ( EntityField ) collectionIterator.next();
+            String fieldName = ( String ) ( testedField ).get( "name" );
 
-                    if(toRemoveFlag){
-                        collectionIterator.remove();
-                        //mapFields.remove( testedField );
-                    }
-                }
+            //Checks to see if the fieldname is a default property. If it is then keep it, otherwise send it to
+            //be verified the aptly named method
+            if ( !defaultProperties.contains( fieldName ) ) {
+                iterateThroughMapForFieldsToBeIndexed( fieldsToKeep, collectionIterator, fieldName );
             }
         }
+
         return map;
     }
-    
 
+
+    /**
+     * This method is crucial for selective top level indexing. Here we check to see if the flatted properties
+     * are in fact a top level exclusion e.g one.two.three and one.three.two can be allowed for querying by
+     * specifying one in the schema. If they are not a top level exclusion then they are removed from the iterator and
+     * the map.
+     *
+     * @param fieldsToKeep - contains a list of fields that the user defined in their schema.
+     * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field.
+     * @param fieldName - contains the name of the field that we want to keep.
+     */
+    private void iterateThroughMapForFieldsToBeIndexed( final ArrayList fieldsToKeep, final Iterator collectionIterator,
+                                                        final String fieldName ) {
+        boolean toRemoveFlag = true;
+        String[] flattedStringArray = getStrings( fieldName );
+
+        Iterator fieldIterator = fieldsToKeep.iterator();
+
+        //goes through a loop of all the fields ( excluding default ) that we want to keep.
+        //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to true and remove
+        //the property.
+        while ( fieldIterator.hasNext() ) {
+            String requiredInclusionString = ( String ) fieldIterator.next();
+            String[] flattedRequirementString = getStrings( requiredInclusionString );
+
+
+            //loop each split array value to see if it matches the equivalent value
+            //in the field. e.g in the example one.two.three and one.two.four we need to check that the schema
+            //matches in both one and two above. If instead it says to exclude one.twor then we would still exclude the above
+            //since it is required to be a hard match.
+
+            //The way the below works if we see that the current field isn't as fine grained as the schema rule
+            //( aka the array is shorter than the current index of the schema rule then there is no way the rule could apply
+            // to the index.
+
+            //Then if that check passes we go to check that both parts are equal. If they are ever not equal
+            // e.g one.two.three and one.three.two then it shouldn't be included
+            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
+                //if the array contains a string that it is equals to then set the remove flag to true
+                //otherwise remain false.
+
+                if ( flattedStringArray.length <= index ) {
+                    toRemoveFlag = true;
+                    break;
+                }
+
+                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
+                    toRemoveFlag = false;
+                }
+                else {
+                    toRemoveFlag = true;
+                    break;
+                }
+            }
+            if ( toRemoveFlag == false ) {
+                break;
+            }
+        }
+
+        if ( toRemoveFlag ) {
+            collectionIterator.remove();
+        }
+    }
+
+
+    /**
+     * Splits the string on the flattened period "." seperated values.
+     * @param fieldName
+     * @return
+     */
     private String[] getStrings( final String fieldName ) {
         final String[] flattedStringArray;
-        if(!fieldName.contains( "." )){
+        if ( !fieldName.contains( "." ) ) {
             //create a single array that is made of a the single value.
-            flattedStringArray = new String[]{fieldName};
+            flattedStringArray = new String[] { fieldName };
         }
         else {
-            flattedStringArray= fieldName.split( "\\." );
+            flattedStringArray = fieldName.split( "\\." );
         }
         return flattedStringArray;
     }
 
 
-    //    private void innerLoop( final ArrayList fieldsToKeep, final HashSet mapFields, final EntityField testedField,
-//                            final String fieldName ) {//loop through and string split it all and if they still dont' match after that loop then remove them.
-//        boolean toRemoveFlag = true;
-//        String[] flattedStringArray = null;
-//
-//        if(!fieldName.contains( "." )){
-//            //create a single array that is made of a the single value.
-//            flattedStringArray = new String[]{fieldName};
-//        }
-//        else {
-//            flattedStringArray= fieldName.split( "\\." );
-//        }
-//
-//        Iterator fieldIterator = fieldsToKeep.iterator();
-//
-//        //goes through a loop of all the fields ( excluding default ) that we want to query on
-//        while(fieldIterator.hasNext()) {
-//            String requiredInclusionString = ( String ) fieldIterator.next();
-//            String[] flattedRequirementString;
-//
-//            //in the case you only have a filter that is a single field.Otherwise split it.
-//            if(!requiredInclusionString.contains( "." )){
-//                flattedRequirementString = new String[]{requiredInclusionString};
-//            }
-//            else {
-//                 flattedRequirementString= requiredInclusionString.split( "\\." );
-//            }
-//
-//
-//            //loop each split array value to see if it matches an equivalent value
-//            //in the field.
-//            for ( int index = 0; index < flattedRequirementString.length;index++){
-//                //if the array contains a string that it is equals to then set the remove flag to true
-//                //otherwise remain false.
-//
-//                if(flattedStringArray.length <= index){
-//                    toRemoveFlag = true;
-//                    break;
-//                }
-//                //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
-//                if(flattedRequirementString[index].equals( flattedStringArray[index] )){
-//                    toRemoveFlag=false;
-//                }
-//                else{
-//                    toRemoveFlag=true;
-//                }
-//            }
-//            if(toRemoveFlag==false){
-//                break;
-//            }
-//        }
-//
-//        if(toRemoveFlag){
-//            mapFields.remove( testedField );
-//        }
-//    }
-
 
     //Steps to delete an IndexEdge.
     //1.Take the search edge given and search for all the edges in elasticsearch matching that search edge


[08/36] usergrid git commit: Ignored test that isn't currently supported due to needing a new endpoint. Added logic that will index entire arrays by only specifying the top level identifier.

Posted by gr...@apache.org.
Ignored test that isn't currently supported due to needing a new endpoint.
Added logic that will index entire arrays by only specifying the top level identifier.


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

Branch: refs/heads/release-2.1.1
Commit: c0b96a56729e8f1bf10a6c883756dbedb08a4baa
Parents: f0480b4
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 16 15:21:04 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:25 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 78 +++++++++++++++++++-
 .../collection/CollectionsResourceIT.java       |  2 +-
 2 files changed, 77 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/c0b96a56/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 9e0e799..8d7a541 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -199,6 +199,7 @@ public class IndexServiceImpl implements IndexService {
         String jsonMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
 
         Set<String> defaultProperties = null;
+        ArrayList fieldsToKeep = null;
 
         if(jsonMap != null) {
 
@@ -206,7 +207,7 @@ public class IndexServiceImpl implements IndexService {
             Schema schema = Schema.getDefaultSchema();
             defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
             //TODO: additional logic to
-            ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
+            fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
             defaultProperties.addAll( fieldsToKeep );
         }
         else
@@ -221,6 +222,7 @@ public class IndexServiceImpl implements IndexService {
             while ( collectionIterator.hasNext() ) {
                 EntityField testedField = ( EntityField ) collectionIterator.next();
                 String fieldName = ( String ) (testedField).get( "name" );
+
                 //TODO: need to change the logic here such that default properties does a check against each every field.
                 //it is very likely that the below does O(n) comparisons anyways so doing it for each value in a loop
                 //would be the right equivalent here. Even if it isn't very efficient.
@@ -232,9 +234,81 @@ public class IndexServiceImpl implements IndexService {
                 //then if it doesn't do a split of the properties and see if any of them match for the split
                 //if they do match then allow in, otherwise don't allow.
 
+                //will only enter the loop for properties that aren't default properties so we only need to check
+                //the properties that the user imposed.
                 if ( !finalDefaultProperties.contains( fieldName ) ) {
-                    mapFields.remove( testedField );
+
+                    //loop through and string split it all and if they still dont' match after that loop then remove them.
+                    boolean toRemoveFlag = true;
+                    String[] flattedStringArray = fieldName.split( "\\." );
+                    Iterator fieldIterator = fieldsToKeep.iterator();
+                    while(fieldIterator.hasNext()) {
+                        String requiredInclusionString = ( String ) fieldIterator.next();
+                        String[] flattedRequirementString = new String[0];
+
+                        if(!requiredInclusionString.contains( "." )){
+                            flattedRequirementString = new String[]{requiredInclusionString};
+                        }
+                        else {
+                             flattedRequirementString= requiredInclusionString.split( "\\." );
+                        }
+
+                        //what we're aiming to do here is check the entire length of the string against
+                        //
+                        for ( int index = 0; index < flattedRequirementString.length;index++){
+                            //if the array contains a string that it is equals to then set the remove flag to true
+                            //otherwise remain false.
+
+                            //TODO: document that whatever comes first in the index will be filtered out in the way specified
+                            //so if the filtering spec had to filter one and one.two.three. and there is a value of
+                            // one.three. Then it will be filtered out because the rule one.two.three is applied
+                            //without a reference or care that one exists.
+                            if(flattedStringArray.length <= index){
+                                toRemoveFlag = true;
+                                break;
+                            }
+                            //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
+                            if(flattedRequirementString[index].equals( flattedStringArray[index] )){
+                                toRemoveFlag=false;
+                            }
+                            else{
+                                toRemoveFlag=true;
+                            }
+                        }
+                        if(toRemoveFlag==false){
+                            break;
+                        }
+                    }
+
+                    if(toRemoveFlag){
+                        mapFields.remove( testedField );
+                    }
+
                 }
+
+
+//                Iterator iterator = finalDefaultProperties.iterator();
+//                while(iterator.hasNext()){
+//                    String includedFieldName = ( String ) iterator.next();
+//                    //if the field name
+//                    if(!includedFieldName.equals( fieldName )){
+//
+//                    }
+//
+//                }
+
+//                for(int index = 0; index < finalDefaultProperties.size();index++){
+//                    finalDefaultProperties.
+//
+//                }
+
+//
+//                if ( !finalDefaultProperties.contains( fieldName ) ) {
+//                    mapFields.remove( testedField );
+//                }
+//                else{
+//
+//                }
             }
         }
         return map;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/c0b96a56/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index ab46681..7e29016 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -123,7 +123,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
      *
      * @throws Exception
      */
-    @Test
+    @Ignore("The reindexing isn't currently supported yet.")
     public void postToCollectionSchemaUpdateExistingCollection() throws Exception {
 
         //Create test collection with test entity that is full text indexed.


[19/36] usergrid git commit: Cleaning up the left over code from the endeavor.

Posted by gr...@apache.org.
Cleaning up the left over code from the endeavor.


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

Branch: refs/heads/release-2.1.1
Commit: 0feeebbccd47ebc642925da27164bb00e26a7e54
Parents: 0e53dcf
Author: George Reyes <gr...@apache.org>
Authored: Tue Mar 29 16:02:29 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Tue Mar 29 16:02:29 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpRelationManager.java      |   9 --
 .../asyncevents/EventBuilderImpl.java           |   1 -
 .../corepersistence/index/IndexServiceImpl.java | 115 ++-----------------
 .../usergrid/persistence/map/MapManager.java    |   2 -
 .../index/impl/EntityToMapConverter.java        |  10 --
 .../persistence/index/impl/EntityIndexTest.java |   4 +-
 .../rest/applications/ServiceResource.java      |   3 -
 .../collection/CollectionsResourceIT.java       |  20 ----
 .../usergrid/services/AbstractService.java      |   2 +-
 .../apache/usergrid/services/ServiceAction.java |   2 +-
 .../usergrid/services/ServiceManager.java       |   2 +-
 11 files changed, 13 insertions(+), 157 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
index 739aea4..378767e 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
@@ -356,15 +356,6 @@ public class CpRelationManager implements RelationManager {
     @Override
     public Entity addToCollection( String collectionName, EntityRef itemRef ) throws Exception {
 
-        /**
-         * Get the map manager for uuid mapping
-         */
-        Id mapOwner = new SimpleId( applicationId, TYPE_APPLICATION );
-
-        final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
-
-        MapManager mm = managerCache.getMapManager( ms );
-
         Preconditions.checkNotNull( itemRef, "itemref is null" );
         CollectionInfo collection = getDefaultSchema().getCollection( headEntity.getType(), collectionName );
         if ( ( collection != null && collection.getType() != null ) && !collection.getType()

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
index f2a8ff3..b6318fd 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
@@ -141,7 +141,6 @@ public class EventBuilderImpl implements EventBuilder {
         return new EntityDeleteResults( deIndexObservable, ecmDeleteObservable, graphCompactObservable );
     }
 
-    //TODO: have the map manager here and filter out the entities that are going to be loaded.
     @Override
     public Observable<IndexOperationMessage> buildEntityIndex( final EntityIndexOperation entityIndexOperation ) {
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index c3d5361..c010c06 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -123,9 +123,8 @@ public class IndexServiceImpl implements IndexService {
         //do our observable for batching
         //try to send a whole batch if we can
 
-        //TODO: extract the below and call a single method.
         final Observable<IndexOperationMessage>  batches =  sourceEdgesToIndex
-            .buffer(250, TimeUnit.MILLISECONDS, indexFig.getIndexBatchSize() ) //TODO: change to delay. maybe. at least to the before buffer.
+            .buffer(250, TimeUnit.MILLISECONDS, indexFig.getIndexBatchSize() )
 
             //map into batches based on our buffer size
             .flatMap( buffer -> Observable.from( buffer )
@@ -135,7 +134,7 @@ public class IndexServiceImpl implements IndexService {
                         logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
                     }
 
-                    final Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+                    final Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( indexEdge );
 
                     batch.index( indexEdge, entity ,fieldsToIndex);
                 } )
@@ -168,7 +167,7 @@ public class IndexServiceImpl implements IndexService {
                 logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
             }
 
-            Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+            Optional<Set<String>> fieldsToIndex = getFilteredStringObjectMap( indexEdge );
 
             batch.index( indexEdge, entity ,fieldsToIndex);
 
@@ -180,30 +179,21 @@ public class IndexServiceImpl implements IndexService {
 
     }
 
-
     /**
      * This method takes in an entity and flattens it out then begins the process to filter out
      * properties that we do not want to index. Once flatted we parse through each property
      * and verify that we want it to be indexed on. The set of default properties that will always be indexed are as follows.
      * UUID - TYPE - MODIFIED - CREATED. Depending on the schema this may change. For instance, users will always require
      * NAME, but the above four will always be taken in.
-     * @param applicationScope
-     * @param entity
+
      * @param indexEdge
      * @return This returns a filtered map that contains the flatted properties of the entity. If there isn't a schema
      * associated with the collection then return null ( and index the entity in its entirety )
      */
-    private Optional<Set<String>> getFilteredStringObjectMap( final ApplicationScope applicationScope,
-                                            final Entity entity, final IndexEdge indexEdge ) {
-
-
-        //TODO: THIS IS THE FIRST THING TO BE LOOKED AT TOMORROW.
-        //look into this.
-        IndexOperation indexOperation = new IndexOperation();
+    private Optional<Set<String>> getFilteredStringObjectMap( final IndexEdge indexEdge ) {
 
         Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
 
-        //TODO: this needs to be cached
         final MapScope ms = CpNamingUtils.getEntityTypeMapScope( mapOwner );
 
         MapManager mm = mapManagerFactory.createMapManager( ms );
@@ -211,17 +201,16 @@ public class IndexServiceImpl implements IndexService {
         Set<String> defaultProperties;
         ArrayList fieldsToKeep;
 
-        //TODO: extract collection name using other classes than the split.
-        String jsonSchemaMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
+        String collectionName = CpNamingUtils.getCollectionNameFromEdgeName( indexEdge.getEdgeName() );
+        String jsonSchemaMap = mm.getString( collectionName );
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
         if ( jsonSchemaMap != null ) {
 
             Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
             Schema schema = Schema.getDefaultSchema();
-            defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1] );
+            defaultProperties = schema.getRequiredProperties( collectionName );
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
-            //TODO: add method here to update the relevant fields in the map manager when it was accessed.
 
             defaultProperties.addAll( fieldsToKeep );
         }
@@ -232,94 +221,6 @@ public class IndexServiceImpl implements IndexService {
         return Optional.of(defaultProperties);
     }
 
-
-    /**
-     * This method is crucial for selective top level indexing. Here we check to see if the flatted properties
-     * are in fact a top level exclusion e.g one.two.three and one.three.two can be allowed for querying by
-     * specifying one in the schema. If they are not a top level exclusion then they are removed from the iterator and
-     * the map.
-     *
-     * @param fieldsToKeep - contains a list of fields that the user defined in their schema.
-     * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field.
-     * @param fieldName - contains the name of the field that we want to keep.
-     */
-    private void iterateThroughMapForFieldsToBeIndexed( final ArrayList fieldsToKeep, final Iterator collectionIterator,
-                                                        final String fieldName ) {
-        boolean toRemoveFlag = true;
-        String[] flattedStringArray = getStrings( fieldName );
-
-        Iterator fieldIterator = fieldsToKeep.iterator();
-
-        //goes through a loop of all the fields ( excluding default ) that we want to keep.
-        //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to true and remove
-        //the property.
-        while ( fieldIterator.hasNext() ) {
-            String requiredInclusionString = ( String ) fieldIterator.next();
-            String[] flattedRequirementString = getStrings( requiredInclusionString );
-
-
-            //loop each split array value to see if it matches the equivalent value
-            //in the field. e.g in the example one.two.three and one.two.four we need to check that the schema
-            //matches in both one and two above. If instead it says to exclude one.twor then we would still exclude the above
-            //since it is required to be a hard match.
-
-            //The way the below works if we see that the current field isn't as fine grained as the schema rule
-            //( aka the array is shorter than the current index of the schema rule then there is no way the rule could apply
-            // to the index.
-
-            //Then if that check passes we go to check that both parts are equal. If they are ever not equal
-            // e.g one.two.three and one.three.two then it shouldn't be included
-            //TODO: regex.
-            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
-                //if the array contains a string that it is equals to then set the remove flag to true
-                //otherwise remain false.
-
-                //one.three
-                //one.two
-                //one
-                if ( flattedStringArray.length <= index ) {
-                    toRemoveFlag = true;
-                    break;
-                }
-
-                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
-                    toRemoveFlag = false;
-                }
-                else {
-                    toRemoveFlag = true;
-                    break;
-                }
-            }
-            if ( toRemoveFlag == false ) {
-                break;
-            }
-        }
-
-        if ( toRemoveFlag ) {
-            collectionIterator.remove();
-        }
-    }
-
-
-    /**
-     * Splits the string on the flattened period "." seperated values.
-     * @param fieldName
-     * @return
-     */
-    private String[] getStrings( final String fieldName ) {
-        final String[] flattedStringArray;
-        if ( !fieldName.contains( "." ) ) {
-            //create a single array that is made of a the single value.
-            flattedStringArray = new String[] { fieldName };
-        }
-        else {
-            flattedStringArray = fieldName.split( "\\." );
-        }
-        return flattedStringArray;
-    }
-
-
-
     //Steps to delete an IndexEdge.
     //1.Take the search edge given and search for all the edges in elasticsearch matching that search edge
     //2. Batch Delete all of those edges returned in the previous search.

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
index ca8fd9a..80e2d17 100644
--- a/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
+++ b/stack/corepersistence/map/src/main/java/org/apache/usergrid/persistence/map/MapManager.java
@@ -27,8 +27,6 @@ import java.util.UUID;
 /**
  * Generator of a map manager instance
  */
-//TODO: This should be a singleton, otherwise cache could be out of sync and would need to invalidated everywher
-    //TODO: make manager cache injectable everywhere.
 public interface MapManager {
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 5a728a3..885f66e 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -108,10 +108,8 @@ public class EntityToMapConverter {
         //now visit our entity
         final FieldParser parser = new EntityMappingParser();
 
-        //TODO: to the parsing in the parse method below, that way we don't iterate twice and we filter things out as we see them.
         final Set<EntityField> fieldsToBeFiltered =   parser.parse( entityMap );
 
-
         //add our fields
         outputEntity.put( ENTITY_FIELDS, fieldsToBeFiltered );
 
@@ -126,14 +124,6 @@ public class EntityToMapConverter {
                 EntityField testedField = ( EntityField ) collectionIterator.next();
                 String fieldName = ( String ) ( testedField ).get( "name" );
 
-                //Checks to see if the fieldname is a default property. If it is then keep it, otherwise send it to
-                //be verified the aptly named method
-
-                //one.two.three
-                //one.two.four
-                //one.two3.five
-                //one.two
-                //fields { one.two }
                 if ( !defaultProperties.contains( fieldName ) ) {
                     iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
                 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/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 27f3afd..008ec80 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
@@ -365,7 +365,7 @@ public class EntityIndexTest extends BaseIT {
         EntityUtils.setVersion(entity, UUIDGenerator.newTimeUUID() );
         entity.setField(new UUIDField(IndexingUtils.ENTITY_ID_FIELDNAME, UUID.randomUUID() ) );
 
-        indexProducer.put(entityIndex.createBatch().index( searchEdge, entity, null ).build()).subscribe();
+        indexProducer.put(entityIndex.createBatch().index( searchEdge, entity ).build()).subscribe();
         entityIndex.refreshAsync().toBlocking().first();
 
         CandidateResults candidateResults = entityIndex
@@ -412,7 +412,7 @@ public class EntityIndexTest extends BaseIT {
             IndexEdge searchEdge = new IndexEdgeImpl( appId, "mehCars", SearchEdge.NodeType.SOURCE, System.currentTimeMillis()*1000 );
 
             //index the new entity. This is where the loop will be set to create like 100 entities.
-            indexProducer.put(entityIndex.createBatch().index( searchEdge, entity[i], null  ).build()).subscribe();
+            indexProducer.put(entityIndex.createBatch().index( searchEdge, entity[i] ).build()).subscribe();
 
         }
         entityIndex.refreshAsync().toBlocking().first();

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
index 9e7bc91..0b2fef6 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
@@ -462,9 +462,6 @@ public class ServiceResource extends AbstractContextResource {
         return response;
     }
 
-
-
-
     @SuppressWarnings({ "unchecked" })
     public ServicePayload getPayload( Object json ) {
         ServicePayload payload = null;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 7926e49..04ed18e 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -152,25 +152,9 @@ public class CollectionsResourceIT extends AbstractRestIT {
         Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
-        //TODO: write a test to verify the data below.
-
-        //        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
-        //
-        //        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-        //        //TODO: the below will have to be replaced by the values that I deem correct.
-        //        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
-        //        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-        //        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
-        //
-        //        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
-        //        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
-        //        assertEquals( "one",schema.get( 0 ) );
-
 
         //Reindex and verify that the entity only has field one index.
         this.app().collection( "testCollection" ).collection( "_reindex" ).post(true,clientSetup.getSuperuserToken(),ApiResponse.class,null,null,false);
-       // Thread.sleep( 10000 );
-        //refreshIndex();
 
         for(int i = 0; i < 10; i++) {
             String query = "one ='value"+ i + "'";
@@ -218,17 +202,13 @@ public class CollectionsResourceIT extends AbstractRestIT {
         Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
-        //TODO: write a test to verify the data below.
-
         Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
 
         LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-        //TODO: the below will have to be replaced by the values that I deem correct.
         assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
         assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
         assertEquals( 0,testCollectionSchema.get( "lastReindexed" ) );
 
-        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
         ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
         assertEquals( "one",schema.get( 0 ) );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
index 7d33144..e10cb3f 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
@@ -1366,7 +1366,7 @@ public abstract class AbstractService implements Service {
         if ( currentUser == null ) {
             return;
         }
-        //this is breaking because there is no entity manager there.
+
         String perm = getPermissionFromPath( em.getApplicationRef().getUuid(), context.getAction().toString().toLowerCase(),
                         path );
         boolean permitted = currentUser.isPermitted( perm );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java b/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
index ec34df4..e1c6133 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
@@ -18,5 +18,5 @@ package org.apache.usergrid.services;
 
 
 public enum ServiceAction {
-    POST, GET, PUT, DELETE, HEAD, OPTIONS, SCHEMA;
+    POST, GET, PUT, DELETE, HEAD, OPTIONS;
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/0feeebbc/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java b/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
index 9089ab7..a9892f5 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/ServiceManager.java
@@ -290,7 +290,7 @@ public class ServiceManager {
             if ( ( cls != null ) && !Modifier.isAbstract( cls.getModifiers() ) ) {
                 return cls;
             }
-        } //TODO:Find a different way to express this exception. The real exception is returned above. This just needs to be handled some way.
+        }
         catch ( ClassNotFoundException e1 ) {
             if(logger.isTraceEnabled()){
                 logger.trace("Could not find class", e1);


[04/36] usergrid git commit: Another cherry pick with another issue with collection resource it and nothing else.

Posted by gr...@apache.org.
Another cherry pick with another issue with collection resource it and nothing else.


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

Branch: refs/heads/release-2.1.1
Commit: aa7f776edae7f9a2cb4c1577b6c86e1c028f082a
Parents: 99c75cc
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 11 15:19:52 2016 -0800
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:08:05 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        | 11 ---
 .../corepersistence/CpRelationManager.java      | 54 ++++++++++++
 .../asyncevents/EventBuilderImpl.java           |  2 +-
 .../corepersistence/index/IndexServiceImpl.java | 73 ++++++++++++++--
 .../impl/EntityCollectionManagerImpl.java       |  2 +-
 .../index/impl/EsEntityIndexBatchImpl.java      |  9 +-
 .../collection/CollectionsResourceIT.java       | 87 +++++++++++++++++++-
 .../services/AbstractCollectionService.java     |  1 -
 8 files changed, 215 insertions(+), 24 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/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 d5ba946..1fbacbe 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
@@ -1770,17 +1770,6 @@ public class CpEntityManager implements EntityManager {
         return obj;
     }
 
-//    @Override
-//    public Entity createCollectionSchema( String collectionName ){
-//        MapManager mm = getMapManagerForTypes();
-//        String jsonMap = mm.getString( collectionName );
-//
-//        Object obj = JsonUtils.parse( jsonMap );
-//
-//        return null;
-//    }
-
-
         @Override
     public void grantRolePermission( String roleName, String permission ) throws Exception {
         roleName = roleName.toLowerCase();

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
index cfb8dfa..faffbba 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
@@ -18,6 +18,7 @@ package org.apache.usergrid.corepersistence;
 
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -69,10 +70,15 @@ import org.apache.usergrid.persistence.index.EntityIndex;
 import org.apache.usergrid.persistence.index.EntityIndexBatch;
 import org.apache.usergrid.persistence.index.SearchEdge;
 import org.apache.usergrid.persistence.index.query.Identifier;
+import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.persistence.map.MapScope;
 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.NullField;
 import org.apache.usergrid.persistence.schema.CollectionInfo;
 import org.apache.usergrid.utils.InflectionUtils;
+import org.apache.usergrid.utils.JsonUtils;
 import org.apache.usergrid.utils.MapUtils;
 
 import com.google.common.base.Optional;
@@ -90,6 +96,7 @@ import static org.apache.usergrid.persistence.Schema.COLLECTION_ROLES;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_INACTIVITY;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_TITLE;
+import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
 import static org.apache.usergrid.persistence.Schema.TYPE_ENTITY;
 import static org.apache.usergrid.persistence.Schema.TYPE_ROLE;
 import static org.apache.usergrid.persistence.Schema.getDefaultSchema;
@@ -349,6 +356,15 @@ public class CpRelationManager implements RelationManager {
     @Override
     public Entity addToCollection( String collectionName, EntityRef itemRef ) throws Exception {
 
+        /**
+         * Get the map manager for uuid mapping
+         */
+        Id mapOwner = new SimpleId( applicationId, TYPE_APPLICATION );
+
+        final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
+
+        MapManager mm = managerCache.getMapManager( ms );
+
         Preconditions.checkNotNull( itemRef, "itemref is null" );
         CollectionInfo collection = getDefaultSchema().getCollection( headEntity.getType(), collectionName );
         if ( ( collection != null && collection.getType() != null ) && !collection.getType()
@@ -392,6 +408,44 @@ public class CpRelationManager implements RelationManager {
 
         GraphManager gm = managerCache.getGraphManager( applicationScope );
 
+//        //do logic here
+//        String jsonMap = mm.getString( collectionName );
+//
+//        Set<String> defaultProperties = null;
+//
+//        if(jsonMap != null) {
+//
+//            Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
+//            Schema schema = Schema.getDefaultSchema();
+//            defaultProperties = schema.getRequiredProperties( collectionName );
+//            //TODO: additional logic to
+//            ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
+//            defaultProperties.addAll( fieldsToKeep );
+//
+//        }
+//
+//        Collection<String> trimmedFields = null;
+//        if(defaultProperties!=null){
+//           // if(cpHeadEntity.getFields())
+//            final Set<String> finalDefaultProperties = defaultProperties;
+//            trimmedFields = memberEntity.getFieldMap().keySet();
+//            Iterator collectionIterator = trimmedFields.iterator();
+//            while(collectionIterator.hasNext()){
+//                if(!finalDefaultProperties.contains( collectionIterator.next() )){
+//                    collectionIterator.remove();
+//                }
+//            }
+
+
+//            trimmedFields.forEach( element -> {
+//                if(!finalDefaultProperties.contains( element )){
+//                    memberEntity.removeField( element );
+//                }
+//            });
+
+//        }
+
+
         gm.writeEdge( edge ).doOnNext( writtenEdge -> {
             if ( logger.isDebugEnabled() ) {
                 logger.debug( "Wrote edge {}", writtenEdge );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
index 2edc668..f2a8ff3 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/EventBuilderImpl.java
@@ -141,7 +141,7 @@ public class EventBuilderImpl implements EventBuilder {
         return new EntityDeleteResults( deIndexObservable, ecmDeleteObservable, graphCompactObservable );
     }
 
-
+    //TODO: have the map manager here and filter out the entities that are going to be loaded.
     @Override
     public Observable<IndexOperationMessage> buildEntityIndex( final EntityIndexOperation entityIndexOperation ) {
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 6c07212..01bc516 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -20,11 +20,22 @@
 package org.apache.usergrid.corepersistence.index;
 
 
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
+import org.apache.usergrid.persistence.Schema;
 import org.apache.usergrid.persistence.index.*;
+import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.persistence.map.MapManagerFactory;
+import org.apache.usergrid.persistence.map.MapScope;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
+import org.apache.usergrid.persistence.model.field.Field;
+import org.apache.usergrid.utils.JsonUtils;
 import org.apache.usergrid.utils.UUIDUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -52,6 +63,7 @@ import rx.Observable;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createSearchEdgeFromSource;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.generateScopeFromSource;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.generateScopeFromTarget;
+import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
 import static org.apache.usergrid.persistence.Schema.getDefaultSchema;
 
 
@@ -66,6 +78,7 @@ public class IndexServiceImpl implements IndexService {
 
     private final GraphManagerFactory graphManagerFactory;
     private final EntityIndexFactory entityIndexFactory;
+    private final MapManagerFactory mapManagerFactory;
     private final EdgesObservable edgesObservable;
     private final IndexFig indexFig;
     private final IndexLocationStrategyFactory indexLocationStrategyFactory;
@@ -75,9 +88,13 @@ public class IndexServiceImpl implements IndexService {
 
     @Inject
     public IndexServiceImpl( final GraphManagerFactory graphManagerFactory, final EntityIndexFactory entityIndexFactory,
-                             final EdgesObservable edgesObservable, final IndexFig indexFig, final IndexLocationStrategyFactory indexLocationStrategyFactory, final MetricsFactory metricsFactory ) {
+                             final MapManagerFactory mapManagerFactory,
+                             final EdgesObservable edgesObservable, final IndexFig indexFig,
+                             final IndexLocationStrategyFactory indexLocationStrategyFactory,
+                             final MetricsFactory metricsFactory ) {
         this.graphManagerFactory = graphManagerFactory;
         this.entityIndexFactory = entityIndexFactory;
+        this.mapManagerFactory = mapManagerFactory;
         this.edgesObservable = edgesObservable;
         this.indexFig = indexFig;
         this.indexLocationStrategyFactory = indexLocationStrategyFactory;
@@ -93,7 +110,6 @@ public class IndexServiceImpl implements IndexService {
         final GraphManager gm = graphManagerFactory.createEdgeManager( applicationScope );
         final EntityIndex ei = entityIndexFactory.createEntityIndex(indexLocationStrategyFactory.getIndexLocationStrategy(applicationScope));
 
-
         final Id entityId = entity.getId();
 
 
@@ -142,11 +158,58 @@ public class IndexServiceImpl implements IndexService {
 
             final EntityIndexBatch batch = ei.createBatch();
 
-            if (logger.isDebugEnabled()) {
+           // if (logger.isDebugEnabled()) {
                 logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
-            }
+           // }
+
+
+                indexEdge.getNodeId().getUuid();
+
+                //System.out.println("hello");
+
+                Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
+
+                final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
+
+                MapManager mm = mapManagerFactory.createMapManager( ms );
+
+
+
+                String jsonMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
+
+                Set<String> defaultProperties = null;
+
+                if(jsonMap != null) {
+
+                    Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
+                    Schema schema = Schema.getDefaultSchema();
+                    defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
+                    //TODO: additional logic to
+                    ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
+                    defaultProperties.addAll( fieldsToKeep );
+
+                }
+
+            Entity filteredEntity = new Entity( entity.getId(),entity.getVersion() );
+            filteredEntity.setFieldMap( entity.getFieldMap() );
+
+                Collection<String> trimmedFields = null;
+                if(defaultProperties!=null) {
+                    // if(cpHeadEntity.getFields())
+                    final Set<String> finalDefaultProperties = defaultProperties;
+                    trimmedFields = entity.getFieldMap().keySet();
+                    Iterator collectionIterator = trimmedFields.iterator();
+                    while ( collectionIterator.hasNext() ) {
+                        String fieldName = ( String ) collectionIterator.next();
+                        if ( !finalDefaultProperties.contains( fieldName ) ) {
+                            //collectionIterator.remove();
+                            filteredEntity.removeField( fieldName );
+                        }
+                    }
+                }
+
 
-            batch.index( indexEdge, entity );
+            batch.index( indexEdge, filteredEntity );
 
             return batch.build();
         } );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/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 06025d3..e71e6bb 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
@@ -184,7 +184,7 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
         // create our observable and start the write
         final CollectionIoEvent<Entity> writeData = new CollectionIoEvent<Entity>( applicationScope, entity );
 
-        Observable<CollectionIoEvent<MvccEntity>> observable = stageRunner( writeData, writeStart );
+        Observable<CollectionIoEvent<MvccEntity>> observable =  stageRunner( writeData, writeStart );
 
 
         final Observable<Entity> write = observable.map( writeCommit )

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
index 9427be1..f703e32 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
@@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.core.util.ValidationUtils;
 import org.apache.usergrid.persistence.index.utils.IndexValidationUtils;
+import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
 
@@ -68,10 +69,10 @@ public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
         final String writeAlias = alias.getWriteAlias();
 
-        if ( logger.isDebugEnabled() ) {
-            logger.debug( "Indexing to alias {} with scope {} on edge {} with entity data {}",
-                    writeAlias, applicationScope, indexEdge, entity );
-        }
+        //if ( logger.isDebugEnabled() ) {
+            logger.info( "Indexing to alias {} with scope {} on edge {} with entity data {}",
+                    writeAlias, applicationScope, indexEdge, entity.getFieldMap().keySet() );
+        //}
 
         //add app id for indexing
         container.addIndexRequest(new IndexOperation(writeAlias, applicationScope, indexEdge, entity));

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index cea9d5e..1aa91d1 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -21,12 +21,14 @@ import com.fasterxml.jackson.databind.JsonNode;
 
 import org.apache.usergrid.persistence.Schema;
 import org.apache.usergrid.persistence.entities.Application;
+
 import org.apache.usergrid.rest.test.resource.AbstractRestIT;
 import org.apache.usergrid.rest.test.resource.model.ApiResponse;
 import org.apache.usergrid.rest.test.resource.model.Collection;
 import org.apache.usergrid.rest.test.resource.model.Entity;
 import org.apache.usergrid.rest.test.resource.model.QueryParameters;
 import org.apache.usergrid.rest.test.resource.model.Token;
+
 import org.junit.Ignore;
 import org.junit.Test;
 import org.slf4j.Logger;
@@ -123,7 +125,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
      * @throws Exception
      */
     @Test
-    public void postToReservedField() throws Exception {
+    public void postToCollectionSchemaUpdateExistingCollection() throws Exception {
 
         //Create test collection with test entity that is full text indexed.
         Entity testEntity = new Entity();
@@ -163,6 +165,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
         assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
         assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
 
+        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
         ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
         assertEquals( "one",schema.get( 0 ) );
 
@@ -179,6 +182,88 @@ public class CollectionsResourceIT extends AbstractRestIT {
     }
 
     /**
+     * Create test collection
+     * Give collection an indexing schema
+     * Give collection a new entity and ensure it only indexes wht is in the schema
+     * Reindex and make sure old entity with full text indexing is reindexed with the schema.
+     *
+     * @throws Exception
+     */
+    @Test
+    public void postToCollectionSchemaWithSchemaFirst() throws Exception {
+
+
+
+        //Creating schema.
+        //this could be changed to a hashmap.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "one" );
+        indexingArray.add( "name" );
+
+        //TODO: add indexing array to the backend/test once you finish the regular selective indexing.
+        //indexingArray.add( "field.three.index.array" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+       // Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        //Create test collection with test entity that is full text indexed.
+        Entity testEntity = new Entity();
+        //testEntity.put( "name", "tester");
+        testEntity.put( "one", "helper" );
+        //this field shouldn't persist after reindexing.
+        testEntity.put( "two","query" );
+
+        //TODO: add arrays to the indexing test
+        //testEntity.put("array","array stuff here");
+
+        Entity returnedEntity = this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+        //testEntity.put( "three","notthree" );
+        //ApiResponse updatedEntity = this.app().collection( "testCollection" ).put( null,testEntity );
+
+        //Below is what needs to be implemented along with the index call above
+
+//        //Get the collection schema and verify that it contains the same schema as posted above.
+//        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+//
+//        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+//        //TODO: the below will have to be replaced by the values that I deem correct.
+//        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+//        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+//        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+
+//        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
+//        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+//        assertEquals( "one",schema.get( 0 ) );
+
+        //Reindex and verify that the entity only has field one index.
+//        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+//
+//        refreshIndex();
+
+        //this needs to be a query. not a graph. This should still return the full entity.
+
+        String query = "two ='query'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+//having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+
+
+        Entity reindexedEntity = tempEntity.getResponse().getEntity(); //this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
+        assertEquals( "helper",reindexedEntity.get( "one" ) );
+        assertNull( reindexedEntity.get( "two" ) );
+        //not sure if this should have some kind of sleep here because this reindex will be heavily throttled.
+
+    }
+
+
+    /**
      * Test posts with a user level token on a path with permissions
      */
     //TODO: App level permissions aren't functioning.

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aa7f776e/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
index 4d73fa5..8b23e7a 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
@@ -333,7 +333,6 @@ public class AbstractCollectionService extends AbstractService {
         setServiceManager( serviceRequest.getServices() );
         ServiceContext context = serviceRequest.getAppContext();
 
-        context.setAction( ServiceAction.POST );
         checkPermissionsForCollection( context );
         Subject currentUser = SubjectUtils.getSubject();
         Object currentUser2 =currentUser.getPrincipal();


[03/36] usergrid git commit: Cherry picking 2 more commits with the working selective indexing but improperly

Posted by gr...@apache.org.
Cherry picking 2 more commits with the working selective indexing but improperly


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

Branch: refs/heads/release-2.1.1
Commit: 99c75ccd6ca16f93e3be934e5f1c5455d6e375c5
Parents: 58e6cf3
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 9 12:18:36 2016 -0800
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:06:42 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  21 +-
 .../usergrid/persistence/EntityManager.java     |   2 +-
 .../rest/applications/ApplicationResource.java  |   2 +-
 .../rest/applications/CollectionResource.java   | 199 +++++++++++++++++++
 .../rest/applications/ServiceResource.java      | 142 ++++++-------
 .../collection/CollectionsResourceIT.java       |  13 +-
 .../services/AbstractCollectionService.java     |  23 ++-
 .../services/AbstractConnectionsService.java    |  10 +-
 .../usergrid/services/AbstractService.java      |  12 +-
 .../org/apache/usergrid/services/Service.java   |   3 +
 .../usergrid/services/ServiceRequest.java       |   5 +
 .../applications/ApplicationsService.java       |  11 +-
 12 files changed, 338 insertions(+), 105 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/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 6a6d036..d5ba946 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
@@ -1754,27 +1754,32 @@ public class CpEntityManager implements EntityManager {
         schemaMap.put("lastReindexed",0);
         schemaMap.putAll( properties );
 
-        //Map<String,Object> fields = properties.get( "properties" );
-
-        //for(Object)
-
         MapManager mm = getMapManagerForTypes();
-        mm.putString( collectionName,schemaMap.toString() );
+        mm.putString( collectionName,JsonUtils.mapToJsonString( schemaMap ) );
 
         return schemaMap;
 
     }
 
     @Override
-    public Entity createCollectionSchema( String collectionName ){
+    public Object getCollectionSchema( String collectionName ){
         MapManager mm = getMapManagerForTypes();
         String jsonMap = mm.getString( collectionName );
 
         Object obj = JsonUtils.parse( jsonMap );
-
-        return null;
+        return obj;
     }
 
+//    @Override
+//    public Entity createCollectionSchema( String collectionName ){
+//        MapManager mm = getMapManagerForTypes();
+//        String jsonMap = mm.getString( collectionName );
+//
+//        Object obj = JsonUtils.parse( jsonMap );
+//
+//        return null;
+//    }
+
 
         @Override
     public void grantRolePermission( String roleName, String permission ) throws Exception {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/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 7c5cc5b..13fb098 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
@@ -514,7 +514,7 @@ public interface EntityManager {
 
     public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties );
 
-    Entity createCollectionSchema( String collectionName );
+    Object getCollectionSchema( String collectionName );
 
     public void grantRolePermission( String roleName, String permission ) throws Exception;
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
----------------------------------------------------------------------
diff --git 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
index f2d07e3..9836f1c 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
@@ -82,7 +82,7 @@ import static org.apache.usergrid.utils.StringUtils.stringOrSubstringBeforeFirst
         MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript",
         "application/ecmascript", "text/jscript"
 })
-public class ApplicationResource extends ServiceResource {
+public class ApplicationResource extends CollectionResource {
 
     public static final Logger logger = LoggerFactory.getLogger( ApplicationResource.class );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
new file mode 100644
index 0000000..856bce0
--- /dev/null
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -0,0 +1,199 @@
+/*
+ * 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.rest.applications;
+
+
+import java.util.UUID;
+
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+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.UriInfo;
+
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+
+import org.apache.commons.lang.StringUtils;
+
+import org.apache.usergrid.persistence.Query;
+import org.apache.usergrid.rest.AbstractContextResource;
+import org.apache.usergrid.rest.ApiResponse;
+import org.apache.usergrid.rest.RootResource;
+import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
+import org.apache.usergrid.services.AbstractCollectionService;
+import org.apache.usergrid.services.ServiceAction;
+import org.apache.usergrid.services.ServiceParameter;
+import org.apache.usergrid.services.ServicePayload;
+
+import com.fasterxml.jackson.jaxrs.json.annotation.JSONP;
+
+
+/**
+ * A collection resource that stands before the Service Resource. If it cannot find
+ * the specified method then we should route the call to the service resource proper.
+ * Otherwise handle it in here.
+ */
+@Component
+@Scope("prototype")
+@Produces({
+    MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript",
+    "application/ecmascript", "text/jscript"
+})
+public class CollectionResource extends ServiceResource {
+
+    public CollectionResource() {
+    }
+
+    /**
+     * THE BEGINNINGS OF AN ENDPOINT THAT WILL ALLOW TO DEFINE WHAT TO
+     * STORE IN ELASTICSEARCH.
+     * @param ui
+     * @param callback
+     * @return
+     * @throws Exception
+     */
+    @POST
+    @Path("_indexes")
+    @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executePostOnIndexes( @Context UriInfo ui, String body,
+                                             @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.executePostOnIndexes" );
+        }
+
+        Object json;
+        if ( StringUtils.isEmpty( body ) ) {
+            json = null;
+        } else {
+            json = readJsonToObject( body );
+        }
+
+        ApiResponse response = createApiResponse();
+
+        response.setAction( "post" );
+        response.setApplication( services.getApplication() );
+        response.setParams( ui.getQueryParameters() );
+
+        ServicePayload payload = getPayload( json );
+
+        executeServicePostRequestForSchema( ui,response, ServiceAction.POST,payload );
+
+        return response;
+    }
+
+    @GET
+    @Path("_index")
+    @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executeGetOnIndex( @Context UriInfo ui, String body,
+                                          @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "CollectionResource.executeGetOnIndex" );
+        }
+
+        Object json;
+        if ( StringUtils.isEmpty( body ) ) {
+            json = null;
+        } else {
+            json = readJsonToObject( body );
+        }
+
+        ApiResponse response = createApiResponse();
+
+
+
+        response.setAction( "get" );
+        response.setApplication( services.getApplication() );
+        response.setParams( ui.getQueryParameters() );
+
+        executeServiceGetRequestForSchema( ui,response,ServiceAction.GET,null );
+
+        ///ServicePayload payload = getPayload( json );
+
+        ///emf.getEntityManager( getApplicationId() ).get
+
+        //executeServiceRequest( ui, response, ServiceAction.GET, payload );
+
+        return response;
+    }
+
+    @Override
+    @Path( RootResource.ENTITY_ID_PATH)
+    public AbstractContextResource addIdParameter( @Context UriInfo ui, @PathParam("entityId") PathSegment entityId )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.addIdParameter" );
+        }
+
+        UUID itemId = UUID.fromString( entityId.getPath() );
+
+        ServiceParameter.addParameter( getServiceParameters(), itemId );
+
+        addMatrixParams( getServiceParameters(), ui, entityId );
+
+        return getSubResource( CollectionResource.class );
+    }
+
+
+    @Override
+    @Path("{itemName}")
+    public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName )
+        throws Exception {
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.addNameParameter" );
+            logger.trace( "Current segment is {}", itemName.getPath() );
+        }
+
+
+        if ( itemName.getPath().startsWith( "{" ) ) {
+            Query query = Query.fromJsonString( itemName.getPath() );
+            if ( query != null ) {
+                ServiceParameter.addParameter( getServiceParameters(), query );
+            }
+        }
+        else {
+            ServiceParameter.addParameter( getServiceParameters(), itemName.getPath() );
+        }
+
+        addMatrixParams( getServiceParameters(), ui, itemName );
+
+        return getSubResource( CollectionResource.class );
+    }
+
+//    @
+//    public ServiceResource doLogicInServiceResource() throws Exception{
+//        return getSubResource( ServiceResource.class );
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
index 3318adf..c723366 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
@@ -244,7 +244,64 @@ public class ServiceResource extends AbstractContextResource {
         return getSubResource( ServiceResource.class );
     }
 
-    public ServiceResults executeServiceRequestForSchema(UriInfo ui, ApiResponse response, ServiceAction action,
+
+    public ServiceResults executeServiceGetRequestForSchema(UriInfo ui, ApiResponse response, ServiceAction action,
+                                                             ServicePayload payload) throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.executeServiceRequest" );
+        }
+
+
+        boolean tree = "true".equalsIgnoreCase( ui.getQueryParameters().getFirst( "tree" ) );
+
+        String connectionQueryParm = ui.getQueryParameters().getFirst("connections");
+        boolean returnInboundConnections = true;
+        boolean returnOutboundConnections = true;
+
+        addQueryParams( getServiceParameters(), ui );
+
+        ServiceRequest r = services.newRequest( action, tree, getServiceParameters(), payload,
+            returnInboundConnections, returnOutboundConnections );
+
+        response.setServiceRequest( r );
+
+
+        AbstractCollectionService abstractCollectionService = new AbstractCollectionService();
+
+       // abstractCollectionService
+        ServiceResults results = abstractCollectionService.getCollectionSchema( r );
+
+        //        ServiceResults results = r.execute();
+        if ( results != null ) {
+            if ( results.hasData() ) {
+                response.setData( results.getData() );
+            }
+            if ( results.getServiceMetadata() != null ) {
+                response.setMetadata( results.getServiceMetadata() );
+            }
+            Query query = r.getLastQuery();
+            if ( query != null ) {
+                if ( query.hasSelectSubjects() ) {
+                    response.setList( QueryUtils.getSelectionResults( query, results ) );
+                    response.setCount( response.getList().size() );
+                    response.setNext( results.getNextResult() );
+                    response.setPath( results.getPath() );
+                    return results;
+                }
+            }
+
+            response.setResults( results );
+        }
+
+        httpServletRequest.setAttribute( "applicationId", services.getApplicationId() );
+
+        return results;
+
+
+    }
+
+    public ServiceResults executeServicePostRequestForSchema(UriInfo ui, ApiResponse response, ServiceAction action,
                                                          ServicePayload payload) throws Exception {
 
         if(logger.isTraceEnabled()){
@@ -264,7 +321,13 @@ public class ServiceResource extends AbstractContextResource {
             returnInboundConnections, returnOutboundConnections );
 
         response.setServiceRequest( r );
-        ServiceResults results = r.execute();
+
+
+        AbstractCollectionService abstractCollectionService = new AbstractCollectionService();
+
+        ServiceResults results = abstractCollectionService.postCollectionSchema( r );
+
+//        ServiceResults results = r.execute();
         if ( results != null ) {
             if ( results.hasData() ) {
                 response.setData( results.getData() );
@@ -402,81 +465,6 @@ public class ServiceResource extends AbstractContextResource {
     }
 
 
-    /**
-     * THE BEGINNINGS OF AN ENDPOINT THAT WILL ALLOW TO DEFINE WHAT TO
-     * STORE IN ELASTICSEARCH.
-     * @param ui
-     * @param callback
-     * @return
-     * @throws Exception
-     */
-    @POST
-    @Path("_indexes")
-    @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
-    @RequireApplicationAccess
-    @JSONP
-    public ApiResponse executePostOnIndexes( @Context UriInfo ui, String body,
-                                   @QueryParam("callback") @DefaultValue("callback") String callback )
-        throws Exception {
-
-        if(logger.isTraceEnabled()){
-            logger.trace( "ServiceResource.executePostOnIndexes" );
-        }
-
-        Object json;
-        if ( StringUtils.isEmpty( body ) ) {
-            json = null;
-        } else {
-            json = readJsonToObject( body );
-        }
-
-        ApiResponse response = createApiResponse();
-
-        response.setAction( "post" );
-        response.setApplication( services.getApplication() );
-        response.setParams( ui.getQueryParameters() );
-
-        ServicePayload payload = getPayload( json );
-
-        executeServiceRequestForSchema( ui,response,ServiceAction.SCHEMA,payload );
-
-        return response;
-    }
-
-    @GET
-    @Path("_index")
-    @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
-    @RequireApplicationAccess
-    @JSONP
-    public ApiResponse executeGetOnIndex( @Context UriInfo ui, String body,
-                                             @QueryParam("callback") @DefaultValue("callback") String callback )
-        throws Exception {
-
-        if(logger.isTraceEnabled()){
-            logger.trace( "ServiceResource.executePostOnIndexes" );
-        }
-
-        Object json;
-        if ( StringUtils.isEmpty( body ) ) {
-            json = null;
-        } else {
-            json = readJsonToObject( body );
-        }
-
-        ApiResponse response = createApiResponse();
-
-
-
-        response.setAction( "get" );
-        response.setApplication( services.getApplication() );
-        response.setParams( ui.getQueryParameters() );
-
-        ServicePayload payload = getPayload( json );
-
-        executeServiceRequest( ui, response, ServiceAction.GET, payload );
-
-        return response;
-    }
 
 
     @SuppressWarnings({ "unchecked" })

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 773317b..cea9d5e 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -149,7 +149,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
         payload.put( "fields", indexingArray);
 
         //Post index to the collection metadata
-        Object thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
         //Below is what needs to be implemented along with the index call above
@@ -157,12 +157,11 @@ public class CollectionsResourceIT extends AbstractRestIT {
         //Get the collection schema and verify that it contains the same schema as posted above.
         Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
 
-        Entity testCollectionSchema = (Entity)collection.getResponse().getEntity();
-        //the below will have to be replaced by the values that I deem correct.
-        assertEquals( "lastUpdated", testCollectionSchema.get( "lastUpdated" ));
-        assertEquals( "lastUpdatedBy",testCollectionSchema.get( "lastUpdatedBy" ) );
-        assertEquals( "lastReindex",testCollectionSchema.get( "lastReindex" ) );
-
+        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+        //TODO: the below will have to be replaced by the values that I deem correct.
+        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
 
         ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
         assertEquals( "one",schema.get( 0 ) );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
index f6d2849..4d73fa5 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
@@ -55,6 +55,11 @@ public class AbstractCollectionService extends AbstractService {
         declareMetadataType( "indexes" );
     }
 
+    public AbstractCollectionService(ServiceRequest serviceRequest){
+        setServiceManager( serviceRequest.getServices() );
+    }
+
+
     @Override
     public Entity getEntity( ServiceRequest request, UUID uuid ) throws Exception {
         if ( !isRootService() ) {
@@ -324,7 +329,10 @@ public class AbstractCollectionService extends AbstractService {
     }
 
     @Override
-    public ServiceResults postCollectionSchema( ServiceContext context ) throws Exception {
+    public ServiceResults postCollectionSchema( ServiceRequest serviceRequest ) throws Exception {
+        setServiceManager( serviceRequest.getServices() );
+        ServiceContext context = serviceRequest.getAppContext();
+
         context.setAction( ServiceAction.POST );
         checkPermissionsForCollection( context );
         Subject currentUser = SubjectUtils.getSubject();
@@ -337,6 +345,19 @@ public class AbstractCollectionService extends AbstractService {
 
     }
 
+    @Override
+    public ServiceResults getCollectionSchema( ServiceRequest serviceRequest ) throws Exception {
+        setServiceManager( serviceRequest.getServices() );
+        ServiceContext context = serviceRequest.getAppContext();
+        context.setAction( ServiceAction.GET );
+        checkPermissionsForCollection( context );
+
+        Object collectionSchema = em.getCollectionSchema( context.getCollectionName() );
+
+        return new ServiceResults( this, context, Type.COLLECTION, Results.fromData( collectionSchema ), null, null );
+
+    }
+
 
     @Override
     public ServiceResults postCollection( ServiceContext context ) throws Exception {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
index 666f676..395f2d4 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
@@ -392,8 +392,14 @@ public class AbstractConnectionsService extends AbstractService {
 
 
     @Override
-    public ServiceResults postCollectionSchema( final ServiceContext context ) throws Exception {
-        throw new UnsupportedServiceOperationException( context );
+    public ServiceResults postCollectionSchema( final ServiceRequest request ) throws Exception {
+        throw new UnsupportedServiceOperationException( request );
+    }
+
+
+    @Override
+    public ServiceResults getCollectionSchema( final ServiceRequest serviceRequest ) throws Exception {
+        throw new UnsupportedServiceOperationException( serviceRequest );
     }
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
index 3c5503c..7d33144 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
@@ -656,6 +656,7 @@ public abstract class AbstractService implements Service {
      * the queue. Remaining parameters are left for next service request to allow for request chaining.
      */
 
+    @Override
     public ServiceContext getContext( ServiceAction action, ServiceRequest request, ServiceResults previousResults,
                                       ServicePayload payload ) throws Exception {
 
@@ -828,9 +829,6 @@ public abstract class AbstractService implements Service {
 
             case HEAD:
                 return headCollection( context );
-
-            case SCHEMA:
-                return postCollectionSchema( context );
         }
 
         throw new ServiceInvocationException( context, "Request action unhandled " + context.getAction() );
@@ -891,8 +889,10 @@ public abstract class AbstractService implements Service {
         return getItemsByQuery( context, query );
     }
 
+    public abstract ServiceResults postCollectionSchema( ServiceRequest serviceRequest ) throws Exception;
+
 
-    public abstract ServiceResults postCollectionSchema( ServiceContext context ) throws Exception;
+    public abstract ServiceResults getCollectionSchema( ServiceRequest serviceRequest ) throws Exception;
 
 
     public ServiceResults postCollection( ServiceContext context ) throws Exception {
@@ -1366,8 +1366,8 @@ public abstract class AbstractService implements Service {
         if ( currentUser == null ) {
             return;
         }
-        String perm =
-                getPermissionFromPath( em.getApplicationRef().getUuid(), context.getAction().toString().toLowerCase(),
+        //this is breaking because there is no entity manager there.
+        String perm = getPermissionFromPath( em.getApplicationRef().getUuid(), context.getAction().toString().toLowerCase(),
                         path );
         boolean permitted = currentUser.isPermitted( perm );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/Service.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/Service.java b/stack/services/src/main/java/org/apache/usergrid/services/Service.java
index f463813..0a84dbf 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/Service.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/Service.java
@@ -47,4 +47,7 @@ public interface Service {
     public Entity writeEntity( ServiceRequest request, Entity entity ) throws Exception;
 
     public Entity updateEntity( ServiceRequest request, EntityRef ref, ServicePayload payload ) throws Exception;
+
+    ServiceContext getContext( ServiceAction action, ServiceRequest request, ServiceResults previousResults,
+                               ServicePayload payload ) throws Exception;
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/ServiceRequest.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/ServiceRequest.java b/stack/services/src/main/java/org/apache/usergrid/services/ServiceRequest.java
index 2c95465..f8a5abb 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/ServiceRequest.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/ServiceRequest.java
@@ -236,6 +236,11 @@ public class ServiceRequest {
         return sb.toString();
     }
 
+    public ServiceContext getAppContext() throws Exception {
+        Service s = services.getService( serviceName );
+
+        return s.getContext( action,this,null,payload );
+    }
 
     public ServiceResults execute( ServiceResults previousResults ) throws Exception {
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/99c75ccd/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java b/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
index cf4aa80..0eef711 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
@@ -32,6 +32,7 @@ import org.apache.usergrid.services.AbstractService;
 import org.apache.usergrid.services.ServiceContext;
 import org.apache.usergrid.services.ServiceParameter.QueryParameter;
 import org.apache.usergrid.services.ServicePayload;
+import org.apache.usergrid.services.ServiceRequest;
 import org.apache.usergrid.services.ServiceResults;
 import org.apache.usergrid.services.ServiceResults.Type;
 import org.apache.usergrid.services.exceptions.UnsupportedServiceOperationException;
@@ -95,8 +96,14 @@ public class ApplicationsService extends AbstractService {
 
 
     @Override
-    public ServiceResults postCollectionSchema( final ServiceContext context ) throws Exception {
-        throw new UnsupportedServiceOperationException( context );
+    public ServiceResults postCollectionSchema( final ServiceRequest request ) throws Exception {
+        throw new UnsupportedServiceOperationException( request );
+    }
+
+
+    @Override
+    public ServiceResults getCollectionSchema( final ServiceRequest serviceRequest ) throws Exception {
+        throw new UnsupportedServiceOperationException( serviceRequest );
     }
 
 


[23/36] usergrid git commit: Added the index schema cache to the index service.

Posted by gr...@apache.org.
Added the index schema cache to the index service.


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

Branch: refs/heads/release-2.1.1
Commit: 12a3be9d7c3b5d35c6ee243b06a8e4613835514d
Parents: 7e180af
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 17:02:30 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 17:02:30 2016 -0700

----------------------------------------------------------------------
 .../usergrid/corepersistence/CpEntityManager.java   | 16 +++++++++++++---
 .../usergrid/corepersistence/CpManagerCache.java    |  4 ++--
 .../usergrid/corepersistence/ManagerCache.java      |  3 ++-
 .../corepersistence/index/IndexServiceImpl.java     | 15 ++++++++++++++-
 4 files changed, 31 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/12a3be9d/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 d1f28be..751fd9a 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
@@ -1760,8 +1760,15 @@ public class CpEntityManager implements EntityManager {
 
         MapManager mm = getMapManagerForTypes();
 
-        //TODO: add a cache around
-        String jsonSchemaMap = mm.getString( collectionName );
+        IndexSchemaCache indexSchemaCache = managerCache.getIndexSchema( mm );
+
+        java.util.Optional<String> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
+
+        String jsonSchemaMap = null;
+
+        if(collectionIndexingSchema.isPresent()){
+            jsonSchemaMap = collectionIndexingSchema.get();
+        }
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
         if ( jsonSchemaMap != null ) {
@@ -1773,7 +1780,9 @@ public class CpEntityManager implements EntityManager {
         }
         schemaMap.putAll( properties );
 
+        //TODO: we have to update then invalidate previous entry.
         mm.putString( collectionName,JsonUtils.mapToJsonString( schemaMap ) );
+        indexSchemaCache.evictCollectionSchema( collectionName );
 
         return schemaMap;
 
@@ -1783,8 +1792,9 @@ public class CpEntityManager implements EntityManager {
     public Object getCollectionSchema( String collectionName ){
         MapManager mm = getMapManagerForTypes();
 
+        IndexSchemaCache indexSchemaCache = managerCache.getIndexSchema( mm );
 
-        java.util.Optional<String> collectionIndexingSchema =  managerCache.getIndexSchema( mm,collectionName );
+        java.util.Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
         if(collectionIndexingSchema.isPresent()){
             return JsonUtils.parse( collectionIndexingSchema.get() );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/12a3be9d/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
index dfbab00..e30de0f 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
@@ -106,8 +106,8 @@ public class CpManagerCache implements ManagerCache {
     //could be called an index schema manager.
 
     @Override
-    public Optional<String> getIndexSchema( MapManager mapManager, String collectionName ) {
-        return indexSchemaCacheFactory.getInstance( mapManager ).getCollectionSchema( collectionName );
+    public IndexSchemaCache getIndexSchema( MapManager mapManager ) {
+        return indexSchemaCacheFactory.getInstance( mapManager );
     }
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/12a3be9d/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
index e0a8257..c07930c 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
@@ -22,6 +22,7 @@ package org.apache.usergrid.corepersistence;
 
 import java.util.Optional;
 
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
 import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.graph.GraphManager;
@@ -68,7 +69,7 @@ public interface ManagerCache {
      */
     MapManager getMapManager(MapScope mapScope);
 
-    Optional<String> getIndexSchema( MapManager mapManager, String collectionName );
+    IndexSchemaCache getIndexSchema( MapManager mapManager );
 
     /**
      * gets index producer

http://git-wip-us.apache.org/repos/asf/usergrid/blob/12a3be9d/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index f3a3389..f931528 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -84,6 +84,7 @@ public class IndexServiceImpl implements IndexService {
     private final GraphManagerFactory graphManagerFactory;
     private final EntityIndexFactory entityIndexFactory;
     private final MapManagerFactory mapManagerFactory;
+    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
     private final EdgesObservable edgesObservable;
     private final IndexFig indexFig;
     private final IndexLocationStrategyFactory indexLocationStrategyFactory;
@@ -94,6 +95,7 @@ public class IndexServiceImpl implements IndexService {
     @Inject
     public IndexServiceImpl( final GraphManagerFactory graphManagerFactory, final EntityIndexFactory entityIndexFactory,
                              final MapManagerFactory mapManagerFactory,
+                             final IndexSchemaCacheFactory indexSchemaCacheFactory,
                              final EdgesObservable edgesObservable, final IndexFig indexFig,
                              final IndexLocationStrategyFactory indexLocationStrategyFactory,
                              final MetricsFactory metricsFactory ) {
@@ -103,6 +105,7 @@ public class IndexServiceImpl implements IndexService {
         this.edgesObservable = edgesObservable;
         this.indexFig = indexFig;
         this.indexLocationStrategyFactory = indexLocationStrategyFactory;
+        this.indexSchemaCacheFactory = indexSchemaCacheFactory;
         this.indexTimer = metricsFactory.getTimer( IndexServiceImpl.class, "index.update_all");
         this.addTimer = metricsFactory.getTimer( IndexServiceImpl.class, "index.add" );
     }
@@ -206,7 +209,17 @@ public class IndexServiceImpl implements IndexService {
         ArrayList fieldsToKeep;
 
         String collectionName = CpNamingUtils.getCollectionNameFromEdgeName( indexEdge.getEdgeName() );
-        String jsonSchemaMap = mm.getString( collectionName );
+
+        IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
+
+        Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
+
+
+        String jsonSchemaMap =  null;
+
+        if(collectionIndexingSchema.isPresent()){
+            jsonSchemaMap = collectionIndexingSchema.get();
+        }
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
         if ( jsonSchemaMap != null ) {


[30/36] usergrid git commit: Created a easier to understand algorithm that checks for top level indexing values. Passes existing tests.

Posted by gr...@apache.org.
Created a easier to understand algorithm that checks for top level indexing values. Passes existing tests.


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

Branch: refs/heads/release-2.1.1
Commit: c748368bd0dae90a0a88015478440105d36faf3a
Parents: 1736ce1
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 31 17:20:24 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 31 17:20:24 2016 -0700

----------------------------------------------------------------------
 .../index/impl/EntityToMapConverter.java        | 89 ++++++++++++++------
 1 file changed, 63 insertions(+), 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/c748368b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index e9a2075..259b421 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -109,7 +109,7 @@ public class EntityToMapConverter {
 
         final Set<EntityField> fieldsToBeFiltered =   parser.parse( entityMap );
 
-        //add our fields
+        //add our fields to output entity
         outputEntity.put( ENTITY_FIELDS, fieldsToBeFiltered );
 
         if(fieldsToIndex.isPresent()){
@@ -119,14 +119,15 @@ public class EntityToMapConverter {
             Iterator collectionIterator = mapFields.iterator();
 
             //Loop through all of the fields of the flatted entity and check to see if they should be filtered out.
-            while ( collectionIterator.hasNext() ) {
-                EntityField testedField = ( EntityField ) collectionIterator.next();
+            collectionIterator.forEachRemaining(outputEntityField -> {
+                EntityField testedField = ( EntityField ) outputEntityField;
                 String fieldName = ( String ) ( testedField ).get( "name" );
 
                 if ( !defaultProperties.contains( fieldName ) ) {
-                    iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
+                iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
                 }
-            }
+            });
+
         }
 
 
@@ -150,12 +151,15 @@ public class EntityToMapConverter {
         boolean toRemoveFlag = true;
         String[] flattedStringArray = getStrings( fieldName );
 
-        Iterator fieldIterator = fieldsToKeep.iterator(); //fieldsToKeep.iterator();
+        Iterator fieldIterator = fieldsToKeep.iterator();
+
+
 
         //goes through a loop of all the fields ( excluding default ) that we want to keep.
         //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to true and remove
         //the property.
         while ( fieldIterator.hasNext() ) {
+            //this is the field that we're
             String requiredInclusionString = ( String ) fieldIterator.next();
             String[] flattedRequirementString = getStrings( requiredInclusionString );
 
@@ -172,29 +176,62 @@ public class EntityToMapConverter {
             //Then if that check passes we go to check that both parts are equal. If they are ever not equal
             // e.g one.two.three and one.three.two then it shouldn't be included
             //TODO: regex.
-            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
-                //if the array contains a string that it is equals to then set the remove flag to true
-                //otherwise remain false.
-
-                //one.three
-                //one.two
-                //one
-                if ( flattedStringArray.length <= index ) {
-                    toRemoveFlag = true;
-                    break;
-                }
+            //The regex for this will need to be as follows
+            //Check to make sure that the strings match all the way and end with a period.
+
+            //so if the field we're evaluting against  is in the field name
+            //is one.two.three contains one.two
+            //if one.two is following by nothing or a period then it can be indexed.
+            if(fieldName.length() > requiredInclusionString.length()
+                && fieldName.contains( requiredInclusionString )
+                && fieldName.charAt( requiredInclusionString.length() )=='.' ) {
+                toRemoveFlag = false;
+                break;
+
+                //Since we know that the fieldName cannot be equal to the requiredInclusion criteria due to the if condition before we enter this method
+                //and we are certain that the indexing criteria is shorter we want to be sure that the inclusion criteria
+                //is contained within the field we're evaluating. i.e that one.two.three contains one.two
+
+                //The second part of the if loop also requires that the fieldName is followed by a period after we check to ensure that the
+                //indexing criteria is included in the string. This is done to weed out values such as one.twoexample.three
+                // when we should only keep one.two.three when comparing the indexing criteria of one.two.
+//                if(fieldName.contains( requiredInclusionString ) && fieldName.charAt( requiredInclusionString.length() )=='.'){
+//                    toRemoveFlag = false;
+//                    break;
+//                }
+//                toRemoveFlag = true;
 
-                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
-                    toRemoveFlag = false;
-                }
-                else {
-                    toRemoveFlag = true;
-                    break;
-                }
             }
-            if ( toRemoveFlag == false ) {
-                break;
+            else {
+                //the of the field we're evaluating is shorter than the indexing criteria so it can't match.
+                //Move onto the next field and see if they match.
+                toRemoveFlag = true;
             }
+
+
+//            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
+//                //if the array contains a string that it is equals to then set the remove flag to true
+//                //otherwise remain false.
+//
+//                //one.three
+//                //one.two
+//                //one
+//                if ( flattedStringArray.length <= index ) {
+//                    toRemoveFlag = true;
+//                    break;
+//                }
+//
+//                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
+//                    toRemoveFlag = false;
+//                }
+//                else {
+//                    toRemoveFlag = true;
+//                    break;
+//                }
+//            }
+//            if ( toRemoveFlag == false ) {
+//                break;
+//            }
         }
 
         if ( toRemoveFlag ) {


[13/36] usergrid git commit: Cleaned up reindexing test, and covered a case where reindexing wasn't properly filtering values.

Posted by gr...@apache.org.
Cleaned up reindexing test, and covered a case where reindexing wasn't properly filtering values.


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

Branch: refs/heads/release-2.1.1
Commit: 975616b0a13187d5c87b2eacc3266b27661ac904
Parents: aebfe1b
Author: George Reyes <gr...@apache.org>
Authored: Tue Mar 22 16:24:08 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:56 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 13 +++++-
 .../collection/CollectionsResourceIT.java       | 47 +++++++-------------
 2 files changed, 27 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/975616b0/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index a753dba..f8d7aa5 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -119,6 +119,9 @@ public class IndexServiceImpl implements IndexService {
         //we may have to index  we're indexing from source->target here
         final Observable<IndexEdge> sourceEdgesToIndex = edgesToTarget.map( edge -> generateScopeFromSource( edge ) );
 
+
+
+
         //do our observable for batching
         //try to send a whole batch if we can
         final Observable<IndexOperationMessage>  batches =  sourceEdgesToIndex
@@ -131,7 +134,15 @@ public class IndexServiceImpl implements IndexService {
                     if (logger.isDebugEnabled()) {
                         logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
                     }
-                    batch.index( indexEdge, entity );
+
+                    final Map map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
+
+                    if(map!=null){
+                        batch.index( indexEdge, entity ,map);
+                    }
+                    else{
+                        batch.index( indexEdge,entity );
+                    }
                 } )
                     //return the future from the batch execution
                 .map( batch -> batch.build() ) );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/975616b0/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 026f8a1..11a1878 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -128,22 +128,24 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
         //Create test collection with test entity that is full text indexed.
         Entity testEntity = new Entity();
-        testEntity.put( "one", "value" );
+        testEntity.put( "one", "value1" );
         //this field shouldn't persist after reindexing.
-        testEntity.put( "two","valuetwo" );
+        testEntity.put( "two","valuetwo1" );
 
-        //TODO: add arrays to the indexing test
-        //testEntity.put("array","array stuff here");
+        this.app().collection( "testCollection" ).post( testEntity );
+
+        testEntity.put( "one", "value2" );
+        //this field shouldn't persist after reindexing.
+        testEntity.put( "two","valuetwo2" );
+
+        this.app().collection( "testCollection" ).post( testEntity );
 
-        Entity returnedEntity = this.app().collection( "testCollection" ).post( testEntity );
 
         //Creating schema.
         //this could be changed to a hashmap.
         ArrayList<String> indexingArray = new ArrayList<>(  );
         indexingArray.add( "one" );
 
-        //TODO: add indexing array to the backend/test once you finish the regular selective indexing.
-        //indexingArray.add( "field.three.index.array" );
 
         //field "fields" is required.
         Entity payload = new Entity();
@@ -153,44 +155,25 @@ public class CollectionsResourceIT extends AbstractRestIT {
         Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
-        //Below is what needs to be implemented along with the index call above
-
-        //Get the collection schema and verify that it contains the same schema as posted above.
-//        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
-//
-//        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-//        //TODO: the below will have to be replaced by the values that I deem correct.
-//        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
-//        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-//        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
-//
-//        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
-//        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
-//        assertEquals( "one",schema.get( 0 ) );
-
         //Reindex and verify that the entity only has field one index.
         this.app().collection( "testCollection" ).collection( "_reindex" ).post();
+        Thread.sleep( 1000 );
+        refreshIndex();
 
-        String query = "one ='value'";
+        String query = "one ='value1'";
         QueryParameters queryParameters = new QueryParameters().setQuery(query);
 
         //having a name breaks it. Need to get rid of the stack trace and also
         Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
         Entity reindexedEntity = tempEntity.getResponse().getEntity();
-        assertEquals( "value",reindexedEntity.get( "one" ) );
+        assertEquals( "value1",reindexedEntity.get( "one" ) );
+        tempEntity=null;
 
         //Verify if you can query on an entity that was not indexed and that no entities are returned.
-        query = "two = 'valuetwo'";
+        query = "two = 'valuetwo1'";
         queryParameters = new QueryParameters().setQuery(query);
         tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
         assertEquals(0,tempEntity.getResponse().getEntities().size());
-
-//        refreshIndex();
-//
-//        Entity reindexedEntity = this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
-//        assertEquals( "12/31/9999",reindexedEntity.get( "one" ) );
-        //not sure if this should have some kind of sleep here because this reindex will be heavily throttled.
-
     }
 
     /**


[12/36] usergrid git commit: Unignored and fixed the test that verified reindexing. It now passes because I've added the reindexing functionality and proved it works. More tests to be added.

Posted by gr...@apache.org.
Unignored and fixed the test that verified reindexing. It now passes because I've added the reindexing functionality and proved it works. More tests to be added.


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

Branch: refs/heads/release-2.1.1
Commit: aebfe1b6db6f4855cb3cff4d371120161106e597
Parents: 2562e97
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 18 15:44:02 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:50 2016 -0700

----------------------------------------------------------------------
 .../rest/applications/CollectionResource.java   |  60 ++++++-
 .../collection/CollectionsResourceIT.java       | 156 ++++++++++++++++---
 2 files changed, 187 insertions(+), 29 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/aebfe1b6/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index b7f5f93..8b05a79 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -38,7 +38,11 @@ import org.springframework.stereotype.Component;
 
 import org.apache.commons.lang.StringUtils;
 
+import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilder;
+import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilderImpl;
+import org.apache.usergrid.corepersistence.index.ReIndexService;
 import org.apache.usergrid.persistence.Query;
+import org.apache.usergrid.persistence.index.utils.UUIDUtils;
 import org.apache.usergrid.rest.AbstractContextResource;
 import org.apache.usergrid.rest.ApiResponse;
 import org.apache.usergrid.rest.RootResource;
@@ -131,6 +135,30 @@ public class CollectionResource extends ServiceResource {
         return response;
     }
 
+    @POST
+    @Path("_reindex")
+    @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executePostForReindexing( @Context UriInfo ui, String body,
+                                             @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        System.out.println();
+//        logger.info( "Rebuilding collection {} in  application {}", collectionName, applicationIdStr );
+//
+//
+//
+//        final UUID appId = UUIDUtils.tryExtractUUID( applicationIdStr );
+//
+        //TODO: check to see how all of this runs with service and query params. Ideally none should be passed in.
+        final ReIndexRequestBuilder request =
+            createRequest().withApplicationId( services.getApplicationId() ).withCollection(
+                String.valueOf( getServiceParameters().get( 0 ) ) );
+//
+        return executeAndCreateResponse( request, callback );
+    }
+
     @Override
     @Path( RootResource.ENTITY_ID_PATH)
     public AbstractContextResource addIdParameter( @Context UriInfo ui, @PathParam("entityId") PathSegment entityId )
@@ -175,9 +203,33 @@ public class CollectionResource extends ServiceResource {
         return getSubResource( CollectionResource.class );
     }
 
-//    @
-//    public ServiceResource doLogicInServiceResource() throws Exception{
-//        return getSubResource( ServiceResource.class );
-//    }
+    private ReIndexService getReIndexService() {
+        return injector.getInstance( ReIndexService.class );
+    }
+
+    private ReIndexRequestBuilder createRequest() {
+        //TODO: wire this up through spring, and in the future guice.
+        return new ReIndexRequestBuilderImpl();
+    }
+
+    /**
+     * Execute the request and return the response.
+     */
+    private ApiResponse executeAndCreateResponse( final ReIndexRequestBuilder request, final String callback ) {
+
+
+        final ReIndexService.ReIndexStatus status = getReIndexService().rebuildIndex( request );
+
+        final ApiResponse response = createApiResponse();
+
+        response.setAction( "rebuild indexes" );
+        response.setProperty( "jobId", status.getJobId() );
+        response.setProperty( "status", status.getStatus() );
+        response.setProperty( "lastUpdatedEpoch", status.getLastUpdated() );
+        response.setProperty( "numberQueued", status.getNumberProcessed() );
+        response.setSuccess();
+
+        return response;
+    }
 
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/aebfe1b6/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 6d8a5e6..026f8a1 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -123,14 +123,14 @@ public class CollectionsResourceIT extends AbstractRestIT {
      *
      * @throws Exception
      */
-    @Ignore("The reindexing isn't currently supported yet.")
+    @Test
     public void postToCollectionSchemaUpdateExistingCollection() throws Exception {
 
         //Create test collection with test entity that is full text indexed.
         Entity testEntity = new Entity();
-        testEntity.put( "one", "12/31/9999" );
+        testEntity.put( "one", "value" );
         //this field shouldn't persist after reindexing.
-        testEntity.put( "two","2015-04-20T17:41:38.035Z" );
+        testEntity.put( "two","valuetwo" );
 
         //TODO: add arrays to the indexing test
         //testEntity.put("array","array stuff here");
@@ -156,26 +156,39 @@ public class CollectionsResourceIT extends AbstractRestIT {
         //Below is what needs to be implemented along with the index call above
 
         //Get the collection schema and verify that it contains the same schema as posted above.
-        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
-
-        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-        //TODO: the below will have to be replaced by the values that I deem correct.
-        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
-        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
-
-        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
-        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
-        assertEquals( "one",schema.get( 0 ) );
+//        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+//
+//        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+//        //TODO: the below will have to be replaced by the values that I deem correct.
+//        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
+//        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
+//        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
+//
+//        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
+//        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+//        assertEquals( "one",schema.get( 0 ) );
 
         //Reindex and verify that the entity only has field one index.
         this.app().collection( "testCollection" ).collection( "_reindex" ).post();
 
-        refreshIndex();
+        String query = "one ='value'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
 
-        Entity reindexedEntity = this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
-        assertEquals( "12/31/9999",reindexedEntity.get( "one" ) );
-        assertNull( reindexedEntity.get( "two" ) );
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "value",reindexedEntity.get( "one" ) );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "two = 'valuetwo'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+//        refreshIndex();
+//
+//        Entity reindexedEntity = this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
+//        assertEquals( "12/31/9999",reindexedEntity.get( "one" ) );
         //not sure if this should have some kind of sleep here because this reindex will be heavily throttled.
 
     }
@@ -318,12 +331,6 @@ public class CollectionsResourceIT extends AbstractRestIT {
         Entity reindexedEntity = tempEntity.getResponse().getEntity();
         assertEquals( "value2",((Map)reindexedEntity.get( "one" )).get( "anotherKey" ) );
 
-        //Verify if you can query on an entity that was not indexed and that no entities are returned.
-        //TODO: check that the below gets indexed as well. although the above should prove that at least one thing is getting indexed.
-//        query = "one.anotherKey = 'value2'";
-//        queryParameters = new QueryParameters().setQuery(query);
-//        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
-//        assertEquals(0,tempEntity.getResponse().getEntities().size());
 
     }
 
@@ -373,7 +380,6 @@ public class CollectionsResourceIT extends AbstractRestIT {
         assertEquals( "value2",((Map)reindexedEntity.get( "one" )).get( "anotherKey" ) );
 
         //Verify if you can query on an entity that was not indexed and that no entities are returned.
-        //TODO: check that the below gets indexed as well. although the above should prove that at least one thing is getting indexed.
         query = "one.anotherKey = 'value2'";
         queryParameters = new QueryParameters().setQuery(query);
         tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
@@ -382,6 +388,106 @@ public class CollectionsResourceIT extends AbstractRestIT {
     }
 
 
+    @Test
+    public void postToCollectionSchemaArrayWithSelectiveTopLevelIndexingAddingDefaultPropertyNames() throws Exception {
+
+        //Include the property labeled two to be index.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "two" );
+        //this should work such that one.key and one.anotherKey should work.
+        indexingArray.add( "one.key" );
+        indexingArray.add( "name" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        Map<String,Object> arrayFieldsForTestingSelectiveIndexing = new HashMap<>();
+
+        arrayFieldsForTestingSelectiveIndexing.put( "wowMoreKeys","value" );
+        arrayFieldsForTestingSelectiveIndexing.put( "thisShouldBeQueryableToo","value2");
+
+        Map<String,Object> arrayFieldsForTesting = new HashMap<>();
+
+        arrayFieldsForTesting.put( "key",arrayFieldsForTestingSelectiveIndexing );
+        arrayFieldsForTesting.put( "anotherKey","value2");
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", arrayFieldsForTesting );
+        testEntity.put( "two","query" );
+        testEntity.put( "name","howdy");
+
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "name = 'howdy'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "howdy",(reindexedEntity.get( "name" )) );
+
+    }
+
+
+    /**
+     * Verify that doing a put goes through and still applies the existing schema.
+     * @throws Exception
+     */
+    @Test
+    public void putToCollectionSchema() throws Exception {
+
+        //Include the property labeled two to be index.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "one" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", "two");
+        testEntity.put( "test", "anotherTest");
+
+        //Post entity.
+        Entity postedEntity = this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        testEntity.put( "one","three" );
+        this.app().collection( "testCollection" ).entity( postedEntity.getUuid() ).put( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "one = 'three'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "three",(reindexedEntity.get( "one" )) );
+
+        //check that the old value no longer exists in elasticsearch
+        query = "one = 'two'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+    }
+
+
 
 
     /**


[32/36] usergrid git commit: Added tests and code to cover the following cases: Somebody doesn't have a field array in the payload submitted to the index schema. Somebody submits something other than a JSON array to the "fields" field.

Posted by gr...@apache.org.
Added tests and code to cover the following cases: Somebody doesn't have a field array in the payload submitted to the index schema. Somebody submits something other than a JSON array to the "fields" field.


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

Branch: refs/heads/release-2.1.1
Commit: fc312bd8c168f395fe7a2982ef4c42c334fcfd13
Parents: 8beb3a5
Author: George Reyes <gr...@apache.org>
Authored: Fri Apr 1 12:28:31 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Fri Apr 1 12:28:31 2016 -0700

----------------------------------------------------------------------
 .../index/impl/EntityToMapConverter.java        |  5 ++-
 .../rest/applications/CollectionResource.java   | 16 ++++++++
 .../collection/CollectionsResourceIT.java       | 40 +++++++++++++++++++-
 3 files changed, 58 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/fc312bd8/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index a331c38..98a8ed5 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -123,8 +123,9 @@ public class EntityToMapConverter {
                 EntityField testedField = ( EntityField ) outputEntityField;
                 String fieldName = ( String ) ( testedField ).get( "name" );
 
+                //could move this down into the method below
                 if ( !defaultProperties.contains( fieldName ) ) {
-                iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
+                    iterateThroughMapForFieldsToBeIndexed( defaultProperties, collectionIterator, fieldName );
                 }
             });
 
@@ -142,7 +143,7 @@ public class EntityToMapConverter {
      * the map.
      *
      * @param fieldsToKeep - contains a list of fields that the user defined in their schema.
-     * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field.
+     * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field. Once removed here it is removed from the entity so it won't be indexed.
      * @param fieldName - contains the name of the field that we want to keep.
      */
     private static void iterateThroughMapForFieldsToBeIndexed( final Set<String> fieldsToKeep,

http://git-wip-us.apache.org/repos/asf/usergrid/blob/fc312bd8/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index c124f9d..5bd895c 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -18,6 +18,8 @@
 package org.apache.usergrid.rest.applications;
 
 
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
@@ -33,21 +35,25 @@ 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.springframework.context.annotation.Scope;
 import org.springframework.stereotype.Component;
 
+import org.apache.commons.lang.NullArgumentException;
 import org.apache.commons.lang.StringUtils;
 
 import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilder;
 import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilderImpl;
 import org.apache.usergrid.corepersistence.index.ReIndexService;
 import org.apache.usergrid.persistence.Query;
+import org.apache.usergrid.persistence.exceptions.RequiredPropertyNotFoundException;
 import org.apache.usergrid.persistence.index.utils.UUIDUtils;
 import org.apache.usergrid.rest.AbstractContextResource;
 import org.apache.usergrid.rest.ApiResponse;
 import org.apache.usergrid.rest.RootResource;
+import org.apache.usergrid.rest.exceptions.RequiredPropertyNotFoundExceptionMapper;
 import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
 import org.apache.usergrid.rest.security.annotations.RequireSystemAccess;
 import org.apache.usergrid.rest.system.IndexResource;
@@ -56,6 +62,7 @@ import org.apache.usergrid.services.ServiceAction;
 import org.apache.usergrid.services.ServiceParameter;
 import org.apache.usergrid.services.ServicePayload;
 
+import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.jaxrs.json.annotation.JSONP;
 
 
@@ -114,6 +121,15 @@ public class CollectionResource extends ServiceResource {
 
         ServicePayload payload = getPayload( json );
 
+        if(payload.getProperty( "fields" )==null){
+            throw new NullArgumentException( "fields" );
+        }
+
+        if(! (payload.getProperty( "fields" ) instanceof ArrayList)){
+            throw new NullArgumentException( "fields must be of json array type" );
+        }
+
+
         executeServicePostRequestForSchema( ui,response, ServiceAction.POST,payload );
 
         return response;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/fc312bd8/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index d814f55..e0b75ba 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -35,6 +35,7 @@ import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.ws.rs.BadRequestException;
 import javax.ws.rs.ClientErrorException;
 import java.io.IOException;
 import java.util.HashMap;
@@ -43,6 +44,8 @@ import java.util.Map;
 import java.util.Set;
 import java.util.ArrayList;
 
+import org.apache.commons.lang.NullArgumentException;
+
 import static org.junit.Assert.*;
 
 
@@ -195,8 +198,43 @@ public class CollectionsResourceIT extends AbstractRestIT {
     }
 
     @Test
-    public void putCollectionSchema() throws Exception {
+    public void verifyThatFieldsIsRequiredForCollectionSchema() throws Exception {
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fieldWeirdnessNotFields", indexingArray);
+
+        //Post index to the collection metadata
+        try {
+            this.app().collection( "testCollections" ).collection( "_indexes" ).post( payload );
+            fail();
+        }catch(BadRequestException bre){
+            //this is expected.
+        }
+
+        //ensure that it has to be an arraylist passed in.
+        Map indexingMap = new HashMap<>(  );
+        indexingMap.put( "exludeStuff","randomtext" );
 
+        payload = new Entity();
+        payload.put( "fields", indexingMap);
+
+        try {
+            this.app().collection( "testCollections" ).collection( "_indexes" ).post( payload );
+            fail();
+        }catch(BadRequestException bre){
+            //this is expected.
+        }
+
+        payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        try {
+            this.app().collection( "testCollections" ).collection( "_indexes" ).post( payload );
+        }catch(BadRequestException bre){
+            fail( "This shouldn't fail" );
+        }
 
     }
 


[34/36] usergrid git commit: Add some more comments and clarity to selective indexing.

Posted by gr...@apache.org.
Add some more comments and clarity to selective indexing.


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

Branch: refs/heads/release-2.1.1
Commit: 9f3720e998edd6343d78ec1b5360f1ce244a4d49
Parents: e5ae2a5
Author: George Reyes <gr...@apache.org>
Authored: Mon Apr 4 10:55:44 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Mon Apr 4 10:55:44 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        | 36 ++++++++------------
 .../index/ReIndexServiceImpl.java               |  1 -
 .../core/consistency/TimeServiceImpl.java       |  5 ++-
 .../index/impl/EntityToMapConverter.java        | 23 +++++++------
 4 files changed, 31 insertions(+), 34 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/9f3720e9/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 6bbf0a3..4ee497c 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
@@ -18,14 +18,11 @@ package org.apache.usergrid.corepersistence;
 
 import java.nio.ByteBuffer;
 import java.time.Instant;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -38,22 +35,15 @@ import java.util.TreeMap;
 import java.util.TreeSet;
 import java.util.UUID;
 
-
-import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
-import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
-import org.apache.usergrid.corepersistence.service.CollectionService;
-import org.apache.usergrid.corepersistence.service.ConnectionService;
-import org.apache.usergrid.persistence.index.EntityIndex;
-import org.apache.usergrid.utils.*;
-import org.apache.usergrid.utils.ClassUtils;
-import org.apache.usergrid.utils.UUIDUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.util.Assert;
 
-import org.apache.avro.generic.GenericData;
-
 import org.apache.usergrid.corepersistence.asyncevents.AsyncEventService;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
+import org.apache.usergrid.corepersistence.service.CollectionService;
+import org.apache.usergrid.corepersistence.service.ConnectionService;
 import org.apache.usergrid.corepersistence.util.CpEntityMapUtils;
 import org.apache.usergrid.corepersistence.util.CpNamingUtils;
 import org.apache.usergrid.persistence.AggregateCounter;
@@ -97,6 +87,7 @@ import org.apache.usergrid.persistence.exceptions.UnexpectedEntityTypeException;
 import org.apache.usergrid.persistence.graph.GraphManager;
 import org.apache.usergrid.persistence.graph.GraphManagerFactory;
 import org.apache.usergrid.persistence.graph.SearchEdgeType;
+import org.apache.usergrid.persistence.index.EntityIndex;
 import org.apache.usergrid.persistence.index.query.CounterResolution;
 import org.apache.usergrid.persistence.index.query.Identifier;
 import org.apache.usergrid.persistence.map.MapManager;
@@ -106,6 +97,13 @@ 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.utils.ClassUtils;
+import org.apache.usergrid.utils.CompositeUtils;
+import org.apache.usergrid.utils.InflectionUtils;
+import org.apache.usergrid.utils.Inflector;
+import org.apache.usergrid.utils.JsonUtils;
+import org.apache.usergrid.utils.StringUtils;
+import org.apache.usergrid.utils.UUIDUtils;
 
 import com.codahale.metrics.Meter;
 import com.codahale.metrics.Timer;
@@ -1751,17 +1749,14 @@ public class CpEntityManager implements EntityManager {
     @Override
     public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties ){
 
-        //haven't decided which one I should base off of which, maybe from epoch to utc
 
         //TODO: change timeservice as below then use timeservice.
-        //TODO: only allow a single reindex in elasticsearch at a time. akka.
         Instant timeInstance = Instant.now();
 
         Long epoch = timeInstance.toEpochMilli();
 
         Map<String,Object> schemaMap = new HashMap<>(  );
 
-
         schemaMap.put("lastUpdated",epoch);
         //this needs the method that can extract the user from the token no matter the token.
         //Possible values are app credentials, org credentials, or the user email(Admin tokens).
@@ -1775,7 +1770,7 @@ public class CpEntityManager implements EntityManager {
         java.util.Optional<Map> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
 
 
-        //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
+        //If there is an existing schema then take the lastReindexed time and keep it around.Otherwise initialize to 0.
         if ( collectionIndexingSchema.isPresent() ) {
             Map jsonMapData = collectionIndexingSchema.get();
             schemaMap.put( "lastReindexed", jsonMapData.get( "lastReindexed" ) );
@@ -1786,6 +1781,8 @@ public class CpEntityManager implements EntityManager {
 
         ArrayList<String> fieldProperties = ( ArrayList<String> ) properties.get( "fields" );
 
+        //do a check to see if you have a * field. If you do have a * field then ignore all other fields
+        //and only accept the * field.
         if(fieldProperties.contains( "*" )){
             ArrayList<String> wildCardArrayList = new ArrayList<>(  );
             wildCardArrayList.add( "*" );
@@ -1795,9 +1792,6 @@ public class CpEntityManager implements EntityManager {
             schemaMap.putAll( properties );
         }
 
-        //do a check to see if you have a * field. If you do have a * field then ignore all other fields
-        //and only accept the * field. That logic goes below and in the put.
-
         indexSchemaCache.putCollectionSchema( collectionName, JsonUtils.mapToJsonString( schemaMap ) );
 
         return schemaMap;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/9f3720e9/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 125222a..0aa0f60 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -44,7 +44,6 @@ import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapManagerFactory;
 import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.map.impl.MapScopeImpl;
-import org.apache.usergrid.persistence.model.entity.SimpleId;
 import org.apache.usergrid.persistence.model.util.UUIDGenerator;
 import org.apache.usergrid.utils.InflectionUtils;
 import org.apache.usergrid.utils.JsonUtils;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/9f3720e9/stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/consistency/TimeServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/consistency/TimeServiceImpl.java b/stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/consistency/TimeServiceImpl.java
index 00a58d3..99fe756 100644
--- a/stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/consistency/TimeServiceImpl.java
+++ b/stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/consistency/TimeServiceImpl.java
@@ -20,6 +20,9 @@
 package org.apache.usergrid.persistence.core.consistency;
 
 
+import java.time.Instant;
+
+
 /**
  * Simple time service to get the current system time.
  */
@@ -28,6 +31,6 @@ public class TimeServiceImpl implements TimeService{
 
     @Override
     public long getCurrentTime() {
-        return System.currentTimeMillis();
+        return Instant.now().toEpochMilli();
     }
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/9f3720e9/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 98a8ed5..8eb9f48 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -65,6 +65,7 @@ public class EntityToMapConverter {
      * @param applicationScope
      * @param entity The entity
      * @param indexEdge The edge this entity is indexed on
+     * @param fieldsToIndex A set of fields that will be indexed should they exist on the entity. Other fields will be filtered out.
      */
     public static Map<String, Object> convert(ApplicationScope applicationScope, final IndexEdge indexEdge,
                                               final Entity entity, Optional<Set<String>> fieldsToIndex) {
@@ -114,7 +115,6 @@ public class EntityToMapConverter {
 
         if(fieldsToIndex.isPresent()){
             Set<String> defaultProperties = fieldsToIndex.get();
-            //copy paste logic here.
             HashSet mapFields = ( HashSet ) outputEntity.get( "fields" );
             Iterator collectionIterator = mapFields.iterator();
 
@@ -137,10 +137,11 @@ public class EntityToMapConverter {
     }
 
     /**
-     * This method is crucial for selective top level indexing. Here we check to see if the flatted properties
-     * are in fact a top level exclusion e.g one.two.three and one.three.two can be allowed for querying by
-     * specifying one in the schema. If they are not a top level exclusion then they are removed from the iterator and
-     * the map.
+     * Handles checking to see if a field is a top level exclusion or just a field that shouldn't be indexed.
+     * This is handled by looping through all the fields we want to be able to query on, and checking to see if a
+     * specific field name is included. If the field name is included then do nothing. If the field name is not included
+     * then we do not want to be able to query on it. Instead we remove it from the collectionIterator which
+     * removes it from the outputEntity above, thus filtering it out.
      *
      * @param fieldsToKeep - contains a list of fields that the user defined in their schema.
      * @param collectionIterator - contains the iterator with the reference to the map where we want to remove the field. Once removed here it is removed from the entity so it won't be indexed.
@@ -154,12 +155,12 @@ public class EntityToMapConverter {
 
 
 
-        //goes through a loop of all the fields ( excluding default ) that we want to keep.
-        //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to true and remove
+        //goes through a loop of all the fields that we want to keep.
+        //if the toRemoveFlag is set to false then we want to keep the property and do nothing to it, otherwise we set it to true and remove
         //the property.
         while ( fieldIterator.hasNext() ) {
             //this is the field that we're
-            String requiredInclusionString = ( String ) fieldIterator.next();
+            String fieldToKeep = ( String ) fieldIterator.next();
 
 
             //Since we know that the fieldName cannot be equal to the requiredInclusion criteria due to the if condition before we enter this method
@@ -169,9 +170,9 @@ public class EntityToMapConverter {
             //The second part of the if loop also requires that the fieldName is followed by a period after we check to ensure that the
             //indexing criteria is included in the string. This is done to weed out values such as one.twoexample.three
             // when we should only keep one.two.three when comparing the indexing criteria of one.two.
-            if(fieldName.length() > requiredInclusionString.length()
-                && fieldName.contains( requiredInclusionString )
-                && fieldName.charAt( requiredInclusionString.length() )=='.' ) {
+            if(fieldName.length() > fieldToKeep.length()
+                && fieldName.contains( fieldToKeep )
+                && fieldName.charAt( fieldToKeep.length() )=='.' ) {
                 toRemoveFlag = false;
                 break;
             }


[29/36] usergrid git commit: Forced the indexing schema to store the map instead of the JSON string that way we only do the parsing once if we're doing a lot of get's on the schema.

Posted by gr...@apache.org.
Forced the indexing schema to store the map instead of the JSON string that way we only do the parsing once if we're doing a lot of get's on the schema.


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

Branch: refs/heads/release-2.1.1
Commit: 1736ce15762fa8d1e0341b8383890854b2c0a18e
Parents: 37eca05
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 31 16:38:16 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 31 16:38:16 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        | 17 +++++----------
 .../corepersistence/index/IndexSchemaCache.java |  3 ++-
 .../index/IndexSchemaCacheImpl.java             | 22 +++++++++++++-------
 .../corepersistence/index/IndexServiceImpl.java | 13 +++---------
 .../index/ReIndexServiceImpl.java               | 13 +++---------
 5 files changed, 28 insertions(+), 40 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/1736ce15/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 08204c9..6bbf0a3 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
@@ -1772,27 +1772,20 @@ public class CpEntityManager implements EntityManager {
 
         IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
 
-        java.util.Optional<String> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
+        java.util.Optional<Map> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
 
-        String jsonSchemaMap = null;
-
-        if(collectionIndexingSchema.isPresent()){
-            jsonSchemaMap = collectionIndexingSchema.get();
-        }
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
-        if ( jsonSchemaMap != null ) {
-            Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+        if ( collectionIndexingSchema.isPresent() ) {
+            Map jsonMapData = collectionIndexingSchema.get();
             schemaMap.put( "lastReindexed", jsonMapData.get( "lastReindexed" ) );
         }
         else {
             schemaMap.put( "lastReindexed", 0 );
         }
 
-
         ArrayList<String> fieldProperties = ( ArrayList<String> ) properties.get( "fields" );
 
-        //TODO: do tests for * , and now add put and delete.
         if(fieldProperties.contains( "*" )){
             ArrayList<String> wildCardArrayList = new ArrayList<>(  );
             wildCardArrayList.add( "*" );
@@ -1828,10 +1821,10 @@ public class CpEntityManager implements EntityManager {
 
         IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm ); //managerCache.getIndexSchema( mm );
 
-        java.util.Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
+        java.util.Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
         if(collectionIndexingSchema.isPresent()){
-            return JsonUtils.parse( collectionIndexingSchema.get() );
+            return collectionIndexingSchema.get();
         }
         else{
             return null;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1736ce15/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
index debfe2a..a56ffd6 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
@@ -17,6 +17,7 @@
 package org.apache.usergrid.corepersistence.index;
 
 
+import java.util.Map;
 import java.util.Optional;
 
 
@@ -27,7 +28,7 @@ public interface IndexSchemaCache {
      * @param collectionName
      * @return
      */
-    public Optional<String> getCollectionSchema(String collectionName);
+    public Optional<Map> getCollectionSchema( String collectionName );
 
     void putCollectionSchema( String collectionName, String collectionSchema );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1736ce15/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
index 14752b4..3df31cc 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -18,12 +18,14 @@
 package org.apache.usergrid.corepersistence.index;
 
 
+import java.util.Map;
 import java.util.Optional;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.utils.JsonUtils;
 
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
@@ -39,7 +41,7 @@ import com.google.inject.Singleton;
 public class IndexSchemaCacheImpl implements IndexSchemaCache {
     private static final Logger logger = LoggerFactory.getLogger(IndexSchemaCacheImpl.class );
 
-    private final LoadingCache<String,Optional<String>> indexSchemaCache;
+    private final LoadingCache<String,Optional<Map>> indexSchemaCache;
     private final MapManager mapManager;
 
 
@@ -48,23 +50,29 @@ public class IndexSchemaCacheImpl implements IndexSchemaCache {
         indexSchemaCache = CacheBuilder.newBuilder()
             .maximumSize( indexSchemaCacheFig.getCacheSize() )
             //.expireAfterWrite( indexSchemaCacheFig.getCacheTimeout(), TimeUnit.MILLISECONDS ) <-- I don't think we want this to expire that quickly.
-            .build( new CacheLoader<String, Optional<String>>() {
+            .build( new CacheLoader<String, Optional<Map>>() {
                 @Override
-                public Optional<String> load( final String collectionName ) throws Exception {
+                public Optional<Map> load( final String collectionName ) throws Exception {
                     return Optional.ofNullable( retrieveCollectionSchema( collectionName ) );
                 }
             } );
     }
 
-    private String retrieveCollectionSchema( final String collectionName ){
-        return mapManager.getString( collectionName );
+    private Map retrieveCollectionSchema( final String collectionName ){
+        String collectionIndexingSchema = mapManager.getString( collectionName );
+        Map parsedCollectionIndexingSchema = null;
+        if(collectionIndexingSchema!=null){
+            return (Map) JsonUtils.parse( collectionIndexingSchema );
+
+        }
+        return parsedCollectionIndexingSchema;
     }
 
 
     @Override
-    public Optional<String> getCollectionSchema( final String collectionName ) {
+    public Optional<Map> getCollectionSchema( final String collectionName ) {
         try {
-            Optional<String> optionalCollectionSchema = indexSchemaCache.get( collectionName );
+            Optional<Map> optionalCollectionSchema = indexSchemaCache.get( collectionName );
             if(!optionalCollectionSchema.isPresent()){
                 indexSchemaCache.invalidate( collectionName );
                 return Optional.empty();

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1736ce15/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 9e05df3..c81c4ef 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -212,19 +212,12 @@ public class IndexServiceImpl implements IndexService {
 
         IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
 
-        Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
-
-
-        String jsonSchemaMap =  null;
-
-        if(collectionIndexingSchema.isPresent()){
-            jsonSchemaMap = collectionIndexingSchema.get();
-        }
+        Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
         //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
-        if ( jsonSchemaMap != null ) {
+        if ( collectionIndexingSchema.isPresent()) {
 
-            Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+            Map jsonMapData = collectionIndexingSchema.get();
             Schema schema = Schema.getDefaultSchema();
             defaultProperties = schema.getRequiredProperties( collectionName );
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1736ce15/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 591fcd6..125222a 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -142,19 +142,12 @@ public class ReIndexServiceImpl implements ReIndexService {
             MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
             IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( collectionMapStorage );
 
-            java.util.Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
-
-
-            String jsonSchemaMap =  null;
-
-            if(collectionIndexingSchema.isPresent()){
-                jsonSchemaMap = collectionIndexingSchema.get();
-            }
+            java.util.Optional<Map> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 
             //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
-            if ( jsonSchemaMap != null ) {
+            if ( collectionIndexingSchema.isPresent() ) {
 
-                Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+                Map jsonMapData = collectionIndexingSchema.get();
 
                 jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
                 //should probably roll this into the cache.


[36/36] usergrid git commit: Merge branch 'selectiveIndexingCherryPicked' into release-2.1.1

Posted by gr...@apache.org.
Merge branch 'selectiveIndexingCherryPicked' into release-2.1.1

* selectiveIndexingCherryPicked: (33 commits)
  Removed all instance of java.util.Optional from selective indexing.
  Add some more comments and clarity to selective indexing.
  Added tests and code to cover the following cases: Somebody doesn't have a field array in the payload submitted to the index schema. Somebody submits something other than a JSON array to the "fields" field.
  Cleaned up the old code that used to do the filtering.
  Created a easier to understand algorithm that checks for top level indexing values. Passes existing tests.
  Forced the indexing schema to store the map instead of the JSON string that way we only do the parsing once if we're doing a lot of get's on the schema.
  Added a way to use the existing reindex code to reindex the collection rather than copying and pasting the reindex code.
  Added a delete test and a delete endpoint so that we can delete schema's
  Added a put that will automatically invalidate the cache.
  Removed the index schema cache from the manager cache as it can and should stand alone.
  Added the index schema cache to the index service.
  Added first instances of using a cache for access index schema values
  Removed all unused imports in cpRelationManager and IndexServiceImpl and EsEntityIndexBatchImpl. Re-added final keyword to indexing interface
  Changed the seemingly not working delay to 50 millisecond , moved the collection reindexing timer updating code to be easier to follow.
  Cleaning up the left over code from the endeavor.
  Simplified the CollectionResource and remove recursive call based on serviceResource wonkiness
  Working lower level selective indexing. Working field updates when we do reindexing and stuff. Added test proving that it works.
  Comments with changes to make to selective indexing. Changes to reindexing to add a delay given the reindexing call.
  Commented out the delay because it broke tests. Cleaned up some commented out code and spaces.
  Cleaned up the updating test to verify that a collection of 10 will be indexed.
  ...


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

Branch: refs/heads/release-2.1.1
Commit: 74de4bca3a6c74b1a8491b9bc093cda9e9b26add
Parents: 29d7660 d751ac1
Author: George Reyes <gr...@apache.org>
Authored: Fri Apr 8 13:20:27 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Fri Apr 8 13:20:27 2016 -0700

----------------------------------------------------------------------
 .../main/resources/usergrid-default.properties  |   3 -
 .../usergrid/corepersistence/CoreModule.java    |   6 +
 .../corepersistence/CpEntityManager.java        | 111 +++-
 .../corepersistence/CpEntityManagerFactory.java |   8 +-
 .../corepersistence/CpManagerCache.java         |   2 +-
 .../corepersistence/CpRelationManager.java      |   5 -
 .../usergrid/corepersistence/ManagerCache.java  |   2 +-
 .../asyncevents/EventBuilderImpl.java           |   1 -
 .../corepersistence/index/IndexSchemaCache.java |  50 ++
 .../index/IndexSchemaCacheFactory.java          |  44 ++
 .../index/IndexSchemaCacheFig.java              |  39 ++
 .../index/IndexSchemaCacheImpl.java             | 119 ++++
 .../corepersistence/index/IndexServiceImpl.java |  94 ++-
 .../index/ReIndexRequestBuilder.java            |   7 +
 .../index/ReIndexRequestBuilderImpl.java        |  32 +
 .../index/ReIndexServiceImpl.java               |  39 +-
 .../usergrid/persistence/EntityManager.java     |   7 +
 .../persistence/cassandra/ApplicationCF.java    |   2 +-
 .../impl/EntityCollectionManagerImpl.java       |   2 +-
 .../core/consistency/TimeServiceImpl.java       |   5 +-
 .../persistence/map/impl/MapManagerImpl.java    |   6 +
 .../persistence/index/EntityIndexBatch.java     |  13 +-
 .../index/impl/EntityToMapConverter.java        |  93 ++-
 .../index/impl/EsEntityIndexBatchImpl.java      |  21 +-
 .../persistence/index/impl/IndexOperation.java  |   9 +-
 .../persistence/index/impl/EntityIndexTest.java |   2 +-
 .../org/apache/usergrid/rest/ApiResponse.java   |   7 +-
 .../rest/applications/ApplicationResource.java  |   2 +-
 .../rest/applications/CollectionResource.java   | 233 +++++++
 .../rest/applications/ServiceResource.java      | 111 +++-
 .../usergrid/rest/system/IndexResource.java     |   6 +
 .../collection/CollectionsResourceIT.java       | 622 ++++++++++++++++++-
 .../test/resource/endpoints/NamedResource.java  |  22 +
 .../services/AbstractCollectionService.java     |  39 ++
 .../services/AbstractConnectionsService.java    |  13 +
 .../usergrid/services/AbstractService.java      |  11 +-
 .../org/apache/usergrid/services/Service.java   |   3 +
 .../usergrid/services/ServiceManager.java       |   1 -
 .../usergrid/services/ServiceRequest.java       |   5 +
 .../applications/ApplicationsService.java       |  14 +
 40 files changed, 1738 insertions(+), 73 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/74de4bca/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
----------------------------------------------------------------------


[18/36] usergrid git commit: Simplified the CollectionResource and remove recursive call based on serviceResource wonkiness

Posted by gr...@apache.org.
Simplified the CollectionResource and remove recursive call based on serviceResource wonkiness


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

Branch: refs/heads/release-2.1.1
Commit: 0e53dcf118c71a7d9e496f62372ade25ca9a597d
Parents: b5d81ac
Author: George Reyes <gr...@apache.org>
Authored: Tue Mar 29 15:46:44 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Tue Mar 29 15:46:44 2016 -0700

----------------------------------------------------------------------
 .../rest/applications/CollectionResource.java   | 82 ++++++++------------
 1 file changed, 31 insertions(+), 51 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/0e53dcf1/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index fb660fa..8f4bdf0 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -82,12 +82,13 @@ public class CollectionResource extends ServiceResource {
      * @throws Exception
      */
     @POST
-    @Path("_indexes")
+    @Path( "{itemName}/_indexes" )
     @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
     @RequireApplicationAccess
     @JSONP
-    public ApiResponse executePostOnIndexes( @Context UriInfo ui, String body,
-                                             @QueryParam("callback") @DefaultValue("callback") String callback )
+    public ApiResponse executePostOnIndexesWithCollectionName( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName,
+                                                               String body,
+                                                               @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
         if(logger.isTraceEnabled()){
@@ -96,6 +97,7 @@ public class CollectionResource extends ServiceResource {
         /**
 
          */
+        addItemToServiceContext( ui, itemName );
 
         Object json;
         if ( StringUtils.isEmpty( body ) ) {
@@ -117,12 +119,29 @@ public class CollectionResource extends ServiceResource {
         return response;
     }
 
+
+    private void addItemToServiceContext( final @Context UriInfo ui,
+                                          final @PathParam( "itemName" ) PathSegment itemName ) throws Exception {
+        if ( itemName.getPath().startsWith( "{" ) ) {
+            Query query = Query.fromJsonString( itemName.getPath() );
+            if ( query != null ) {
+                ServiceParameter.addParameter( getServiceParameters(), query );
+            }
+        }
+        else {
+            ServiceParameter.addParameter( getServiceParameters(), itemName.getPath() );
+        }
+
+        addMatrixParams( getServiceParameters(), ui, itemName );
+    }
+
+
     @GET
-    @Path("_index")
+    @Path( "{itemName}/_index")
     @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
     @RequireApplicationAccess
     @JSONP
-    public ApiResponse executeGetOnIndex( @Context UriInfo ui,
+    public ApiResponse executeGetOnIndex( @Context UriInfo ui,@PathParam("itemName") PathSegment itemName,
                                           @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
@@ -130,6 +149,8 @@ public class CollectionResource extends ServiceResource {
             logger.trace( "CollectionResource.executeGetOnIndex" );
         }
 
+        addItemToServiceContext( ui, itemName );
+
         ApiResponse response = createApiResponse();
         response.setAction( "get" );
         response.setApplication( services.getApplication() );
@@ -140,17 +161,21 @@ public class CollectionResource extends ServiceResource {
         return response;
     }
 
+
     //TODO: this can't be controlled and until it can be controlled we should allow muggles to do this. So system access only.
     //TODO: use scheduler here to get around people sending a reindex call 30 times.
     @POST
-    @Path("_reindex")
+    @Path("{itemName}/_reindex")
     @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
     @RequireSystemAccess
     @JSONP
     public ApiResponse executePostForReindexing( @Context UriInfo ui, String body,
+                                                 @PathParam("itemName") PathSegment itemName,
                                              @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
+        addItemToServiceContext( ui, itemName );
+
         final ReIndexRequestBuilder request =
             createRequest().withApplicationId( services.getApplicationId() ).withCollection(
                 String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 1, TimeUnit.SECONDS );
@@ -158,51 +183,6 @@ public class CollectionResource extends ServiceResource {
         return executeAndCreateResponse( request, callback );
     }
 
-    @Override
-    @Path( RootResource.ENTITY_ID_PATH)
-    public AbstractContextResource addIdParameter( @Context UriInfo ui, @PathParam("entityId") PathSegment entityId )
-        throws Exception {
-
-        if(logger.isTraceEnabled()){
-            logger.trace( "ServiceResource.addIdParameter" );
-        }
-
-        UUID itemId = UUID.fromString( entityId.getPath() );
-
-        ServiceParameter.addParameter( getServiceParameters(), itemId );
-
-        addMatrixParams( getServiceParameters(), ui, entityId );
-
-        return getSubResource( CollectionResource.class );
-    }
-
-
-    //TODO: change this to {itemName}/_indexes and that should do what we already have. Then we don't have this overriden method.
-    @Override
-    @Path("{itemName}")
-    public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName )
-        throws Exception {
-        if(logger.isTraceEnabled()){
-            logger.trace( "ServiceResource.addNameParameter" );
-            logger.trace( "Current segment is {}", itemName.getPath() );
-        }
-
-
-        if ( itemName.getPath().startsWith( "{" ) ) {
-            Query query = Query.fromJsonString( itemName.getPath() );
-            if ( query != null ) {
-                ServiceParameter.addParameter( getServiceParameters(), query );
-            }
-        }
-        else {
-            ServiceParameter.addParameter( getServiceParameters(), itemName.getPath() );
-        }
-
-        addMatrixParams( getServiceParameters(), ui, itemName );
-
-        return getSubResource( CollectionResource.class );
-    }
-
     private ReIndexService getReIndexService() {
         return injector.getInstance( ReIndexService.class );
     }


[20/36] usergrid git commit: Changed the seemingly not working delay to 50 millisecond , moved the collection reindexing timer updating code to be easier to follow.

Posted by gr...@apache.org.
Changed the seemingly not working delay to 50 millisecond , moved the collection reindexing timer updating code to be easier to follow.


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

Branch: refs/heads/release-2.1.1
Commit: 899e4646f8990188840d7361fd37522abf1daf62
Parents: 0feeebb
Author: George Reyes <gr...@apache.org>
Authored: Tue Mar 29 16:43:02 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Tue Mar 29 16:43:02 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  2 --
 .../index/ReIndexServiceImpl.java               | 27 +++++++++++---------
 .../rest/applications/CollectionResource.java   |  2 +-
 3 files changed, 16 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/899e4646/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 2c97bc6..78e52ef 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
@@ -2737,8 +2737,6 @@ public class CpEntityManager implements EntityManager {
         // add to and index in collection of the application
         if ( !is_application ) {
 
-            //maybe a check here to see if it exists in the column family and if it doesn't then SEND IT ON THROUGHH
-
             String collectionName = Schema.defaultCollectionName( eType );
             CpRelationManager cpr = ( CpRelationManager ) getRelationManager( getApplication() );
             cpr.addToCollection( collectionName, entity );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/899e4646/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 42067f5..22ec9d9 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -138,24 +138,27 @@ public class ReIndexServiceImpl implements ReIndexService {
             reIndexRequestBuilder.getCollectionName(), cursorSeek.getSeekValue() )
             .buffer( indexProcessorFig.getReindexBufferSize());
 
-        if(delayTimer.isPresent()){
+        //Check to see if we have a selective indexing schema, if we do then update its reindexing time, otherwise
+        //don't update or create anything.
+        if(reIndexRequestBuilder.getCollectionName().isPresent()) {
+            String collectionName =  InflectionUtils.pluralize( CpNamingUtils.getNameFromEdgeType(reIndexRequestBuilder.getCollectionName().get() ));
+            MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
+            String jsonSchemaMap = collectionMapStorage.getString( collectionName );
+
 
-            if(reIndexRequestBuilder.getCollectionName().isPresent()) {
-                String collectionName =  InflectionUtils.pluralize( CpNamingUtils.getNameFromEdgeType(reIndexRequestBuilder.getCollectionName().get() ));
-                MapManager collectionMapStorage = mapManagerFactory.createMapManager( CpNamingUtils.getEntityTypeMapScope( appId.get().getApplication()  ) );
-                String jsonSchemaMap = collectionMapStorage.getString( collectionName );
+            //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
+            if ( jsonSchemaMap != null ) {
 
+                Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
 
-                //If we do have a schema then parse it and add it to a list of properties we want to keep.Otherwise return.
-                if ( jsonSchemaMap != null ) {
+                jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
+                collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
+            }
 
-                    Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
+        }
 
-                    jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
-                    collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
-                }
+        if(delayTimer.isPresent()){
 
-            }
             if(timeUnitOptional.isPresent()){
                 runningReIndex = runningReIndex.delay( delayTimer.get(),timeUnitOptional.get() );
             }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/899e4646/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index 8f4bdf0..80ed36b 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -178,7 +178,7 @@ public class CollectionResource extends ServiceResource {
 
         final ReIndexRequestBuilder request =
             createRequest().withApplicationId( services.getApplicationId() ).withCollection(
-                String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 1, TimeUnit.SECONDS );
+                String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 50, TimeUnit.MILLISECONDS );
 
         return executeAndCreateResponse( request, callback );
     }


[10/36] usergrid git commit: Added some helper methods and fixed the iterator by adding the correct removal.

Posted by gr...@apache.org.
Added some helper methods and fixed the iterator by adding the correct removal.


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

Branch: refs/heads/release-2.1.1
Commit: 859d6bfd3c189279fb750eb68502f75ed96d49bc
Parents: 1491264
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 18 11:13:36 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:38 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 150 ++++++++++++-------
 1 file changed, 100 insertions(+), 50 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/859d6bfd/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 6722dbe..74776ac 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -221,7 +221,6 @@ public class IndexServiceImpl implements IndexService {
 
         if(defaultProperties!=null) {
             final Set<String> finalDefaultProperties = defaultProperties;
-            //the iterator is based off of this valu
             Iterator collectionIterator = mapFields.iterator();
 
             //TODO:I think there is a bug when we modify it and continue iterating then it fails
@@ -233,19 +232,54 @@ public class IndexServiceImpl implements IndexService {
                 //will only enter the loop for properties that aren't default properties so we only need to check
                 //the properties that the user imposed.
                 if ( !finalDefaultProperties.contains( fieldName ) ) {
-                    innerLoop( fieldsToKeep, mapFields, testedField, fieldName );
+                    boolean toRemoveFlag = true;
+                    String[] flattedStringArray = getStrings( fieldName );
+
+                    Iterator fieldIterator = fieldsToKeep.iterator();
+
+                    //goes through a loop of all the fields ( excluding default ) that we want to keep.
+                    //if the toRemoveFlag is set to false then we want to keep the property, otherwise we set it to false
+                    while(fieldIterator.hasNext()) {
+                        String requiredInclusionString = ( String ) fieldIterator.next();
+                        String[] flattedRequirementString = getStrings( requiredInclusionString );
+
+
+                        //loop each split array value to see if it matches an equivalent value
+                        //in the field.
+                        for ( int index = 0; index < flattedRequirementString.length;index++){
+                            //if the array contains a string that it is equals to then set the remove flag to true
+                            //otherwise remain false.
+
+                            if(flattedStringArray.length <= index){
+                                toRemoveFlag = true;
+                                break;
+                            }
+                            //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
+                            if(flattedRequirementString[index].equals( flattedStringArray[index] )){
+                                toRemoveFlag=false;
+                            }
+                            else{
+                                toRemoveFlag=true;
+                            }
+                        }
+                        if(toRemoveFlag==false){
+                            break;
+                        }
+                    }
+
+                    if(toRemoveFlag){
+                        collectionIterator.remove();
+                        //mapFields.remove( testedField );
+                    }
                 }
             }
         }
         return map;
     }
+    
 
-
-    private void innerLoop( final ArrayList fieldsToKeep, final HashSet mapFields, final EntityField testedField,
-                            final String fieldName ) {//loop through and string split it all and if they still dont' match after that loop then remove them.
-        boolean toRemoveFlag = true;
-        String[] flattedStringArray = null;
-
+    private String[] getStrings( final String fieldName ) {
+        final String[] flattedStringArray;
         if(!fieldName.contains( "." )){
             //create a single array that is made of a the single value.
             flattedStringArray = new String[]{fieldName};
@@ -253,50 +287,66 @@ public class IndexServiceImpl implements IndexService {
         else {
             flattedStringArray= fieldName.split( "\\." );
         }
+        return flattedStringArray;
+    }
 
-        Iterator fieldIterator = fieldsToKeep.iterator();
-
-        //goes through a loop of all the fields ( excluding default ) that we want to query on
-        while(fieldIterator.hasNext()) {
-            String requiredInclusionString = ( String ) fieldIterator.next();
-            String[] flattedRequirementString;
-
-            //in the case you only have a filter that is a single field.Otherwise split it.
-            if(!requiredInclusionString.contains( "." )){
-                flattedRequirementString = new String[]{requiredInclusionString};
-            }
-            else {
-                 flattedRequirementString= requiredInclusionString.split( "\\." );
-            }
-
-
-            //loop each split array value to see if it matches an equivalent value
-            //in the field.
-            for ( int index = 0; index < flattedRequirementString.length;index++){
-                //if the array contains a string that it is equals to then set the remove flag to true
-                //otherwise remain false.
-
-                if(flattedStringArray.length <= index){
-                    toRemoveFlag = true;
-                    break;
-                }
-                //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
-                if(flattedRequirementString[index].equals( flattedStringArray[index] )){
-                    toRemoveFlag=false;
-                }
-                else{
-                    toRemoveFlag=true;
-                }
-            }
-            if(toRemoveFlag==false){
-                break;
-            }
-        }
 
-        if(toRemoveFlag){
-            mapFields.remove( testedField );
-        }
-    }
+    //    private void innerLoop( final ArrayList fieldsToKeep, final HashSet mapFields, final EntityField testedField,
+//                            final String fieldName ) {//loop through and string split it all and if they still dont' match after that loop then remove them.
+//        boolean toRemoveFlag = true;
+//        String[] flattedStringArray = null;
+//
+//        if(!fieldName.contains( "." )){
+//            //create a single array that is made of a the single value.
+//            flattedStringArray = new String[]{fieldName};
+//        }
+//        else {
+//            flattedStringArray= fieldName.split( "\\." );
+//        }
+//
+//        Iterator fieldIterator = fieldsToKeep.iterator();
+//
+//        //goes through a loop of all the fields ( excluding default ) that we want to query on
+//        while(fieldIterator.hasNext()) {
+//            String requiredInclusionString = ( String ) fieldIterator.next();
+//            String[] flattedRequirementString;
+//
+//            //in the case you only have a filter that is a single field.Otherwise split it.
+//            if(!requiredInclusionString.contains( "." )){
+//                flattedRequirementString = new String[]{requiredInclusionString};
+//            }
+//            else {
+//                 flattedRequirementString= requiredInclusionString.split( "\\." );
+//            }
+//
+//
+//            //loop each split array value to see if it matches an equivalent value
+//            //in the field.
+//            for ( int index = 0; index < flattedRequirementString.length;index++){
+//                //if the array contains a string that it is equals to then set the remove flag to true
+//                //otherwise remain false.
+//
+//                if(flattedStringArray.length <= index){
+//                    toRemoveFlag = true;
+//                    break;
+//                }
+//                //this has a condition issue where if we evaluate that it passes on the first pass, we dont' want to continue the while lo
+//                if(flattedRequirementString[index].equals( flattedStringArray[index] )){
+//                    toRemoveFlag=false;
+//                }
+//                else{
+//                    toRemoveFlag=true;
+//                }
+//            }
+//            if(toRemoveFlag==false){
+//                break;
+//            }
+//        }
+//
+//        if(toRemoveFlag){
+//            mapFields.remove( testedField );
+//        }
+//    }
 
 
     //Steps to delete an IndexEdge.


[27/36] usergrid git commit: Added a delete test and a delete endpoint so that we can delete schema's

Posted by gr...@apache.org.
Added a delete test and a delete endpoint so that we can delete schema's


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

Branch: refs/heads/release-2.1.1
Commit: 956a6f5a552d2b627b0ac0547d40beed9712d416
Parents: f4769e6
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 31 12:53:45 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 31 12:53:45 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        |  33 ++++-
 .../corepersistence/index/IndexSchemaCache.java |   2 +
 .../index/IndexSchemaCacheImpl.java             |   7 +-
 .../corepersistence/index/IndexServiceImpl.java |   4 +
 .../usergrid/persistence/EntityManager.java     |   2 +
 .../rest/applications/CollectionResource.java   |  35 ++++-
 .../collection/CollectionsResourceIT.java       | 142 +++++++++++++++++++
 7 files changed, 217 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/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 642b837..08204c9 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
@@ -51,6 +51,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.util.Assert;
 
+import org.apache.avro.generic.GenericData;
+
 import org.apache.usergrid.corepersistence.asyncevents.AsyncEventService;
 import org.apache.usergrid.corepersistence.util.CpEntityMapUtils;
 import org.apache.usergrid.corepersistence.util.CpNamingUtils;
@@ -1786,16 +1788,41 @@ public class CpEntityManager implements EntityManager {
         else {
             schemaMap.put( "lastReindexed", 0 );
         }
-        schemaMap.putAll( properties );
 
-        //TODO: we have to update then invalidate previous entry.
+
+        ArrayList<String> fieldProperties = ( ArrayList<String> ) properties.get( "fields" );
+
+        //TODO: do tests for * , and now add put and delete.
+        if(fieldProperties.contains( "*" )){
+            ArrayList<String> wildCardArrayList = new ArrayList<>(  );
+            wildCardArrayList.add( "*" );
+            schemaMap.put( "fields",wildCardArrayList );
+        }
+        else {
+            schemaMap.putAll( properties );
+        }
+
+        //do a check to see if you have a * field. If you do have a * field then ignore all other fields
+        //and only accept the * field. That logic goes below and in the put.
+
         indexSchemaCache.putCollectionSchema( collectionName, JsonUtils.mapToJsonString( schemaMap ) );
-        
+
         return schemaMap;
 
     }
 
     @Override
+    public void deleteCollectionSchema( String collectionName ){
+        MapManager mm = getMapManagerForTypes();
+
+        IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
+
+        indexSchemaCache.deleteCollectionSchema( collectionName );
+
+    }
+
+
+    @Override
     public Object getCollectionSchema( String collectionName ){
         MapManager mm = getMapManagerForTypes();
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
index 6fbe148..debfe2a 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
@@ -31,6 +31,8 @@ public interface IndexSchemaCache {
 
     void putCollectionSchema( String collectionName, String collectionSchema );
 
+    void deleteCollectionSchema( String collectionName );
+
     /**
      * Evict the collection schema from the cache.
      * @param collectionName

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
index 9e57480..14752b4 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -80,11 +80,16 @@ public class IndexSchemaCacheImpl implements IndexSchemaCache {
     }
 
     @Override
-    public void putCollectionSchema(final String collectionName ,final String collectionSchema){
+    public void putCollectionSchema( final String collectionName, final String collectionSchema ){
         mapManager.putString( collectionName, collectionSchema );
         evictCollectionSchema( collectionName );
     }
 
+    @Override
+    public void deleteCollectionSchema(final String collectionName){
+        mapManager.delete( collectionName );
+        evictCollectionSchema( collectionName );
+    }
 
     @Override
     public void evictCollectionSchema( final String collectionName ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index f931528..9e05df3 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -229,6 +229,10 @@ public class IndexServiceImpl implements IndexService {
             defaultProperties = schema.getRequiredProperties( collectionName );
             fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
 
+            if(fieldsToKeep.contains( "*" )){
+                return Optional.empty();
+            }
+
             defaultProperties.addAll( fieldsToKeep );
         }
         else {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/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 f5b398a..ef96f10 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
@@ -514,6 +514,8 @@ public interface EntityManager {
 
     public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties );
 
+    void deleteCollectionSchema( String collectionName );
+
     Object getCollectionSchema( String collectionName );
 
     public void grantRolePermission( String roleName, String permission ) throws Exception;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index 80ed36b..b097469 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -21,6 +21,7 @@ package org.apache.usergrid.rest.applications;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
+import javax.ws.rs.DELETE;
 import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
@@ -94,9 +95,7 @@ public class CollectionResource extends ServiceResource {
         if(logger.isTraceEnabled()){
             logger.trace( "ServiceResource.executePostOnIndexes" );
         }
-        /**
 
-         */
         addItemToServiceContext( ui, itemName );
 
         Object json;
@@ -119,7 +118,6 @@ public class CollectionResource extends ServiceResource {
         return response;
     }
 
-
     private void addItemToServiceContext( final @Context UriInfo ui,
                                           final @PathParam( "itemName" ) PathSegment itemName ) throws Exception {
         if ( itemName.getPath().startsWith( "{" ) ) {
@@ -135,6 +133,35 @@ public class CollectionResource extends ServiceResource {
         addMatrixParams( getServiceParameters(), ui, itemName );
     }
 
+    @DELETE
+    @Path( "{itemName}/_indexes" )
+    @Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executeDeleteOnIndexesWithCollectionName( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName,
+                                                               String body,
+                                                               @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "CollectionResource.executeDeleteOnIndexesWithCollectionName" );
+        }
+
+        addItemToServiceContext( ui, itemName );
+
+        ApiResponse response = createApiResponse();
+
+        response.setAction( "delete" );
+        response.setApplication( services.getApplication() );
+        response.setParams( ui.getQueryParameters() );
+
+
+        emf.getEntityManager( services.getApplicationId() ).deleteCollectionSchema( itemName.getPath().toLowerCase() );
+
+        return response;
+    }
+
+
 
     @GET
     @Path( "{itemName}/_index")
@@ -162,7 +189,7 @@ public class CollectionResource extends ServiceResource {
     }
 
 
-    //TODO: this can't be controlled and until it can be controlled we should allow muggles to do this. So system access only.
+    //TODO: this can't be controlled and until it can be controlled we shouldn' allow muggles to do this. So system access only.
     //TODO: use scheduler here to get around people sending a reindex call 30 times.
     @POST
     @Path("{itemName}/_reindex")

http://git-wip-us.apache.org/repos/asf/usergrid/blob/956a6f5a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 04ed18e..8ec4a3a 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -115,6 +115,148 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
     }
 
+    @Test
+    public void deleteCollectionSchema() throws Exception {
+        //Creating schema.
+        //this could be changed to a hashmap.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        Entity thing = this.app().collection( "testCollections" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+
+        //The above verifies the test case.
+
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", "helper" );
+        testEntity.put( "two","query" );
+
+        //Post entity.
+        Entity postedEntity = this.app().collection( "testCollections" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "two ='query'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals( 0,tempEntity.getResponse().getEntities().size() );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "one = 'helper'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+        query = "uuid = "+postedEntity.getUuid().toString();
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals(1,tempEntity.getResponse().getEntities().size());
+
+        //since the collection schema doesn't index anything it shouldn't show up except for the default properties
+        //to prove that the entity exists
+
+        //next part is to delete the schema then reindex it and it should work.
+        this.app().collection( "testCollections" ).collection( "_indexes" ).delete();
+        refreshIndex();
+
+        this.app().collection( "testCollections" ).collection( "_reindex" ).post(true,clientSetup.getSuperuserToken(),ApiResponse.class,null,null,false);
+        refreshIndex();
+
+
+        //Do a query to see if you can find the indexed query.
+        query = "two ='query'";
+        queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals( 1,tempEntity.getResponse().getEntities().size() );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "one = 'helper'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals(1,tempEntity.getResponse().getEntities().size());
+
+        query = "uuid = "+postedEntity.getUuid().toString();
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollections" ).get(queryParameters,true);
+        assertEquals(1,tempEntity.getResponse().getEntities().size());
+
+    }
+
+    @Test
+    public void putCollectionSchema() throws Exception {
+
+
+    }
+
+
+    @Test
+    public void postCollectionSchemaWithWildcardIndexAll() throws Exception {
+        //Creating schema.
+        //this could be changed to a hashmap.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "*" );
+        indexingArray.add( "one" );
+        indexingArray.add( "two" );
+
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+
+        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
+
+        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
+        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
+        assertTrue( schema.contains( "*" ) );
+        assertFalse( schema.contains( "one" ) );
+        assertFalse( schema.contains( "two" ) );
+
+
+//The above verifies the test case.
+
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", "helper" );
+        testEntity.put( "two","query" );
+
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "two ='query'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "helper",reindexedEntity.get( "one" ) );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "one = 'helper'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(1,tempEntity.getResponse().getEntities().size());
+    }
+
 
     /**
      * Create test collection


[05/36] usergrid git commit: Cleaned up the test

Posted by gr...@apache.org.
Cleaned up the test


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

Branch: refs/heads/release-2.1.1
Commit: 3c98c2ddefc799924d4069b6010eac4e561a69b2
Parents: aa7f776
Author: George Reyes <gr...@apache.org>
Authored: Fri Mar 11 16:25:25 2016 -0800
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:09:32 2016 -0700

----------------------------------------------------------------------
 .../collection/CollectionsResourceIT.java       | 62 +++++---------------
 1 file changed, 15 insertions(+), 47 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/3c98c2dd/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 1aa91d1..2e4a3ff 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -192,73 +192,41 @@ public class CollectionsResourceIT extends AbstractRestIT {
     @Test
     public void postToCollectionSchemaWithSchemaFirst() throws Exception {
 
-
-
-        //Creating schema.
-        //this could be changed to a hashmap.
+        //Include the property labeled two to be index.
         ArrayList<String> indexingArray = new ArrayList<>(  );
-        indexingArray.add( "one" );
-        indexingArray.add( "name" );
-
-        //TODO: add indexing array to the backend/test once you finish the regular selective indexing.
-        //indexingArray.add( "field.three.index.array" );
+        indexingArray.add( "two" );
 
         //field "fields" is required.
         Entity payload = new Entity();
         payload.put( "fields", indexingArray);
 
         //Post index to the collection metadata
-       // Entity thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
-        //Create test collection with test entity that is full text indexed.
+        //Create test collection with a test entity that is partially indexed.
         Entity testEntity = new Entity();
-        //testEntity.put( "name", "tester");
         testEntity.put( "one", "helper" );
-        //this field shouldn't persist after reindexing.
         testEntity.put( "two","query" );
 
-        //TODO: add arrays to the indexing test
-        //testEntity.put("array","array stuff here");
-
-        Entity returnedEntity = this.app().collection( "testCollection" ).post( testEntity );
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
         refreshIndex();
-        //testEntity.put( "three","notthree" );
-        //ApiResponse updatedEntity = this.app().collection( "testCollection" ).put( null,testEntity );
-
-        //Below is what needs to be implemented along with the index call above
-
-//        //Get the collection schema and verify that it contains the same schema as posted above.
-//        Collection collection = this.app().collection( "testCollection" ).collection( "_index" ).get();
-//
-//        LinkedHashMap testCollectionSchema = (LinkedHashMap)collection.getResponse().getData();
-//        //TODO: the below will have to be replaced by the values that I deem correct.
-//        assertEquals( ( thing ).get( "lastUpdated" ), testCollectionSchema.get( "lastUpdated" ));
-//        assertEquals( ( thing ).get( "lastUpdateBy" ),testCollectionSchema.get( "lastUpdateBy" ) );
-//        assertEquals( ( thing ).get( "lastReindexed" ),testCollectionSchema.get( "lastReindexed" ) );
-
-//        //TODO: this test doesn't check to see if create checks the schema. Only that the reindex removes whats already there.
-//        ArrayList<String> schema = ( ArrayList<String> ) testCollectionSchema.get( "fields" );
-//        assertEquals( "one",schema.get( 0 ) );
-
-        //Reindex and verify that the entity only has field one index.
-//        this.app().collection( "testCollection" ).collection( "_reindex" ).post();
-//
-//        refreshIndex();
-
-        //this needs to be a query. not a graph. This should still return the full entity.
 
+        //Do a query to see if you can find the indexed query.
         String query = "two ='query'";
         QueryParameters queryParameters = new QueryParameters().setQuery(query);
 
-//having a name breaks it. Need to get rid of the stack trace and also
+        //having a name breaks it. Need to get rid of the stack trace and also
         Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
-
-
-        Entity reindexedEntity = tempEntity.getResponse().getEntity(); //this.app().collection( "testCollection" ).entity( returnedEntity.getUuid() ).get();
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
         assertEquals( "helper",reindexedEntity.get( "one" ) );
-        assertNull( reindexedEntity.get( "two" ) );
-        //not sure if this should have some kind of sleep here because this reindex will be heavily throttled.
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "one = 'helper'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
 
     }
 


[26/36] usergrid git commit: Added a put that will automatically invalidate the cache.

Posted by gr...@apache.org.
Added a put that will automatically invalidate the cache.


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

Branch: refs/heads/release-2.1.1
Commit: f4769e6b526059fc328f71d60f0985425a254b3b
Parents: 78bba1a
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 17:36:36 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 17:36:36 2016 -0700

----------------------------------------------------------------------
 .../org/apache/usergrid/corepersistence/CpEntityManager.java   | 5 ++---
 .../usergrid/corepersistence/index/IndexSchemaCache.java       | 3 ++-
 .../usergrid/corepersistence/index/IndexSchemaCacheImpl.java   | 6 ++++++
 .../usergrid/corepersistence/index/ReIndexServiceImpl.java     | 3 +--
 4 files changed, 11 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/f4769e6b/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 968d91d..642b837 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
@@ -1789,9 +1789,8 @@ public class CpEntityManager implements EntityManager {
         schemaMap.putAll( properties );
 
         //TODO: we have to update then invalidate previous entry.
-        mm.putString( collectionName,JsonUtils.mapToJsonString( schemaMap ) );
-        indexSchemaCache.evictCollectionSchema( collectionName );
-
+        indexSchemaCache.putCollectionSchema( collectionName, JsonUtils.mapToJsonString( schemaMap ) );
+        
         return schemaMap;
 
     }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f4769e6b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
index 5a9e95d..6fbe148 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCache.java
@@ -17,7 +17,6 @@
 package org.apache.usergrid.corepersistence.index;
 
 
-import java.util.Map;
 import java.util.Optional;
 
 
@@ -30,6 +29,8 @@ public interface IndexSchemaCache {
      */
     public Optional<String> getCollectionSchema(String collectionName);
 
+    void putCollectionSchema( String collectionName, String collectionSchema );
+
     /**
      * Evict the collection schema from the cache.
      * @param collectionName

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f4769e6b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
index 90c07bf..9e57480 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -79,6 +79,12 @@ public class IndexSchemaCacheImpl implements IndexSchemaCache {
         return null;
     }
 
+    @Override
+    public void putCollectionSchema(final String collectionName ,final String collectionSchema){
+        mapManager.putString( collectionName, collectionSchema );
+        evictCollectionSchema( collectionName );
+    }
+
 
     @Override
     public void evictCollectionSchema( final String collectionName ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f4769e6b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 559e117..591fcd6 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -158,8 +158,7 @@ public class ReIndexServiceImpl implements ReIndexService {
 
                 jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
                 //should probably roll this into the cache.
-                collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
-                indexSchemaCache.evictCollectionSchema( collectionName );
+                indexSchemaCache.putCollectionSchema( collectionName, JsonUtils.mapToJsonString(jsonMapData ) );
             }
 
         }


[25/36] usergrid git commit: Removed the index schema cache from the manager cache as it can and should stand alone.

Posted by gr...@apache.org.
Removed the index schema cache from the manager cache as it can and should stand alone.


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

Branch: refs/heads/release-2.1.1
Commit: 78bba1a7917ea85e88bcdf965f13505187260ff4
Parents: 0aa241d
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 17:20:53 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 17:20:53 2016 -0700

----------------------------------------------------------------------
 .../usergrid/corepersistence/CpEntityManager.java |  9 +++++++--
 .../corepersistence/CpEntityManagerFactory.java   |  4 +++-
 .../usergrid/corepersistence/CpManagerCache.java  | 18 ------------------
 .../usergrid/corepersistence/ManagerCache.java    |  2 --
 .../index/IndexSchemaCacheImpl.java               |  6 ++----
 .../corepersistence/index/ReIndexServiceImpl.java |  2 ++
 6 files changed, 14 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/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 e39a584..968d91d 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
@@ -40,6 +40,7 @@ import java.util.UUID;
 
 
 import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
+import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
 import org.apache.usergrid.corepersistence.service.CollectionService;
 import org.apache.usergrid.corepersistence.service.ConnectionService;
 import org.apache.usergrid.persistence.index.EntityIndex;
@@ -185,6 +186,8 @@ public class CpEntityManager implements EntityManager {
 
     private final ManagerCache managerCache;
 
+    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
+
     private final ApplicationScope applicationScope;
 
     private final CassandraService cass;
@@ -246,6 +249,7 @@ public class CpEntityManager implements EntityManager {
                             final GraphManagerFactory graphManagerFactory,
                             final CollectionService collectionService,
                             final ConnectionService connectionService,
+                            final IndexSchemaCacheFactory indexSchemaCacheFactory,
                             final UUID applicationId ) {
 
         this.entityManagerFig = entityManagerFig;
@@ -269,6 +273,7 @@ public class CpEntityManager implements EntityManager {
         this.managerCache = managerCache;
         this.applicationId = applicationId;
         this.indexService = indexService;
+        this.indexSchemaCacheFactory = indexSchemaCacheFactory;
 
         applicationScope = CpNamingUtils.getApplicationScope( applicationId );
 
@@ -1763,7 +1768,7 @@ public class CpEntityManager implements EntityManager {
 
         MapManager mm = getMapManagerForTypes();
 
-        IndexSchemaCache indexSchemaCache = managerCache.getIndexSchema( mm );
+        IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm );
 
         java.util.Optional<String> collectionIndexingSchema = indexSchemaCache.getCollectionSchema( collectionName );
 
@@ -1795,7 +1800,7 @@ public class CpEntityManager implements EntityManager {
     public Object getCollectionSchema( String collectionName ){
         MapManager mm = getMapManagerForTypes();
 
-        IndexSchemaCache indexSchemaCache = managerCache.getIndexSchema( mm );
+        IndexSchemaCache indexSchemaCache = indexSchemaCacheFactory.getInstance( mm ); //managerCache.getIndexSchema( mm );
 
         java.util.Optional<String> collectionIndexingSchema =  indexSchemaCache.getCollectionSchema( collectionName );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/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 047947e..a2054d9 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
@@ -125,6 +125,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
     private final CollectionService collectionService;
     private final ConnectionService connectionService;
     private final GraphManagerFactory graphManagerFactory;
+    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
 
     public CpEntityManagerFactory( final CassandraService cassandraService, final CounterUtils counterUtils,
                                    final Injector injector ) {
@@ -140,6 +141,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
         this.graphManagerFactory = injector.getInstance( GraphManagerFactory.class );
         this.collectionService = injector.getInstance( CollectionService.class );
         this.connectionService = injector.getInstance( ConnectionService.class );
+        this.indexSchemaCacheFactory = injector.getInstance( IndexSchemaCacheFactory.class );
 
         //this line always needs to be last due to the temporary cicular dependency until spring is removed
 
@@ -201,7 +203,7 @@ public class CpEntityManagerFactory implements EntityManagerFactory, Application
 
     private EntityManager _getEntityManager( UUID applicationId ) {
         EntityManager em = new CpEntityManager(cassandraService, counterUtils, indexService, managerCache,
-            metricsFactory, entityManagerFig, graphManagerFactory,  collectionService, connectionService, applicationId );
+            metricsFactory, entityManagerFig, graphManagerFactory,  collectionService, connectionService,indexSchemaCacheFactory, applicationId );
 
         return em;
     }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
index e30de0f..4e1f5e3 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpManagerCache.java
@@ -16,20 +16,13 @@
 package org.apache.usergrid.corepersistence;
 
 
-import java.util.Optional;
-
-import org.safehaus.guicyfig.Overrides;
-
 import org.apache.usergrid.corepersistence.index.IndexLocationStrategyFactory;
-import org.apache.usergrid.corepersistence.index.IndexSchemaCache;
-import org.apache.usergrid.corepersistence.index.IndexSchemaCacheFactory;
 import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 import org.apache.usergrid.persistence.collection.EntityCollectionManagerFactory;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.graph.GraphManager;
 import org.apache.usergrid.persistence.graph.GraphManagerFactory;
 import org.apache.usergrid.persistence.index.EntityIndex;
-import org.apache.usergrid.persistence.index.EntityIndex;
 import org.apache.usergrid.persistence.index.EntityIndexFactory;
 import org.apache.usergrid.persistence.index.IndexLocationStrategy;
 import org.apache.usergrid.persistence.index.impl.IndexProducer;
@@ -50,7 +43,6 @@ public class CpManagerCache implements ManagerCache {
     private final EntityIndexFactory eif;
     private final GraphManagerFactory gmf;
     private final MapManagerFactory mmf;
-    private final IndexSchemaCacheFactory indexSchemaCacheFactory;
     private final IndexLocationStrategyFactory indexLocationStrategyFactory;
     private final IndexProducer indexProducer;
 
@@ -62,7 +54,6 @@ public class CpManagerCache implements ManagerCache {
                            final EntityIndexFactory eif,
                            final GraphManagerFactory gmf,
                            final MapManagerFactory mmf,
-                           final IndexSchemaCacheFactory indexSchemaCacheFactory,
                            final IndexLocationStrategyFactory indexLocationStrategyFactory,
                            final IndexProducer indexProducer
     ) {
@@ -71,7 +62,6 @@ public class CpManagerCache implements ManagerCache {
         this.eif = eif;
         this.gmf = gmf;
         this.mmf = mmf;
-        this.indexSchemaCacheFactory = indexSchemaCacheFactory;
         this.indexLocationStrategyFactory = indexLocationStrategyFactory;
         this.indexProducer = indexProducer;
     }
@@ -103,14 +93,6 @@ public class CpManagerCache implements ManagerCache {
         return mmf.createMapManager( mapScope );
     }
 
-    //could be called an index schema manager.
-
-    @Override
-    public IndexSchemaCache getIndexSchema( MapManager mapManager ) {
-        return indexSchemaCacheFactory.getInstance( mapManager );
-    }
-
-
     @Override
     public IndexProducer getIndexProducer() {
         return indexProducer;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
index c07930c..ebfd5a4 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/ManagerCache.java
@@ -69,8 +69,6 @@ public interface ManagerCache {
      */
     MapManager getMapManager(MapScope mapScope);
 
-    IndexSchemaCache getIndexSchema( MapManager mapManager );
-
     /**
      * gets index producer
      * @return

http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
index d818ce0..90c07bf 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexSchemaCacheImpl.java
@@ -18,26 +18,24 @@
 package org.apache.usergrid.corepersistence.index;
 
 
-import java.util.Map;
 import java.util.Optional;
-import java.util.concurrent.TimeUnit;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.usergrid.corepersistence.ManagerCache;
 import org.apache.usergrid.persistence.map.MapManager;
-import org.apache.usergrid.utils.JsonUtils;
 
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
+import com.google.inject.Singleton;
 
 
 /**
  * Cache the calls to update and get the map manager so we don't overload cassandra when we update
  * after each call?
  */
+@Singleton
 public class IndexSchemaCacheImpl implements IndexSchemaCache {
     private static final Logger logger = LoggerFactory.getLogger(IndexSchemaCacheImpl.class );
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/78bba1a7/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index 1b68712..559e117 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -157,7 +157,9 @@ public class ReIndexServiceImpl implements ReIndexService {
                 Map jsonMapData = ( Map ) JsonUtils.parse( jsonSchemaMap );
 
                 jsonMapData.put( "lastReindexed", Instant.now().toEpochMilli() );
+                //should probably roll this into the cache.
                 collectionMapStorage.putString( collectionName,JsonUtils.mapToJsonString(jsonMapData )  );
+                indexSchemaCache.evictCollectionSchema( collectionName );
             }
 
         }


[07/36] usergrid git commit: no message

Posted by gr...@apache.org.
no message


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

Branch: refs/heads/release-2.1.1
Commit: f0480b4881a097e50ad2153e735268834b40dbb9
Parents: a2ec1df
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 16 11:38:10 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:14:15 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/index/IndexServiceImpl.java | 101 +++++++++++--------
 .../persistence/index/EntityIndexBatch.java     |   3 +
 .../index/impl/EntityToMapConverter.java        |   7 ++
 .../index/impl/EsEntityIndexBatchImpl.java      |  27 ++++-
 .../persistence/index/impl/IndexOperation.java  |  19 +++-
 .../collection/CollectionsResourceIT.java       | 101 ++++++++++++++++++-
 6 files changed, 213 insertions(+), 45 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index 01bc516..9e0e799 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -22,6 +22,7 @@ package org.apache.usergrid.corepersistence.index;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
@@ -30,6 +31,8 @@ import java.util.concurrent.TimeUnit;
 
 import org.apache.usergrid.persistence.Schema;
 import org.apache.usergrid.persistence.index.*;
+import org.apache.usergrid.persistence.index.impl.EntityField;
+import org.apache.usergrid.persistence.index.impl.IndexOperation;
 import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.map.MapManagerFactory;
 import org.apache.usergrid.persistence.map.MapScope;
@@ -158,65 +161,83 @@ public class IndexServiceImpl implements IndexService {
 
             final EntityIndexBatch batch = ei.createBatch();
 
-           // if (logger.isDebugEnabled()) {
+            if (logger.isDebugEnabled()) {
                 logger.debug("adding edge {} to batch for entity {}", indexEdge, entity);
-           // }
+            }
 
+            Map<String, Object> map = getFilteredStringObjectMap( applicationScope, entity, indexEdge );
 
-                indexEdge.getNodeId().getUuid();
+            if(map!=null){
+                batch.index( indexEdge, entity ,map);
+            }
+            else{
+                batch.index( indexEdge,entity );
+            }
 
-                //System.out.println("hello");
 
-                Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
+            return batch.build();
+        } );
 
-                final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
+        return ObservableTimer.time( batches, addTimer  );
 
-                MapManager mm = mapManagerFactory.createMapManager( ms );
 
+    }
 
 
-                String jsonMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
+    private Map<String, Object> getFilteredStringObjectMap( final ApplicationScope applicationScope, final Entity entity,
+                                                    final IndexEdge indexEdge ) {IndexOperation indexOperation = new IndexOperation(  );
 
-                Set<String> defaultProperties = null;
 
-                if(jsonMap != null) {
+        indexEdge.getNodeId().getUuid();
 
-                    Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
-                    Schema schema = Schema.getDefaultSchema();
-                    defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
-                    //TODO: additional logic to
-                    ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
-                    defaultProperties.addAll( fieldsToKeep );
+        Id mapOwner = new SimpleId( indexEdge.getNodeId().getUuid(), TYPE_APPLICATION );
 
-                }
+        final MapScope ms = CpNamingUtils.getEntityTypeMapScope(mapOwner );
 
-            Entity filteredEntity = new Entity( entity.getId(),entity.getVersion() );
-            filteredEntity.setFieldMap( entity.getFieldMap() );
-
-                Collection<String> trimmedFields = null;
-                if(defaultProperties!=null) {
-                    // if(cpHeadEntity.getFields())
-                    final Set<String> finalDefaultProperties = defaultProperties;
-                    trimmedFields = entity.getFieldMap().keySet();
-                    Iterator collectionIterator = trimmedFields.iterator();
-                    while ( collectionIterator.hasNext() ) {
-                        String fieldName = ( String ) collectionIterator.next();
-                        if ( !finalDefaultProperties.contains( fieldName ) ) {
-                            //collectionIterator.remove();
-                            filteredEntity.removeField( fieldName );
-                        }
-                    }
-                }
+        MapManager mm = mapManagerFactory.createMapManager( ms );
 
+        String jsonMap = mm.getString( indexEdge.getEdgeName().split( "\\|" )[1] );
 
-            batch.index( indexEdge, filteredEntity );
-
-            return batch.build();
-        } );
-
-        return ObservableTimer.time( batches, addTimer  );
+        Set<String> defaultProperties = null;
 
+        if(jsonMap != null) {
 
+            Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
+            Schema schema = Schema.getDefaultSchema();
+            defaultProperties = schema.getRequiredProperties( indexEdge.getEdgeName().split( "\\|" )[1]);
+            //TODO: additional logic to
+            ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
+            defaultProperties.addAll( fieldsToKeep );
+        }
+        else
+            return null;
+
+        Map<String, Object> map = indexOperation.convertedEntityToBeIndexed( applicationScope,indexEdge,entity );
+        HashSet mapFields = ( HashSet ) map.get( "fields" );
+
+        if(defaultProperties!=null) {
+            final Set<String> finalDefaultProperties = defaultProperties;
+            Iterator collectionIterator = mapFields.iterator();
+            while ( collectionIterator.hasNext() ) {
+                EntityField testedField = ( EntityField ) collectionIterator.next();
+                String fieldName = ( String ) (testedField).get( "name" );
+                //TODO: need to change the logic here such that default properties does a check against each every field.
+                //it is very likely that the below does O(n) comparisons anyways so doing it for each value in a loop
+                //would be the right equivalent here. Even if it isn't very efficient.
+                //maybe if it was a hashmap, and if the hashmap didn't contain the value then we remove the field.
+                //but now for each hash value we have to do a check to see it doesn't start with a certain value.
+                //making this an O(n) operation anyways.
+
+                //so for each value in the finalDefaultProperties check to see if it matches the current property
+                //then if it doesn't do a split of the properties and see if any of them match for the split
+                //if they do match then allow in, otherwise don't allow.
+
+                if ( !finalDefaultProperties.contains( fieldName ) ) {
+                    mapFields.remove( testedField );
+                }
+            }
+        }
+        return map;
     }
 
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
index 17dd4d3..e3a40f6 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
@@ -19,6 +19,7 @@ package org.apache.usergrid.persistence.index;/*
 
 
 import java.util.List;
+import java.util.Map;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.index.impl.IndexOperationMessage;
@@ -53,6 +54,8 @@ public interface EntityIndexBatch {
      */
     EntityIndexBatch deindex( final SearchEdge searchEdge, final CandidateResult result );
 
+    EntityIndexBatch index( IndexEdge indexEdge, Entity entity, Map flattenedEntityMap );
+
     /**
      * Remove index of entity.
      *

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index d0a5c44..77a8d92 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -17,16 +17,22 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.index.IndexEdge;
+import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.EntityMap;
 import org.apache.usergrid.persistence.model.entity.Id;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
 
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.APPLICATION_ID_FIELDNAME;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.EDGE_NAME_FIELDNAME;
@@ -45,6 +51,7 @@ import static org.apache.usergrid.persistence.index.impl.IndexingUtils.getType;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.nodeId;
 
 
+
 /**
  * Convert a CP entity to an elasticsearch document
  */

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
index f703e32..5296978 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
@@ -19,6 +19,7 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
+import java.util.Map;
 import java.util.UUID;
 
 import org.apache.usergrid.persistence.index.*;
@@ -31,6 +32,7 @@ import org.apache.usergrid.persistence.index.utils.IndexValidationUtils;
 import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
 
 
 public class EsEntityIndexBatchImpl implements EntityIndexBatch {
@@ -69,16 +71,35 @@ public class EsEntityIndexBatchImpl implements EntityIndexBatch {
 
         final String writeAlias = alias.getWriteAlias();
 
-        //if ( logger.isDebugEnabled() ) {
-            logger.info( "Indexing to alias {} with scope {} on edge {} with entity data {}",
+        if ( logger.isDebugEnabled() ) {
+            logger.debug( "Indexing to alias {} with scope {} on edge {} with entity data {}",
                     writeAlias, applicationScope, indexEdge, entity.getFieldMap().keySet() );
-        //}
+        }
 
         //add app id for indexing
         container.addIndexRequest(new IndexOperation(writeAlias, applicationScope, indexEdge, entity));
         return this;
     }
 
+    @Override
+    public EntityIndexBatch index ( final IndexEdge indexEdge, final Entity entity ,final Map flattenedEntityMap){
+        IndexValidationUtils.validateIndexEdge(indexEdge);
+        ValidationUtils.verifyEntityWrite(entity);
+        ValidationUtils.verifyVersion( entity.getVersion() );
+
+        final String writeAlias = alias.getWriteAlias();
+
+        if ( logger.isDebugEnabled() ) {
+            logger.debug( "Indexing to alias {} with scope {} on edge {} with entity data {}",
+                writeAlias, applicationScope, indexEdge, flattenedEntityMap );
+        }
+
+        //add app id for indexing
+        container.addIndexRequest(new IndexOperation(writeAlias, applicationScope,
+            indexEdge,entity.getId(),entity.getVersion(),flattenedEntityMap) );
+        return this;
+    }
+
 
     @Override
     public EntityIndexBatch deindex( final SearchEdge searchEdge, final Id id, final UUID version ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
index 28f2e0d..b51d0c7 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/IndexOperation.java
@@ -21,10 +21,12 @@ package org.apache.usergrid.persistence.index.impl;
 
 
 import java.util.Map;
+import java.util.UUID;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.index.IndexEdge;
 import org.apache.usergrid.persistence.model.entity.Entity;
+import org.apache.usergrid.persistence.model.entity.Id;
 
 import org.elasticsearch.action.bulk.BulkRequestBuilder;
 import org.elasticsearch.action.index.IndexRequestBuilder;
@@ -48,10 +50,21 @@ public class IndexOperation implements BatchOperation {
 
     public IndexOperation( final String writeAlias, final ApplicationScope applicationScope, IndexEdge indexEdge,
                            Entity entity ) {
-        this(writeAlias,IndexingUtils.createIndexDocId(applicationScope, entity,indexEdge), EntityToMapConverter.convert(applicationScope,indexEdge, entity));
+
+
+        this(writeAlias,IndexingUtils.createIndexDocId(applicationScope, entity,indexEdge)
+            ,EntityToMapConverter.convert(applicationScope,indexEdge, entity));
+
 
     }
 
+    public IndexOperation( final String writeAlias, final ApplicationScope applicationScope, IndexEdge indexEdge,
+                           Id entityId, UUID version, Map<String,Object> data ) {
+
+        this(writeAlias,IndexingUtils.createIndexDocId(applicationScope, entityId,version,indexEdge)
+            ,data);
+    }
+
     public IndexOperation( final String writeAlias, String documentId, Map<String, Object> data ) {
         this.writeAlias = writeAlias;
         this.data = data;
@@ -107,4 +120,8 @@ public class IndexOperation implements BatchOperation {
         result = 31 * result + data.hashCode();
         return result;
     }
+
+    public Map convertedEntityToBeIndexed(ApplicationScope applicationScope,IndexEdge indexEdge,Entity entity){
+        return EntityToMapConverter.convert(applicationScope,indexEdge, entity);
+    }
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/f0480b48/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 2e4a3ff..ab46681 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -42,7 +42,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.ArrayList;
 
-
 import static org.junit.Assert.*;
 
 
@@ -230,6 +229,106 @@ public class CollectionsResourceIT extends AbstractRestIT {
 
     }
 
+    @Test
+    public void postToCollectionArraySchemaWithSchemaFirst() throws Exception {
+
+        //Include the property labeled two to be index.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "two" );
+        indexingArray.add( "one.key" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        Map<String,Object> arrayFieldsForTesting = new HashMap<>();
+
+        arrayFieldsForTesting.put( "key","value" );
+        arrayFieldsForTesting.put( "anotherKey","value2");
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", arrayFieldsForTesting );
+        testEntity.put( "two","query" );
+
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "one.key = 'value'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "value2",((Map)reindexedEntity.get( "one" )).get( "anotherKey" ) );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        query = "one.anotherKey = 'value2'";
+        queryParameters = new QueryParameters().setQuery(query);
+        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+    }
+
+    //test to reflect if one would index whatever is prefixed with that. Will
+    //need to do extensive testing to ensure that it will work with different instances.
+    @Test
+    public void postToCollectionSchemaArrayWithTopLevelIndexing() throws Exception {
+
+        //Include the property labeled two to be index.
+        ArrayList<String> indexingArray = new ArrayList<>(  );
+        indexingArray.add( "two" );
+        //this should work such that one.key and one.anotherKey should work.
+        indexingArray.add( "one" );
+
+        //field "fields" is required.
+        Entity payload = new Entity();
+        payload.put( "fields", indexingArray);
+
+        //Post index to the collection metadata
+        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        refreshIndex();
+
+        Map<String,Object> arrayFieldsForTesting = new HashMap<>();
+
+        arrayFieldsForTesting.put( "key","value" );
+        arrayFieldsForTesting.put( "anotherKey","value2");
+
+        //Create test collection with a test entity that is partially indexed.
+        Entity testEntity = new Entity();
+        testEntity.put( "one", arrayFieldsForTesting );
+        testEntity.put( "two","query" );
+
+        //Post entity.
+        this.app().collection( "testCollection" ).post( testEntity );
+        refreshIndex();
+
+        //Do a query to see if you can find the indexed query.
+        String query = "one.key = 'value'";
+        QueryParameters queryParameters = new QueryParameters().setQuery(query);
+
+        //having a name breaks it. Need to get rid of the stack trace and also
+        Collection tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+        Entity reindexedEntity = tempEntity.getResponse().getEntity();
+        assertEquals( "value2",((Map)reindexedEntity.get( "one" )).get( "anotherKey" ) );
+
+        //Verify if you can query on an entity that was not indexed and that no entities are returned.
+        //TODO: check that the below gets indexed as well. although the above should prove that at least one thing is getting indexed.
+//        query = "one.anotherKey = 'value2'";
+//        queryParameters = new QueryParameters().setQuery(query);
+//        tempEntity = this.app().collection( "testCollection" ).get(queryParameters,true);
+//        assertEquals(0,tempEntity.getResponse().getEntities().size());
+
+    }
+
+
+
 
     /**
      * Test posts with a user level token on a path with permissions


[15/36] usergrid git commit: Commented out the delay because it broke tests. Cleaned up some commented out code and spaces.

Posted by gr...@apache.org.
Commented out the delay because it broke tests.
Cleaned up some commented out code and spaces.


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

Branch: refs/heads/release-2.1.1
Commit: 1ba12b882ac9454a40e938199007a575b8d13078
Parents: e1d60b4
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 24 10:37:57 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 10:37:57 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpRelationManager.java      | 38 --------------------
 .../corepersistence/index/IndexServiceImpl.java |  3 --
 .../index/ReIndexServiceImpl.java               |  2 ++
 .../index/impl/EntityToMapConverter.java        |  8 -----
 .../rest/applications/CollectionResource.java   |  8 -----
 .../rest/applications/ServiceResource.java      |  2 --
 6 files changed, 2 insertions(+), 59 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
index faffbba..739aea4 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
@@ -408,44 +408,6 @@ public class CpRelationManager implements RelationManager {
 
         GraphManager gm = managerCache.getGraphManager( applicationScope );
 
-//        //do logic here
-//        String jsonMap = mm.getString( collectionName );
-//
-//        Set<String> defaultProperties = null;
-//
-//        if(jsonMap != null) {
-//
-//            Map jsonMapData = ( Map ) JsonUtils.parse( jsonMap );
-//            Schema schema = Schema.getDefaultSchema();
-//            defaultProperties = schema.getRequiredProperties( collectionName );
-//            //TODO: additional logic to
-//            ArrayList fieldsToKeep = ( ArrayList ) jsonMapData.get( "fields" );
-//            defaultProperties.addAll( fieldsToKeep );
-//
-//        }
-//
-//        Collection<String> trimmedFields = null;
-//        if(defaultProperties!=null){
-//           // if(cpHeadEntity.getFields())
-//            final Set<String> finalDefaultProperties = defaultProperties;
-//            trimmedFields = memberEntity.getFieldMap().keySet();
-//            Iterator collectionIterator = trimmedFields.iterator();
-//            while(collectionIterator.hasNext()){
-//                if(!finalDefaultProperties.contains( collectionIterator.next() )){
-//                    collectionIterator.remove();
-//                }
-//            }
-
-
-//            trimmedFields.forEach( element -> {
-//                if(!finalDefaultProperties.contains( element )){
-//                    memberEntity.removeField( element );
-//                }
-//            });
-
-//        }
-
-
         gm.writeEdge( edge ).doOnNext( writtenEdge -> {
             if ( logger.isDebugEnabled() ) {
                 logger.debug( "Wrote edge {}", writtenEdge );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index f8d7aa5..c0f2e1b 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -119,9 +119,6 @@ public class IndexServiceImpl implements IndexService {
         //we may have to index  we're indexing from source->target here
         final Observable<IndexEdge> sourceEdgesToIndex = edgesToTarget.map( edge -> generateScopeFromSource( edge ) );
 
-
-
-
         //do our observable for batching
         //try to send a whole batch if we can
         final Observable<IndexOperationMessage>  batches =  sourceEdgesToIndex

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
index da2ef1d..fc1c97f 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/ReIndexServiceImpl.java
@@ -21,6 +21,7 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 
 import org.apache.usergrid.persistence.index.EntityIndexFactory;
@@ -125,6 +126,7 @@ public class ReIndexServiceImpl implements ReIndexService {
         final Observable<List<EdgeScope>> runningReIndex = allEntityIdsObservable.getEdgesToEntities( applicationScopes,
             reIndexRequestBuilder.getCollectionName(), cursorSeek.getSeekValue() )
             .buffer( indexProcessorFig.getReindexBufferSize())
+            //.delay( 50, TimeUnit.MILLISECONDS )
             .doOnNext(edges -> {
 
                 logger.info("Sending batch of {} to be indexed.", edges.size());

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 77a8d92..b43f4bb 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -17,22 +17,15 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.index.IndexEdge;
-import org.apache.usergrid.persistence.map.MapManager;
-import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.EntityMap;
 import org.apache.usergrid.persistence.model.entity.Id;
-import org.apache.usergrid.persistence.model.entity.SimpleId;
 
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.APPLICATION_ID_FIELDNAME;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.EDGE_NAME_FIELDNAME;
@@ -51,7 +44,6 @@ import static org.apache.usergrid.persistence.index.impl.IndexingUtils.getType;
 import static org.apache.usergrid.persistence.index.impl.IndexingUtils.nodeId;
 
 
-
 /**
  * Convert a CP entity to an elasticsearch document
  */

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index 8b05a79..b674ac4 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -144,14 +144,6 @@ public class CollectionResource extends ServiceResource {
                                              @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
-        System.out.println();
-//        logger.info( "Rebuilding collection {} in  application {}", collectionName, applicationIdStr );
-//
-//
-//
-//        final UUID appId = UUIDUtils.tryExtractUUID( applicationIdStr );
-//
-        //TODO: check to see how all of this runs with service and query params. Ideally none should be passed in.
         final ReIndexRequestBuilder request =
             createRequest().withApplicationId( services.getApplicationId() ).withCollection(
                 String.valueOf( getServiceParameters().get( 0 ) ) );

http://git-wip-us.apache.org/repos/asf/usergrid/blob/1ba12b88/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
index c723366..9e7bc91 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
@@ -297,8 +297,6 @@ public class ServiceResource extends AbstractContextResource {
         httpServletRequest.setAttribute( "applicationId", services.getApplicationId() );
 
         return results;
-
-
     }
 
     public ServiceResults executeServicePostRequestForSchema(UriInfo ui, ApiResponse response, ServiceAction action,


[02/36] usergrid git commit: Added a method to properly set the owner ( at least the email ) to the schema map in elastic search Removed traces of creating a new column family. Map manager is the way to go. Added the get endpoint to the service resource

Posted by gr...@apache.org.
Added a method to properly set the owner ( at least the email ) to the schema map in elastic search
Removed traces of creating a new column family. Map manager is the way to go.
Added the get endpoint to the service resource that will allow us to do gets.
Added a way for the endpoint to read the JSON response and did the specific call out so that we could work around having to make a service ( Which is bad code )

Returned an object with a terrible name to debug the response that gets returned.
Added AbstractCollectionService method that allows us to get the workaround to a normal call in order to get around path permission checking.
AbstractService has the workaround which is what needs to be done if you want to avoid using a schema.
Added a new service action for the work around.


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

Branch: refs/heads/release-2.1.1
Commit: 58e6cf38660350b16f3d443dfe781bc9f1c90903
Parents: 56e0371
Author: George Reyes <gr...@apache.org>
Authored: Mon Mar 7 10:40:27 2016 -0800
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 24 09:05:42 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpEntityManager.java        | 49 +++++++++-
 .../usergrid/persistence/EntityManager.java     |  4 +
 .../persistence/cassandra/ApplicationCF.java    |  5 -
 .../rest/applications/ServiceResource.java      | 98 +++++++++++++++++++-
 .../collection/CollectionsResourceIT.java       |  2 +-
 .../services/AbstractCollectionService.java     | 19 ++++
 .../services/AbstractConnectionsService.java    |  7 ++
 .../usergrid/services/AbstractService.java      |  7 ++
 .../apache/usergrid/services/ServiceAction.java |  2 +-
 .../applications/ApplicationsService.java       |  7 ++
 10 files changed, 190 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/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 3dbdb7d..6a6d036 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
@@ -17,11 +17,15 @@ package org.apache.usergrid.corepersistence;
 
 
 import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -1730,8 +1734,49 @@ public class CpEntityManager implements EntityManager {
         return get( id, Role.class );
     }
 
+    @Override
+    public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties ){
+
+
+        //haven't decided which one I should base off of which, maybe from epoch to utc
+        Instant timeInstance = Instant.now();
+
+        Date date = Date.from(timeInstance);
+        Long epoch = timeInstance.toEpochMilli();
+
+        Map<String,Object> schemaMap = new HashMap<>(  );
+
+
+        schemaMap.put("lastUpdated",epoch);
+        //this needs the method that can extract the user from the token no matter the token.
+        //Possible values are app credentials, org credentials, or the user email(Admin tokens).
+        schemaMap.put("lastUpdateBy",owner);
+        schemaMap.put("lastReindexed",0);
+        schemaMap.putAll( properties );
+
+        //Map<String,Object> fields = properties.get( "properties" );
+
+        //for(Object)
+
+        MapManager mm = getMapManagerForTypes();
+        mm.putString( collectionName,schemaMap.toString() );
+
+        return schemaMap;
+
+    }
 
     @Override
+    public Entity createCollectionSchema( String collectionName ){
+        MapManager mm = getMapManagerForTypes();
+        String jsonMap = mm.getString( collectionName );
+
+        Object obj = JsonUtils.parse( jsonMap );
+
+        return null;
+    }
+
+
+        @Override
     public void grantRolePermission( String roleName, String permission ) throws Exception {
         roleName = roleName.toLowerCase();
         permission = permission.toLowerCase();
@@ -2663,6 +2708,7 @@ public class CpEntityManager implements EntityManager {
                     cpEntity.getId().getType(), cpEntity.getId().getUuid(), cpEntity.getVersion() );
             }
 
+            //this does the write so before adding to a collection everything already exists already.
             cpEntity = ecm.write( cpEntity ).toBlocking().last();
             entity.setSize(cpEntity.getSize());
 
@@ -2683,6 +2729,8 @@ public class CpEntityManager implements EntityManager {
         // add to and index in collection of the application
         if ( !is_application ) {
 
+            //maybe a check here to see if it exists in the column family and if it doesn't then SEND IT ON THROUGHH
+
             String collectionName = Schema.defaultCollectionName( eType );
             CpRelationManager cpr = ( CpRelationManager ) getRelationManager( getApplication() );
             cpr.addToCollection( collectionName, entity );
@@ -2695,7 +2743,6 @@ public class CpEntityManager implements EntityManager {
         MapManager mm = getMapManagerForTypes();
         mm.putString( itemId.toString(), entity.getType() );
 
-
         return entity;
     }
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/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 1a844f6..7c5cc5b 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
@@ -512,6 +512,10 @@ public interface EntityManager {
      */
     public Entity createRole( String roleName, String roleTitle, long inactivity ) throws Exception;
 
+    public Map createCollectionSchema( String collectionName, String owner ,Map<String, Object> properties );
+
+    Entity createCollectionSchema( String collectionName );
+
     public void grantRolePermission( String roleName, String permission ) throws Exception;
 
     public void grantRolePermissions( String roleName, Collection<String> permissions ) throws Exception;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
index ad72717..242d360 100644
--- a/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
+++ b/stack/core/src/main/java/org/apache/usergrid/persistence/cassandra/ApplicationCF.java
@@ -46,11 +46,6 @@ public enum ApplicationCF implements CFEnum {
     /** Entity counters */
     ENTITY_COUNTERS( "Entity_Counters", "BytesType", COUNTERTYPE.getClassName() );
 
-    /**
-     * Collection Schema
-     */
-    COL_SCHEMA( "")
-
     private final String cf;
     private final String comparator;
     private final String validator;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
index 2843417..3318adf 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ServiceResource.java
@@ -244,6 +244,55 @@ public class ServiceResource extends AbstractContextResource {
         return getSubResource( ServiceResource.class );
     }
 
+    public ServiceResults executeServiceRequestForSchema(UriInfo ui, ApiResponse response, ServiceAction action,
+                                                         ServicePayload payload) throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.executeServiceRequest" );
+        }
+
+
+        boolean tree = "true".equalsIgnoreCase( ui.getQueryParameters().getFirst( "tree" ) );
+
+        String connectionQueryParm = ui.getQueryParameters().getFirst("connections");
+        boolean returnInboundConnections = true;
+        boolean returnOutboundConnections = true;
+
+        addQueryParams( getServiceParameters(), ui );
+
+        ServiceRequest r = services.newRequest( action, tree, getServiceParameters(), payload,
+            returnInboundConnections, returnOutboundConnections );
+
+        response.setServiceRequest( r );
+        ServiceResults results = r.execute();
+        if ( results != null ) {
+            if ( results.hasData() ) {
+                response.setData( results.getData() );
+            }
+            if ( results.getServiceMetadata() != null ) {
+                response.setMetadata( results.getServiceMetadata() );
+            }
+            Query query = r.getLastQuery();
+            if ( query != null ) {
+                if ( query.hasSelectSubjects() ) {
+                    response.setList( QueryUtils.getSelectionResults( query, results ) );
+                    response.setCount( response.getList().size() );
+                    response.setNext( results.getNextResult() );
+                    response.setPath( results.getPath() );
+                    return results;
+                }
+            }
+
+            response.setResults( results );
+        }
+
+        httpServletRequest.setAttribute( "applicationId", services.getApplicationId() );
+
+        return results;
+
+
+    }
+
 
     public ServiceResults executeServiceRequest( UriInfo ui, ApiResponse response, ServiceAction action,
                                                  ServicePayload payload ) throws Exception {
@@ -366,7 +415,7 @@ public class ServiceResource extends AbstractContextResource {
     @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
     @RequireApplicationAccess
     @JSONP
-    public ApiResponse executePostOnIndexes( @Context UriInfo ui,
+    public ApiResponse executePostOnIndexes( @Context UriInfo ui, String body,
                                    @QueryParam("callback") @DefaultValue("callback") String callback )
         throws Exception {
 
@@ -374,17 +423,62 @@ public class ServiceResource extends AbstractContextResource {
             logger.trace( "ServiceResource.executePostOnIndexes" );
         }
 
+        Object json;
+        if ( StringUtils.isEmpty( body ) ) {
+            json = null;
+        } else {
+            json = readJsonToObject( body );
+        }
+
         ApiResponse response = createApiResponse();
 
         response.setAction( "post" );
         response.setApplication( services.getApplication() );
         response.setParams( ui.getQueryParameters() );
 
-        executeServiceRequest( ui, response, ServiceAction.POST, null );
+        ServicePayload payload = getPayload( json );
+
+        executeServiceRequestForSchema( ui,response,ServiceAction.SCHEMA,payload );
+
+        return response;
+    }
+
+    @GET
+    @Path("_index")
+    @Produces({MediaType.APPLICATION_JSON,"application/javascript"})
+    @RequireApplicationAccess
+    @JSONP
+    public ApiResponse executeGetOnIndex( @Context UriInfo ui, String body,
+                                             @QueryParam("callback") @DefaultValue("callback") String callback )
+        throws Exception {
+
+        if(logger.isTraceEnabled()){
+            logger.trace( "ServiceResource.executePostOnIndexes" );
+        }
+
+        Object json;
+        if ( StringUtils.isEmpty( body ) ) {
+            json = null;
+        } else {
+            json = readJsonToObject( body );
+        }
+
+        ApiResponse response = createApiResponse();
+
+
+
+        response.setAction( "get" );
+        response.setApplication( services.getApplication() );
+        response.setParams( ui.getQueryParameters() );
+
+        ServicePayload payload = getPayload( json );
+
+        executeServiceRequest( ui, response, ServiceAction.GET, payload );
 
         return response;
     }
 
+
     @SuppressWarnings({ "unchecked" })
     public ServicePayload getPayload( Object json ) {
         ServicePayload payload = null;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index ca5360d..773317b 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -149,7 +149,7 @@ public class CollectionsResourceIT extends AbstractRestIT {
         payload.put( "fields", indexingArray);
 
         //Post index to the collection metadata
-        this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
+        Object thing = this.app().collection( "testCollection" ).collection( "_indexes" ).post( payload );
         refreshIndex();
 
         //Below is what needs to be implemented along with the index call above

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
index 0ad751a..f6d2849 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
@@ -25,6 +25,9 @@ import java.util.UUID;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+
+import org.apache.shiro.subject.Subject;
+
 import org.apache.usergrid.persistence.Entity;
 import org.apache.usergrid.persistence.EntityRef;
 import org.apache.usergrid.persistence.Query;
@@ -34,6 +37,8 @@ import org.apache.usergrid.persistence.SimpleEntityRef;
 import org.apache.usergrid.persistence.exceptions.EntityNotFoundException;
 import org.apache.usergrid.persistence.exceptions.UnexpectedEntityTypeException;
 import org.apache.usergrid.persistence.Query.Level;
+import org.apache.usergrid.security.shiro.principals.AdminUserPrincipal;
+import org.apache.usergrid.security.shiro.utils.SubjectUtils;
 import org.apache.usergrid.services.ServiceResults.Type;
 import org.apache.usergrid.services.exceptions.ForbiddenServiceOperationException;
 import org.apache.usergrid.services.exceptions.ServiceResourceNotFoundException;
@@ -318,6 +323,20 @@ public class AbstractCollectionService extends AbstractService {
         return new ServiceResults( this, context, Type.COLLECTION, r, null, null );
     }
 
+    @Override
+    public ServiceResults postCollectionSchema( ServiceContext context ) throws Exception {
+        context.setAction( ServiceAction.POST );
+        checkPermissionsForCollection( context );
+        Subject currentUser = SubjectUtils.getSubject();
+        Object currentUser2 =currentUser.getPrincipal();
+
+        Map collectionSchema = em.createCollectionSchema(context.getCollectionName(),
+            ( ( AdminUserPrincipal ) currentUser2 ).getUser().getEmail(),context.getProperties());
+
+        return new ServiceResults( this, context, Type.COLLECTION, Results.fromData( collectionSchema ), null, null );
+
+    }
+
 
     @Override
     public ServiceResults postCollection( ServiceContext context ) throws Exception {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
index 94b25d3..666f676 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
@@ -38,6 +38,7 @@ import org.apache.usergrid.services.ServiceParameter.NameParameter;
 import org.apache.usergrid.services.ServiceParameter.QueryParameter;
 import org.apache.usergrid.services.ServiceResults.Type;
 import org.apache.usergrid.services.exceptions.ServiceResourceNotFoundException;
+import org.apache.usergrid.services.exceptions.UnsupportedServiceOperationException;
 
 import rx.Observable;
 import rx.schedulers.Schedulers;
@@ -391,6 +392,12 @@ public class AbstractConnectionsService extends AbstractService {
 
 
     @Override
+    public ServiceResults postCollectionSchema( final ServiceContext context ) throws Exception {
+        throw new UnsupportedServiceOperationException( context );
+    }
+
+
+    @Override
     public ServiceResults putItemById( ServiceContext context, UUID id ) throws Exception {
 
         if ( context.moreParameters() ) {

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
index 5d818cc..3c5503c 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractService.java
@@ -55,6 +55,7 @@ import org.apache.usergrid.services.ServiceResults.Type;
 import org.apache.usergrid.services.exceptions.ServiceInvocationException;
 import org.apache.usergrid.services.exceptions.ServiceResourceNotFoundException;
 import org.apache.usergrid.services.exceptions.UnsupportedServiceOperationException;
+import org.apache.usergrid.services.generic.RootCollectionService;
 
 import com.google.inject.Injector;
 import com.google.inject.Key;
@@ -827,6 +828,9 @@ public abstract class AbstractService implements Service {
 
             case HEAD:
                 return headCollection( context );
+
+            case SCHEMA:
+                return postCollectionSchema( context );
         }
 
         throw new ServiceInvocationException( context, "Request action unhandled " + context.getAction() );
@@ -888,6 +892,9 @@ public abstract class AbstractService implements Service {
     }
 
 
+    public abstract ServiceResults postCollectionSchema( ServiceContext context ) throws Exception;
+
+
     public ServiceResults postCollection( ServiceContext context ) throws Exception {
         throw new UnsupportedServiceOperationException( context );
     }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java b/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
index e1c6133..ec34df4 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/ServiceAction.java
@@ -18,5 +18,5 @@ package org.apache.usergrid.services;
 
 
 public enum ServiceAction {
-    POST, GET, PUT, DELETE, HEAD, OPTIONS;
+    POST, GET, PUT, DELETE, HEAD, OPTIONS, SCHEMA;
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/58e6cf38/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java b/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
index ae524c6..cf4aa80 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/applications/ApplicationsService.java
@@ -34,6 +34,7 @@ import org.apache.usergrid.services.ServiceParameter.QueryParameter;
 import org.apache.usergrid.services.ServicePayload;
 import org.apache.usergrid.services.ServiceResults;
 import org.apache.usergrid.services.ServiceResults.Type;
+import org.apache.usergrid.services.exceptions.UnsupportedServiceOperationException;
 
 import org.apache.commons.lang.StringUtils;
 
@@ -94,6 +95,12 @@ public class ApplicationsService extends AbstractService {
 
 
     @Override
+    public ServiceResults postCollectionSchema( final ServiceContext context ) throws Exception {
+        throw new UnsupportedServiceOperationException( context );
+    }
+
+
+    @Override
     public ServiceResults getEntityDictionary( ServiceContext context, List<EntityRef> refs,
                                                EntityDictionaryEntry dictionary ) throws Exception {
 


[31/36] usergrid git commit: Cleaned up the old code that used to do the filtering.

Posted by gr...@apache.org.
Cleaned up the old code that used to do the filtering.


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

Branch: refs/heads/release-2.1.1
Commit: 8beb3a586ec0b8aafbee79aff762d354398ba8bb
Parents: c748368
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 31 17:21:56 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 31 17:21:56 2016 -0700

----------------------------------------------------------------------
 .../index/impl/EntityToMapConverter.java        | 85 ++------------------
 1 file changed, 6 insertions(+), 79 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/8beb3a58/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
index 259b421..a331c38 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EntityToMapConverter.java
@@ -149,8 +149,6 @@ public class EntityToMapConverter {
                                                                final Iterator collectionIterator,
                                                                final String fieldName ) {
         boolean toRemoveFlag = true;
-        String[] flattedStringArray = getStrings( fieldName );
-
         Iterator fieldIterator = fieldsToKeep.iterator();
 
 
@@ -161,102 +159,31 @@ public class EntityToMapConverter {
         while ( fieldIterator.hasNext() ) {
             //this is the field that we're
             String requiredInclusionString = ( String ) fieldIterator.next();
-            String[] flattedRequirementString = getStrings( requiredInclusionString );
-
 
-            //loop each split array value to see if it matches the equivalent value
-            //in the field. e.g in the example one.two.three and one.two.four we need to check that the schema
-            //matches in both one and two above. If instead it says to exclude one.twor then we would still exclude the above
-            //since it is required to be a hard match.
 
-            //The way the below works if we see that the current field isn't as fine grained as the schema rule
-            //( aka the array is shorter than the current index of the schema rule then there is no way the rule could apply
-            // to the index.
+            //Since we know that the fieldName cannot be equal to the requiredInclusion criteria due to the if condition before we enter this method
+            //and we are certain that the indexing criteria is shorter we want to be sure that the inclusion criteria
+            //is contained within the field we're evaluating. i.e that one.two.three contains one.two
 
-            //Then if that check passes we go to check that both parts are equal. If they are ever not equal
-            // e.g one.two.three and one.three.two then it shouldn't be included
-            //TODO: regex.
-            //The regex for this will need to be as follows
-            //Check to make sure that the strings match all the way and end with a period.
-
-            //so if the field we're evaluting against  is in the field name
-            //is one.two.three contains one.two
-            //if one.two is following by nothing or a period then it can be indexed.
+            //The second part of the if loop also requires that the fieldName is followed by a period after we check to ensure that the
+            //indexing criteria is included in the string. This is done to weed out values such as one.twoexample.three
+            // when we should only keep one.two.three when comparing the indexing criteria of one.two.
             if(fieldName.length() > requiredInclusionString.length()
                 && fieldName.contains( requiredInclusionString )
                 && fieldName.charAt( requiredInclusionString.length() )=='.' ) {
                 toRemoveFlag = false;
                 break;
-
-                //Since we know that the fieldName cannot be equal to the requiredInclusion criteria due to the if condition before we enter this method
-                //and we are certain that the indexing criteria is shorter we want to be sure that the inclusion criteria
-                //is contained within the field we're evaluating. i.e that one.two.three contains one.two
-
-                //The second part of the if loop also requires that the fieldName is followed by a period after we check to ensure that the
-                //indexing criteria is included in the string. This is done to weed out values such as one.twoexample.three
-                // when we should only keep one.two.three when comparing the indexing criteria of one.two.
-//                if(fieldName.contains( requiredInclusionString ) && fieldName.charAt( requiredInclusionString.length() )=='.'){
-//                    toRemoveFlag = false;
-//                    break;
-//                }
-//                toRemoveFlag = true;
-
             }
             else {
                 //the of the field we're evaluating is shorter than the indexing criteria so it can't match.
                 //Move onto the next field and see if they match.
                 toRemoveFlag = true;
             }
-
-
-//            for ( int index = 0; index < flattedRequirementString.length; index++ ) {
-//                //if the array contains a string that it is equals to then set the remove flag to true
-//                //otherwise remain false.
-//
-//                //one.three
-//                //one.two
-//                //one
-//                if ( flattedStringArray.length <= index ) {
-//                    toRemoveFlag = true;
-//                    break;
-//                }
-//
-//                if ( flattedRequirementString[index].equals( flattedStringArray[index] ) ) {
-//                    toRemoveFlag = false;
-//                }
-//                else {
-//                    toRemoveFlag = true;
-//                    break;
-//                }
-//            }
-//            if ( toRemoveFlag == false ) {
-//                break;
-//            }
         }
 
         if ( toRemoveFlag ) {
-            //Removes the value if it doesn't match anything
             collectionIterator.remove();
         }
     }
-
-
-    /**
-     * Splits the string on the flattened period "." seperated values.
-     * @param fieldName
-     * @return
-     */
-    private static String[] getStrings( final String fieldName ) {
-        final String[] flattedStringArray;
-        if ( !fieldName.contains( "." ) ) {
-            //create a single array that is made of a the single value.
-            flattedStringArray = new String[] { fieldName };
-        }
-        else {
-            flattedStringArray = fieldName.split( "\\." );
-        }
-        return flattedStringArray;
-    }
-
 }
 


[28/36] usergrid git commit: Added a way to use the existing reindex code to reindex the collection rather than copying and pasting the reindex code.

Posted by gr...@apache.org.
Added a way to use the existing reindex code to reindex the collection rather than copying and pasting the reindex code.


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

Branch: refs/heads/release-2.1.1
Commit: 37eca05b1d5f26d6d3e7125a2324ef62378b6070
Parents: 956a6f5
Author: George Reyes <gr...@apache.org>
Authored: Thu Mar 31 15:59:55 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Thu Mar 31 15:59:55 2016 -0700

----------------------------------------------------------------------
 .../org/apache/usergrid/rest/ApiResponse.java   |  7 +++-
 .../rest/applications/CollectionResource.java   | 43 ++++----------------
 .../usergrid/rest/system/IndexResource.java     |  6 +++
 .../collection/CollectionsResourceIT.java       |  1 -
 4 files changed, 21 insertions(+), 36 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/37eca05b/stack/rest/src/main/java/org/apache/usergrid/rest/ApiResponse.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/ApiResponse.java b/stack/rest/src/main/java/org/apache/usergrid/rest/ApiResponse.java
index d5d3182..727d187 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/ApiResponse.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/ApiResponse.java
@@ -118,7 +118,12 @@ public class ApiResponse {
     public ApiResponse( ServerEnvironmentProperties serverProperties, ManagementService management ) {
         this.serverEnvironmentProperties = serverProperties;
         this.management = management;
-        this.config = management.getOrganizationConfigDefaultsOnly();
+        if(management!=null) {
+            this.config = management.getOrganizationConfigDefaultsOnly();
+        }
+        else {
+            this.config = null;
+        }
         timestamp = System.currentTimeMillis();
     }
 

http://git-wip-us.apache.org/repos/asf/usergrid/blob/37eca05b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
index b097469..c124f9d 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/CollectionResource.java
@@ -50,6 +50,7 @@ import org.apache.usergrid.rest.ApiResponse;
 import org.apache.usergrid.rest.RootResource;
 import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
 import org.apache.usergrid.rest.security.annotations.RequireSystemAccess;
+import org.apache.usergrid.rest.system.IndexResource;
 import org.apache.usergrid.services.AbstractCollectionService;
 import org.apache.usergrid.services.ServiceAction;
 import org.apache.usergrid.services.ServiceParameter;
@@ -120,6 +121,8 @@ public class CollectionResource extends ServiceResource {
 
     private void addItemToServiceContext( final @Context UriInfo ui,
                                           final @PathParam( "itemName" ) PathSegment itemName ) throws Exception {
+        //The below is duplicated because it could change in the future and is probably not all needed but
+        //not determined yet.
         if ( itemName.getPath().startsWith( "{" ) ) {
             Query query = Query.fromJsonString( itemName.getPath() );
             if ( query != null ) {
@@ -203,40 +206,12 @@ public class CollectionResource extends ServiceResource {
 
         addItemToServiceContext( ui, itemName );
 
-        final ReIndexRequestBuilder request =
-            createRequest().withApplicationId( services.getApplicationId() ).withCollection(
-                String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 50, TimeUnit.MILLISECONDS );
-
-        return executeAndCreateResponse( request, callback );
-    }
-
-    private ReIndexService getReIndexService() {
-        return injector.getInstance( ReIndexService.class );
-    }
-
-    private ReIndexRequestBuilder createRequest() {
-        //TODO: wire this up through spring, and in the future guice.
-        return new ReIndexRequestBuilderImpl();
-    }
-
-    /**
-     * Execute the request and return the response.
-     */
-    private ApiResponse executeAndCreateResponse( final ReIndexRequestBuilder request, final String callback ) {
-
-
-        final ReIndexService.ReIndexStatus status = getReIndexService().rebuildIndex( request );
-
-        final ApiResponse response = createApiResponse();
-
-        response.setAction( "rebuild indexes" );
-        response.setProperty( "jobId", status.getJobId() );
-        response.setProperty( "status", status.getStatus() );
-        response.setProperty( "lastUpdatedEpoch", status.getLastUpdated() );
-        response.setProperty( "numberQueued", status.getNumberProcessed() );
-        response.setSuccess();
-
-        return response;
+//        final ReIndexRequestBuilder request =
+//            createRequest().withApplicationId( services.getApplicationId() ).withCollection(
+//                String.valueOf( getServiceParameters().get( 0 ) ) ).withDelay( 50, TimeUnit.MILLISECONDS );
+//
+        IndexResource indexResource = new IndexResource(injector);
+        return indexResource.rebuildIndexesPost( services.getApplicationId().toString(),itemName.getPath(),false,callback );
     }
 
 }

http://git-wip-us.apache.org/repos/asf/usergrid/blob/37eca05b/stack/rest/src/main/java/org/apache/usergrid/rest/system/IndexResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/main/java/org/apache/usergrid/rest/system/IndexResource.java b/stack/rest/src/main/java/org/apache/usergrid/rest/system/IndexResource.java
index 4a521b3..be60177 100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/system/IndexResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/system/IndexResource.java
@@ -23,6 +23,8 @@ package org.apache.usergrid.rest.system;
 
 import com.fasterxml.jackson.jaxrs.json.annotation.JSONP;
 import com.google.common.base.Preconditions;
+import com.google.inject.Injector;
+
 import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilder;
 import org.apache.usergrid.corepersistence.index.ReIndexRequestBuilderImpl;
 import org.apache.usergrid.corepersistence.index.ReIndexService;
@@ -67,6 +69,10 @@ public class IndexResource extends AbstractContextResource {
         super();
     }
 
+    public IndexResource( Injector injector) {
+        this.injector = injector;
+    }
+
 
     @RequireSystemAccess
     @POST

http://git-wip-us.apache.org/repos/asf/usergrid/blob/37eca05b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
index 8ec4a3a..d814f55 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -279,7 +279,6 @@ public class CollectionsResourceIT extends AbstractRestIT {
             this.app().collection( "testCollection" ).post( testEntity );
         }
 
-
         //Creating schema.
         //this could be changed to a hashmap.
         ArrayList<String> indexingArray = new ArrayList<>(  );


[21/36] usergrid git commit: Removed all unused imports in cpRelationManager and IndexServiceImpl and EsEntityIndexBatchImpl. Re-added final keyword to indexing interface

Posted by gr...@apache.org.
Removed all unused imports in cpRelationManager and IndexServiceImpl and EsEntityIndexBatchImpl.
Re-added final keyword to indexing interface


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

Branch: refs/heads/release-2.1.1
Commit: bc1fdef34b6d68ff9f95fcae93c4733ca52f91f7
Parents: 899e464
Author: George Reyes <gr...@apache.org>
Authored: Wed Mar 30 11:02:19 2016 -0700
Committer: George Reyes <gr...@apache.org>
Committed: Wed Mar 30 11:02:19 2016 -0700

----------------------------------------------------------------------
 .../corepersistence/CpRelationManager.java      | 12 ---------
 .../corepersistence/index/IndexServiceImpl.java | 26 +++++++++++---------
 .../persistence/index/EntityIndexBatch.java     | 10 ++++++--
 .../index/impl/EsEntityIndexBatchImpl.java      | 13 +++++-----
 4 files changed, 30 insertions(+), 31 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/usergrid/blob/bc1fdef3/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
index 378767e..67e92f8 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
@@ -18,7 +18,6 @@ package org.apache.usergrid.corepersistence;
 
 
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -66,29 +65,19 @@ import org.apache.usergrid.persistence.graph.SearchByEdgeType;
 import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdge;
 import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdgeType;
 import org.apache.usergrid.persistence.graph.impl.SimpleSearchEdgeType;
-import org.apache.usergrid.persistence.index.EntityIndex;
-import org.apache.usergrid.persistence.index.EntityIndexBatch;
-import org.apache.usergrid.persistence.index.SearchEdge;
 import org.apache.usergrid.persistence.index.query.Identifier;
-import org.apache.usergrid.persistence.map.MapManager;
-import org.apache.usergrid.persistence.map.MapScope;
 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.NullField;
 import org.apache.usergrid.persistence.schema.CollectionInfo;
 import org.apache.usergrid.utils.InflectionUtils;
-import org.apache.usergrid.utils.JsonUtils;
 import org.apache.usergrid.utils.MapUtils;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 
 import rx.Observable;
-import rx.functions.Func1;
 
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createCollectionEdge;
-import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createCollectionSearchEdge;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createConnectionEdge;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.createConnectionSearchByEdge;
 import static org.apache.usergrid.corepersistence.util.CpNamingUtils.getNameFromEdgeType;
@@ -96,7 +85,6 @@ import static org.apache.usergrid.persistence.Schema.COLLECTION_ROLES;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_INACTIVITY;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
 import static org.apache.usergrid.persistence.Schema.PROPERTY_TITLE;
-import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
 import static org.apache.usergrid.persistence.Schema.TYPE_ENTITY;
 import static org.apache.usergrid.persistence.Schema.TYPE_ROLE;
 import static org.apache.usergrid.persistence.Schema.getDefaultSchema;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/bc1fdef3/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
index c010c06..f3a3389 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/index/IndexServiceImpl.java
@@ -21,7 +21,6 @@ package org.apache.usergrid.corepersistence.index;
 
 
 import java.util.ArrayList;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Optional;
@@ -29,20 +28,11 @@ import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
-import org.apache.usergrid.persistence.Schema;
-import org.apache.usergrid.persistence.index.*;
-import org.apache.usergrid.persistence.index.impl.EntityField;
-import org.apache.usergrid.persistence.index.impl.IndexOperation;
-import org.apache.usergrid.persistence.map.MapManager;
-import org.apache.usergrid.persistence.map.MapManagerFactory;
-import org.apache.usergrid.persistence.map.MapScope;
-import org.apache.usergrid.persistence.model.entity.SimpleId;
-import org.apache.usergrid.utils.JsonUtils;
-import org.apache.usergrid.utils.UUIDUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.usergrid.corepersistence.util.CpNamingUtils;
+import org.apache.usergrid.persistence.Schema;
 import org.apache.usergrid.persistence.core.metrics.MetricsFactory;
 import org.apache.usergrid.persistence.core.metrics.ObservableTimer;
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
@@ -51,10 +41,24 @@ import org.apache.usergrid.persistence.graph.GraphManager;
 import org.apache.usergrid.persistence.graph.GraphManagerFactory;
 import org.apache.usergrid.persistence.graph.impl.SimpleEdge;
 import org.apache.usergrid.persistence.graph.serialization.EdgesObservable;
+import org.apache.usergrid.persistence.index.CandidateResult;
+import org.apache.usergrid.persistence.index.CandidateResults;
+import org.apache.usergrid.persistence.index.EntityIndex;
+import org.apache.usergrid.persistence.index.EntityIndexBatch;
+import org.apache.usergrid.persistence.index.EntityIndexFactory;
+import org.apache.usergrid.persistence.index.IndexEdge;
+import org.apache.usergrid.persistence.index.IndexFig;
+import org.apache.usergrid.persistence.index.SearchEdge;
 import org.apache.usergrid.persistence.index.impl.IndexOperationMessage;
+import org.apache.usergrid.persistence.map.MapManager;
+import org.apache.usergrid.persistence.map.MapManagerFactory;
+import org.apache.usergrid.persistence.map.MapScope;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
 import org.apache.usergrid.utils.InflectionUtils;
+import org.apache.usergrid.utils.JsonUtils;
+import org.apache.usergrid.utils.UUIDUtils;
 
 import com.codahale.metrics.Timer;
 import com.google.inject.Inject;

http://git-wip-us.apache.org/repos/asf/usergrid/blob/bc1fdef3/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
index 2e5ece6..274aea5 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/EntityIndexBatch.java
@@ -32,7 +32,13 @@ import rx.Observable;
 
 public interface EntityIndexBatch {
 
-    EntityIndexBatch index( IndexEdge indexEdge, Entity entity );
+    /**
+     * Create index for Entity
+     *
+     * @param indexEdge  The edge to index the document into
+     * @param entity     Entity to be indexed.
+     * */
+    EntityIndexBatch index(final IndexEdge indexEdge, final Entity entity );
 
     /**
      * Remove index of entity
@@ -51,7 +57,7 @@ public interface EntityIndexBatch {
     EntityIndexBatch deindex( final SearchEdge searchEdge, final CandidateResult result );
 
 
-    EntityIndexBatch index( IndexEdge indexEdge, Entity entity, Optional<Set<String>> fieldsToIndex );
+    EntityIndexBatch index(final IndexEdge indexEdge, final Entity entity, final Optional<Set<String>> fieldsToIndex );
 
     /**
      * Remove index of entity.

http://git-wip-us.apache.org/repos/asf/usergrid/blob/bc1fdef3/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
index ed00f48..0375841 100644
--- a/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
+++ b/stack/corepersistence/queryindex/src/main/java/org/apache/usergrid/persistence/index/impl/EsEntityIndexBatchImpl.java
@@ -19,24 +19,25 @@
 package org.apache.usergrid.persistence.index.impl;
 
 
-import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 
-import org.apache.usergrid.persistence.index.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.cassandra.auth.IAuthenticator;
-
 import org.apache.usergrid.persistence.core.scope.ApplicationScope;
 import org.apache.usergrid.persistence.core.util.ValidationUtils;
+import org.apache.usergrid.persistence.index.CandidateResult;
+import org.apache.usergrid.persistence.index.EntityIndex;
+import org.apache.usergrid.persistence.index.EntityIndexBatch;
+import org.apache.usergrid.persistence.index.IndexAlias;
+import org.apache.usergrid.persistence.index.IndexEdge;
+import org.apache.usergrid.persistence.index.IndexLocationStrategy;
+import org.apache.usergrid.persistence.index.SearchEdge;
 import org.apache.usergrid.persistence.index.utils.IndexValidationUtils;
-import org.apache.usergrid.persistence.map.MapManager;
 import org.apache.usergrid.persistence.model.entity.Entity;
 import org.apache.usergrid.persistence.model.entity.Id;
-import org.apache.usergrid.persistence.model.entity.SimpleId;
 
 
 public class EsEntityIndexBatchImpl implements EntityIndexBatch {