You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by ro...@apache.org on 2014/11/13 02:09:09 UTC

[1/8] incubator-usergrid git commit: organized rest IT

Repository: incubator-usergrid
Updated Branches:
  refs/heads/two-dot-o-rest-refactor 66b8ecb9e -> c41e920bb


http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/UserResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/UserResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/UserResourceIT.java
deleted file mode 100644
index 5eb7f28..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/UserResourceIT.java
+++ /dev/null
@@ -1,1418 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.java.client.Client.Query;
-import org.apache.usergrid.java.client.entities.Activity;
-import org.apache.usergrid.java.client.entities.Activity.ActivityObject;
-import org.apache.usergrid.java.client.entities.Entity;
-import org.apache.usergrid.java.client.entities.User;
-import org.apache.usergrid.java.client.response.ApiResponse;
-
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.management.ApplicationInfo;
-import org.apache.usergrid.management.OrganizationInfo;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.applications.utils.UserRepo;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import com.sun.jersey.api.client.ClientResponse.Status;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.apache.usergrid.rest.applications.utils.TestUtils.getIdFromSearchResults;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-
-/**
- * @author zznate
- * @author tnine
- */
-@Concurrent()
-public class UserResourceIT extends AbstractRestIT {
-
-    private static Logger log = LoggerFactory.getLogger( UserResourceIT.class );
-
-
-    @Test
-    public void usernameQuery() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "username = 'unq_user*'";
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user1" ), getIdFromSearchResults( node, 0 ) );
-        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user2" ), getIdFromSearchResults( node, 1 ) );
-        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user3" ), getIdFromSearchResults( node, 2 ) );
-    }
-
-
-    @Test
-    public void nameQuery() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "name = 'John*'";
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( UserRepo.INSTANCE.getByUserName( "user2" ), getIdFromSearchResults( node, 0 ) );
-        assertEquals( UserRepo.INSTANCE.getByUserName( "user3" ), getIdFromSearchResults( node, 1 ) );
-    }
-
-
-    @Test
-    public void nameQueryByUUIDs() throws Exception {
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "select uuid name = 'John*'";
-
-        ApplicationInfo appInfo = setup.getMgmtSvc().getApplicationInfo( "test-organization/test-app" );
-        OrganizationInfo orgInfo = setup.getMgmtSvc().getOrganizationByName( "test-organization" );
-
-        resource().path( "/" + orgInfo.getUuid() + "/" + appInfo.getId() + "/users" ).queryParam( "ql", ql )
-                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
-    }
-
-
-    @Test
-    public void nameFullTextQuery() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "name contains 'Smith' order by name ";
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( UserRepo.INSTANCE.getByUserName( "user1" ), getIdFromSearchResults( node, 0 ) );
-        assertEquals( UserRepo.INSTANCE.getByUserName( "user2" ), getIdFromSearchResults( node, 1 ) );
-        assertEquals( UserRepo.INSTANCE.getByUserName( "user3" ), getIdFromSearchResults( node, 2 ) );
-    }
-
-
-    /**
-     * Tests that when a full text index is run on a field that isn't full text indexed an error is thrown
-     */
-    @Ignore("No longer relevant because all text fields are full-text indexed with Core Persistence")
-    @Test(expected = UniformInterfaceException.class)
-    public void fullTextQueryNotFullTextIndexed() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "username contains 'user' ";
-
-        resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
-    }
-
-
-    /**
-     * Tests that when a full text index is run on a field that isn't full text indexed an error is thrown
-     */
-    @Ignore("This test is being ignored as users ")
-    @Test(expected = UniformInterfaceException.class)
-    public void fullQueryNotIndexed() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        String ql = "picture = 'foo' ";
-
-        resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
-    }
-
-
-    /**
-     * Test that when activity is pushed with not actor, it's set to the user who created it
-     */
-    @Test
-    public void emtpyActorActivity() throws IOException {
-        UserRepo.INSTANCE.load( resource(), access_token );
-        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
-        refreshIndex("test-organization", "test-app");
-
-        Activity activity = new Activity();
-        activity.setProperty( "email", "rod@rodsimpson.com" );
-        activity.setProperty( "verb", "POST" );
-        activity.setProperty( "content", "Look! more new content" );
-
-        ApiResponse response = client.postUserActivity( userId.toString(), activity );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        Entity entity = response.getEntities().get( 0 );
-
-        UUID activityId = entity.getUuid();
-
-        assertNotNull( activityId );
-
-        JsonNode actor = getActor( entity );
-
-        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
-
-        assertEquals( userId, actorId );
-
-        assertEquals( "user1@apigee.com", actor.get( "email" ).asText() );
-    }
-
-
-    /**
-     * Insert the uuid and email if they're empty in the request
-     */
-    @Test
-    public void noUUIDorEmail() throws IOException {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
-
-        Activity activity = new Activity();
-        activity.setProperty( "email", "rod@rodsimpson.com" );
-        activity.setProperty( "verb", "POST" );
-        activity.setProperty( "content", "Look! more new content" );
-
-        // same as above, but with actor partially filled out
-
-        ActivityObject actorPost = new ActivityObject();
-        actorPost.setDisplayName( "Dino" );
-
-        activity.setActor( actorPost );
-
-        ApiResponse response = client.postUserActivity( userId.toString(), activity );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        Entity entity = response.getEntities().get( 0 );
-
-        UUID activityId = entity.getUuid();
-
-        assertNotNull( activityId );
-
-        JsonNode actor = getActor( entity );
-
-        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
-
-        assertEquals( userId, actorId );
-
-        assertEquals( "user1@apigee.com", actor.get( "email" ).asText() );
-    }
-
-
-    /**
-     * Don't touch the UUID when it's already set in the JSON
-     */
-    @Test
-    public void ignoreUUIDandEmail() throws IOException {
-        UserRepo.INSTANCE.load( resource(), access_token );
-        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
-        refreshIndex("test-organization", "test-app");
-
-        UUID testUUID = UUIDUtils.newTimeUUID();
-        String testEmail = "foo@bar.com";
-
-        // same as above, but with actor partially filled out
-        Activity activity = new Activity();
-        activity.setProperty( "email", "rod@rodsimpson.com" );
-        activity.setProperty( "verb", "POST" );
-        activity.setProperty( "content", "Look! more new content" );
-
-        // same as above, but with actor partially filled out
-
-        ActivityObject actorPost = new ActivityObject();
-        actorPost.setDisplayName( "Dino" );
-        actorPost.setUuid( testUUID );
-        actorPost.setDynamicProperty( "email", testEmail );
-
-        activity.setActor( actorPost );
-
-        ApiResponse response = client.postUserActivity( userId.toString(), activity );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        Entity entity = response.getEntities().get( 0 );
-
-        UUID activityId = entity.getUuid();
-
-        assertNotNull( activityId );
-
-        JsonNode actor = getActor( entity );
-
-        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
-
-        assertEquals( testUUID, actorId );
-
-        assertEquals( testEmail, actor.get( "email" ).asText() );
-    }
-
-
-    /**
-     * Test that when activity is pushed with not actor, it's set to the user who created it
-     */
-    @Test
-    public void userActivitiesDefaultOrder() throws IOException {
-        UserRepo.INSTANCE.load( resource(), access_token );
-        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
-        refreshIndex("test-organization", "test-app");
-
-        Activity activity = new Activity();
-        activity.setProperty( "email", "rod@rodsimpson.com" );
-        activity.setProperty( "verb", "POST" );
-        activity.setProperty( "content", "activity 1" );
-
-        ApiResponse response = client.postUserActivity( userId.toString(), activity );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        Entity entity = response.getFirstEntity();
-
-        UUID firstActivityId = entity.getUuid();
-
-        activity = new Activity();
-        activity.setProperty( "email", "rod@rodsimpson.com" );
-        activity.setProperty( "verb", "POST" );
-        activity.setProperty( "content", "activity 2" );
-
-        response = client.postUserActivity( userId.toString(), activity );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        entity = response.getFirstEntity();
-
-        UUID secondActivityId = entity.getUuid();
-
-        Query query = client.queryActivity();
-
-        entity = query.getResponse().getEntities().get( 0 );
-
-        assertEquals( secondActivityId, entity.getUuid() );
-
-        entity = query.getResponse().getEntities().get( 1 );
-
-        assertEquals( firstActivityId, entity.getUuid() );
-    }
-
-
-    @Test
-    public void getUserWIthEmailUsername() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username = "username-email" + "@usergrid.org";
-        String name = "name" + id;
-        String email = "email" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username, name, email, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        Entity userEntity = response.getEntities().get( 0 );
-
-        // get the user with username property that has an email value
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + username )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( username, node.get( "entities" ).get( 0 ).get( "username" ).asText() );
-        assertEquals( name, node.get( "entities" ).get( 0 ).get( "name" ).asText() );
-        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).asText() );
-
-        // get the user with email property value
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + email )
-                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( username, node.get( "entities" ).get( 0 ).get( "username" ).asText() );
-        assertEquals( name, node.get( "entities" ).get( 0 ).get( "name" ).asText() );
-        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).asText() );
-    }
-
-
-    /**
-     * Tests that when querying all users, we get the same result size when using "order by"
-     */
-    @Test
-    public void resultSizeSame() throws IOException {
-        UserRepo.INSTANCE.load( resource(), access_token );
-
-        refreshIndex("test-organization", "test-app");
-
-        UUID userId1 = UserRepo.INSTANCE.getByUserName( "user1" );
-        UUID userId2 = UserRepo.INSTANCE.getByUserName( "user2" );
-        UUID userId3 = UserRepo.INSTANCE.getByUserName( "user3" );
-
-        Query query = client.queryUsers();
-
-        ApiResponse response = query.getResponse();
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        int nonOrderedSize = response.getEntities().size();
-
-        query = client.queryUsers( "order by username" );
-
-        response = query.getResponse();
-
-        int orderedSize = response.getEntities().size();
-
-        assertEquals( "Sizes match", nonOrderedSize, orderedSize );
-
-        int firstEntityIndex = getEntityIndex( userId1, response );
-
-        int secondEntityIndex = getEntityIndex( userId2, response );
-
-        int thirdEntityIndex = getEntityIndex( userId3, response );
-
-        assertTrue( "Ordered correctly", firstEntityIndex < secondEntityIndex );
-
-        assertTrue( "Ordered correctly", secondEntityIndex < thirdEntityIndex );
-    }
-
-
-    private int getEntityIndex( UUID entityId, ApiResponse response ) {
-        List<Entity> entities = response.getEntities();
-
-        for ( int i = 0; i < entities.size(); i++ ) {
-            if ( entityId.equals( entities.get( i ).getUuid() ) ) {
-                return i;
-            }
-        }
-
-        return -1;
-    }
-
-
-    @Test
-    public void clientNameQuery() {
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username = "username" + id;
-        String name = "name" + id;
-
-        ApiResponse response = client.createUser( username, name, id + "@usergrid.org", "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID createdId = response.getEntities().get( 0 ).getUuid();
-
-        Query results = client.queryUsers( String.format( "name = '%s'", name ) );
-        User user = results.getResponse().getEntities( User.class ).get( 0 );
-
-        assertEquals( createdId, user.getUuid() );
-    }
-
-
-    @Test
-    public void deleteUser() throws IOException  {
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username = "username" + id;
-        String name = "name" + id;
-
-        ApiResponse response = client.createUser( username, name, id + "@usergrid.org", "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID createdId = response.getEntities().get( 0 ).getUuid();
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        assertNull( node.get( "errors" ) );
-
-        Query results = client.queryUsers( String.format( "username = '%s'", name ) );
-        assertEquals( 0, results.getResponse().getEntities( User.class ).size() );
-
-        // now create that same user again, it should work
-        response = client.createUser( username, name, id + "@usergrid.org", "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        createdId = response.getEntities().get( 0 ).getUuid();
-
-        assertNotNull( createdId );
-    }
-
-
-    @Test
-    public void singularCollectionName() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username = "username1" + id;
-        String name = "name1" + id;
-        String email = "email1" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username, name, email, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        username = "username2" + id;
-        name = "name2" + id;
-        email = "email2" + id + "@usergrid.org";
-
-        response = client.createUser( username, name, email, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        // now create a connection of "likes" between the first user and the
-        // second using pluralized form
-
-        // plural collection name
-        String path = String.format( "/test-organization/test-app/users/%s/conn1/%s", firstCreatedId, secondCreatedId );
-
-        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-        // singular collection name
-        path = String.format( "/test-organization/test-app/user/%s/conn2/%s", firstCreatedId, secondCreatedId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-        path = String.format( "/test-organization/test-app/users/%s/conn1", firstCreatedId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        path = String.format( "/test-organization/test-app/user/%s/conn1", firstCreatedId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        path = String.format( "/test-organization/test-app/users/%s/conn2", firstCreatedId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        path = String.format( "/test-organization/test-app/user/%s/conn2", firstCreatedId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-    }
-
-
-    @Test
-    public void connectionByNameAndType() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username1 = "username1" + id;
-        String name1 = "name1" + id;
-        String email1 = "email1" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username1, name1, email1, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        String username2 = "username2" + id;
-        String name2 = "name2" + id;
-        String email2 = "email2" + id + "@usergrid.org";
-
-        response = client.createUser( username2, name2, email2, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        // now create a connection of "likes" between the first user and the
-        // second using pluralized form
-
-        // named entity in collection name
-        String path = String.format( "/test-organization/test-app/users/%s/conn1/users/%s", firstCreatedId, username2 );
-
-        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        // named entity in collection name
-        path = String.format( "/test-organization/test-app/users/%s/conn2/users/%s", username1, username2 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-    }
-
-
-    /**
-     * Usergrid-1222 test
-     */
-    @Test
-    public void connectionQuerybyEmail() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String name = "name1" + id;
-        String email = "email1" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( email, name, email, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID userId = response.getEntities().get( 0 ).getUuid();
-
-        Entity role = new Entity( "role" );
-        role.setProperty( "name", "connectionQuerybyEmail1" );
-
-        response = client.createEntity( role );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        UUID roleId1 = response.getEntities().get( 0 ).getUuid();
-
-        //add permissions to the role
-
-        Map<String, String> perms = new HashMap<String, String>();
-        perms.put( "permission", "get:/stuff/**" );
-
-        String path = String.format( "/test-organization/test-app/roles/%s/permissions", roleId1 );
-
-        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, perms ));
-
-
-        //Create the second role
-        role = new Entity( "role" );
-        role.setProperty( "name", "connectionQuerybyEmail2" );
-
-        response = client.createEntity( role );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        UUID roleId2 = response.getEntities().get( 0 ).getUuid();
-
-        //add permissions to the role
-
-        perms = new HashMap<String, String>();
-        perms.put( "permission", "get:/stuff/**" );
-
-        path = String.format( "/test-organization/test-app/roles/%s/permissions", roleId2 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, perms ));
-
-        refreshIndex("test-organization", "test-app");
-
-        //connect the entities where role is the root
-        path = String.format( "/test-organization/test-app/roles/%s/users/%s", roleId1, userId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        // now create a connection of "likes" between the first user and the
-        // second using pluralized form
-
-        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-
-        //connect the second role
-        path = String.format( "/test-organization/test-app/roles/%s/users/%s", roleId2, userId );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-
-        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-        //query the second role, it should work
-        path = String.format( "/test-organization/test-app/roles/%s/users", roleId2 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
-                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .get( String.class ));
-
-        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-
-        //query the first role, it should work
-        path = String.format( "/test-organization/test-app/roles/%s/users", roleId1 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
-                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .get( String.class ));
-
-        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-
-        //now delete the first role
-        path = String.format( "/test-organization/test-app/roles/%s", roleId1 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        //query the first role, it should 404
-        path = String.format( "/test-organization/test-app/roles/%s/users", roleId1 );
-
-        refreshIndex("test-organization", "test-app");
-
-        try {
-            node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
-                             .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .get( String.class ));
-        }
-        catch ( UniformInterfaceException e ) {
-            assertEquals( Status.NOT_FOUND, e.getResponse().getClientResponseStatus() );
-        }
-
-        //query the second role, it should work
-        path = String.format( "/test-organization/test-app/roles/%s/users", roleId2 );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
-                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .get( String.class ));
-
-        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-    }
-
-
-    @Test
-    public void connectionByNameAndDynamicType() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username1 = "username1" + id;
-        String name1 = "name1" + id;
-        String email1 = "email1" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username1, name1, email1, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        String name = "pepperoni";
-
-        Entity pizza = new Entity();
-        pizza.setProperty( "name", name );
-        pizza.setType( "pizza" );
-
-        response = client.createEntity( pizza );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
-
-        refreshIndex("test-organization", "test-app");
-
-        // now create a connection of "likes" between the first user and the
-        // second using pluralized form
-
-        // named entity in collection name
-        String path = String.format( "/test-organization/test-app/users/%s/conn1/pizzas/%s", firstCreatedId,
-                secondCreatedId );
-
-        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-        // named entity in collection name
-        path = String.format( "/test-organization/test-app/users/%s/conn2/pizzas/%s", username1, name );
-
-        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
-    }
-
-
-    @Test
-    public void nameUpdate() throws IOException {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String username = "username" + id;
-        String name = "name" + id;
-        String email = "email" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username, name, email, "password" );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        Entity userEntity = response.getEntities().get( 0 );
-
-        // attempt to log in
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/token" ).queryParam( "username", username )
-                                  .queryParam( "password", "password" ).queryParam( "grant_type", "password" )
-                                  .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                                  .get( String.class ));
-
-        assertEquals( username, node.get( "user" ).get( "username" ).asText() );
-        assertEquals( name, node.get( "user" ).get( "name" ).asText() );
-        assertEquals( email, node.get( "user" ).get( "email" ).asText() );
-
-        // now update the name and email
-        String newName = "newName";
-        String newEmail = "newEmail" + UUIDUtils.newTimeUUID() + "@usergrid.org";
-
-        userEntity.setProperty( "name", newName );
-        userEntity.setProperty( "email", newEmail );
-        userEntity.setProperty( "password", "newp2ssword" );
-        userEntity.setProperty( "pin", "newp1n" );
-
-        node = mapper.readTree( resource().path( String.format( "/test-organization/test-app/users/%s", username ) )
-                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, userEntity.getProperties() ));
-
-        refreshIndex("test-organization", "test-app");
-
-        // now see if we've updated
-        node = mapper.readTree( resource().path( "/test-organization/test-app/token" ).queryParam( "username", username )
-                         .queryParam( "password", "password" ).queryParam( "grant_type", "password" )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .get( String.class ));
-
-        assertEquals( username, node.get( "user" ).get( "username" ).asText() );
-        assertEquals( newName, node.get( "user" ).get( "name" ).asText() );
-        assertEquals( newEmail, node.get( "user" ).get( "email" ).asText() );
-        assertNull( newEmail, node.get( "user" ).get( "password" ) );
-        assertNull( newEmail, node.get( "user" ).get( "pin" ) );
-    }
-
-
-    /**
-     *
-     * @return
-     */
-    public JsonNode getActor( Entity entity ) {
-        return entity.getProperties().get( "actor" );
-    }
-
-
-    @Test
-    public void test_POST_batch() throws IOException {
-
-        log.info( "UserResourceIT.test_POST_batch" );
-
-        JsonNode node = null;
-
-        List<Map<String, Object>> batch = new ArrayList<Map<String, Object>>();
-
-        Map<String, Object> properties = new LinkedHashMap<String, Object>();
-        properties.put( "username", "test_user_1" );
-        properties.put( "email", "user1@test.com" );
-        batch.add( properties );
-
-        properties = new LinkedHashMap<String, Object>();
-        properties.put( "username", "test_user_2" );
-        batch.add( properties );
-
-        properties = new LinkedHashMap<String, Object>();
-        properties.put( "username", "test_user_3" );
-        batch.add( properties );
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "access_token", access_token )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .post( String.class, batch ));
-
-        assertNotNull( node );
-        logNode( node );
-    }
-
-
-    @Test
-    public void deactivateUser() throws IOException {
-
-        UUID newUserUuid = UUIDUtils.newTimeUUID();
-
-        String userName = String.format( "test%s", newUserUuid );
-
-        Map<String, String> payload =
-                hashMap( "email", String.format( "%s@anuff.com", newUserUuid ) ).map( "username", userName )
-                                                                                .map( "name", "Ed Anuff" )
-                                                                                .map( "password", "sesame" )
-                                                                                .map( "pin", "1234" );
-
-        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
-                  .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                  .post( String.class, payload );
-
-        refreshIndex("test-organization", "test-app");
-
-        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
-                          .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                          .get( String.class ));
-
-        // disable the user
-
-        Map<String, String> data = new HashMap<String, String>();
-
-        response = mapper.readTree( resource().path( String.format( "/test-organization/test-app/users/%s/deactivate", userName ) )
-                             .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                             .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-
-        JsonNode entity = getEntity( response, 0 );
-
-        assertFalse( entity.get( "activated" ).asBoolean() );
-        assertNotNull( entity.get( "deactivated" ) );
-    }
-
-
-    @Test
-    public void test_PUT_password_fail() {
-
-        boolean fail = false;
-        try {
-            ApiResponse changeResponse = client.changePassword( "edanuff", "foo", "bar" );
-            fail = changeResponse.getError() != null;
-        }
-        catch ( Exception e ) {
-            fail = true;
-        }
-        assertTrue( fail );
-    }
-
-
-    @Test
-    public void test_GET_user_ok() throws InterruptedException, IOException {
-
-        // TODO figure out what is being overridden? why 400?
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" )
-                .queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE )
-                .get( String.class ));
-
-        String uuid = node.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
-        String email = node.get( "entities" ).get( 0 ).get( "email" ).textValue();
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + uuid )
-                .queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE )
-                .get( String.class ));
-        
-        logNode( node );
-        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).textValue() );
-    }
-
-
-    @Test
-    public void test_PUT_password_ok() {
-
-        ApiResponse response = client.changePassword( "edanuff", "sesame", "sesame1" );
-
-        assertNull( response.getError() );
-
-        response = client.authorizeAppUser( "ed@anuff.com", "sesame1" );
-
-        assertNull( response.getError() );
-
-        // if this was successful, we need to re-set the password for other
-        // tests
-        response = client.changePassword( "edanuff", "sesame1", "sesame" );
-
-        assertNull( response.getError() );
-    }
-
-
-    @Test
-    public void setUserPasswordAsAdmin()  throws IOException {
-
-        String newPassword = "foo";
-
-        Map<String, String> data = new HashMap<String, String>();
-        data.put( "newpassword", newPassword );
-
-        // change the password as admin. The old password isn't required
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/password" )
-                                  .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-
-        assertNull( getError( node ) );
-
-        ApiResponse response = client.authorizeAppUser( "ed@anuff.com", newPassword );
-
-        assertNull( response.getError() );
-    }
-
-
-    @Test
-    public void passwordMismatchErrorUser() {
-        String origPassword = "foo";
-        String newPassword = "bar";
-
-        Map<String, String> data = new HashMap<String, String>();
-        data.put( "newpassword", origPassword );
-
-        // now change the password, with an incorrect old password
-
-        data.put( "oldpassword", origPassword );
-        data.put( "newpassword", newPassword );
-
-        Status responseStatus = null;
-        try {
-            resource().path( "/test-organization/test-app/users/edanuff/password" ).accept( MediaType.APPLICATION_JSON )
-                      .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data );
-        }
-        catch ( UniformInterfaceException uie ) {
-            responseStatus = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertNotNull( responseStatus );
-
-        assertEquals( Status.BAD_REQUEST, responseStatus );
-    }
-
-
-    @Test
-    public void addRemoveRole() throws IOException  {
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String roleName = "rolename" + id;
-
-        String username = "username" + id;
-        String name = "name" + id;
-        String email = "email" + id + "@usergrid.org";
-
-        ApiResponse response = client.createUser( username, name, email, "password" );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-        refreshIndex("test-organization", "test-app");
-
-        UUID createdId = response.getEntities().get( 0 ).getUuid();
-
-        // create Role
-
-        String json = "{\"title\":\"" + roleName + "\",\"name\":\"" + roleName + "\"}";
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" )
-            .queryParam( "access_token", access_token )
-            .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-            .post( String.class, json ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        // add Role
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles/" + roleName )
-            .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-            .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-        assertNotNull( node.get( "entities" ) );
-        assertNotNull( node.get( "entities" ).get( 0 ) );
-        assertNotNull( node.get( "entities" ).get( 0 ).get( "name" ) );
-        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles" )
-            .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-            .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertNotNull( node.get( "entities" ) );
-        assertNotNull( node.get( "entities" ).get( 0 ) );
-        assertNotNull( node.get( "entities" ).get( 0 ).get( "name" ) );
-        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
-
-
-        // remove Role
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles/" + roleName )
-                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles" )
-                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "entities" ).size() == 0 );
-    }
-
-
-    @Test
-    public void revokeToken() throws Exception {
-
-        String token1 = super.userToken( "edanuff", "sesame" );
-        String token2 = super.userToken( "edanuff", "sesame" );
-
-        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token1 )
-                          .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                          .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token2 )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        // now revoke the tokens
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/revoketokens" )
-                             .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
-                             .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        // the tokens shouldn't work
-
-        Status status = null;
-
-        try {
-            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token1 )
-                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                              .get( String.class ));
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        status = null;
-
-        try {
-            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token2 )
-                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                              .get( String.class ));
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        String token3 = super.userToken( "edanuff", "sesame" );
-        String token4 = super.userToken( "edanuff", "sesame" );
-
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token3 )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token4 )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        // now revoke the token3
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/revoketoken" )
-                             .queryParam( "access_token", token3 ).queryParam( "token", token3 )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .post( String.class ));
-
-        // the token3 shouldn't work
-
-        status = null;
-
-        try {
-            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token3 )
-                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                              .get( String.class ));
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        status = null;
-
-        try {
-            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token4 )
-                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                              .get( String.class ));
-
-            status = Status.OK;
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.OK, status );
-    }
-
-
-    @Test
-    public void getToken() throws Exception {
-
-        createUser( "test_1", "test_1@test.com", "test123", "Test1 User" ); // client.setApiUrl(apiUrl);
-        createUser( "test_2", "test_2@test.com", "test123", "Test2 User" ); // client.setApiUrl(apiUrl);
-        createUser( "test_3", "test_3@test.com", "test123", "Test3 User" ); // client.setApiUrl(apiUrl);
-        refreshIndex("test-organization", "test-app");
-
-        ApplicationInfo appInfo = setup.getMgmtSvc().getApplicationInfo( "test-organization/test-app" );
-
-        String clientId = setup.getMgmtSvc().getClientIdForApplication( appInfo.getId() );
-        String clientSecret = setup.getMgmtSvc().getClientSecretForApplication( appInfo.getId() );
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1/token" ).queryParam( "client_id", clientId )
-                          .queryParam( "client_secret", clientSecret ).accept( MediaType.APPLICATION_JSON )
-                          .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        String user_token_from_client_credentials = node.get( "access_token" ).asText();
-
-        UUID userId = UUID.fromString( node.get( "user" ).get( "uuid" ).asText() );
-        setup.getMgmtSvc().activateAppUser( appInfo.getId(), userId );
-
-        String user_token_from_java = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userId, 1000000 );
-
-        assertNotNull( user_token_from_client_credentials );
-
-        refreshIndex("test-organization", "test-app");
-
-        Status status = null;
-
-        // bad access token
-        try {
-            resource().path( "/test-organization/test-app/users/test_1/token" ).queryParam( "access_token", "blah" )
-                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                      .get( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-            log.info( "Error Response Body: " + uie.getResponse().getEntity( String.class ) );
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        try {
-            resource().path( "/test-organization/test-app/users/test_2/token" )
-                      .queryParam( "access_token", user_token_from_client_credentials )
-                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                      .get( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-            log.info( "Error Response Body: " + uie.getResponse().getEntity( String.class ) );
-        }
-
-        assertEquals( Status.FORBIDDEN, status );
-
-
-        JsonNode response = null;
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1" )
-                             .queryParam( "access_token", user_token_from_client_credentials )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1" )
-                             .queryParam( "access_token", user_token_from_java ).accept( MediaType.APPLICATION_JSON )
-                             .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-
-        setup.getMgmtSvc().deactivateUser( appInfo.getId(), userId );
-
-        refreshIndex("test-organization", "test-app");
-
-        try {
-            resource().path( "/test-organization/test-app/token" ).queryParam( "grant_type", "password" )
-                      .queryParam( "username", "test_1" ).queryParam( "password", "test123" )
-                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                      .get( String.class );
-            fail( "request for deactivated user should fail" );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-            JsonNode body = mapper.readTree( uie.getResponse().getEntity( String.class ));
-            assertEquals( "user not activated", body.findPath( "error_description" ).textValue() );
-        }
-    }
-
-
-    @Test
-    public void delegatePutOnNotFound() throws Exception {
-        String randomName = "user1_" + UUIDUtils.newTimeUUID().toString();
-        createUser( randomName, randomName + "@apigee.com", "password", randomName );
-        refreshIndex("test-organization", "test-app");
-
-        // should update a field
-        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" + randomName )
-                                      .queryParam( "access_token", adminAccessToken )
-                                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                                      .get( String.class ));
-        logNode( response );
-        assertNotNull( getEntity( response, 0 ) );
-        // PUT on user
-
-        // PUT a new user
-        randomName = "user2_" + UUIDUtils.newTimeUUID().toString();
-        Map<String, String> payload =
-                hashMap( "email", randomName + "@apigee.com" ).map( "username", randomName ).map( "name", randomName )
-                                                              .map( "password", "password" ).map( "pin", "1234" );
-
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", adminAccessToken )
-                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                             .put( String.class, payload ));
-
-        refreshIndex("test-organization", "test-app");
-
-        logNode( response );
-        response = mapper.readTree( resource().path( "/test-organization/test-app/users/" + randomName )
-                             .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
-                             .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-        logNode( response );
-    }
-
-
-    /**
-     * Test that property queries return properties and entity queries return entities.
-     * https://apigeesc.atlassian.net/browse/USERGRID-1715?
-     */
-    @Test
-    public void queryForUuids() throws Exception {
-
-        {
-            final JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "ql",
-                    "select *" )               // query for entities
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-            assertNotNull( "Entities must exist", response.get( "entities" ) );
-            assertTrue( "Must be some entities", response.get( "entities" ).size() > 0 );
-            assertEquals( "Must be users", "user", response.get( "entities" ).get( 0 ).get( "type" ).asText() );
-            assertNull( "List must not exist", response.get( "list" ) );
-        }
-
-        {
-            final JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "ql",
-                    "select uuid" )            // query for uuid properties
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-            assertNotNull( "List must exist", response.get( "list" ) );
-            assertTrue( "Must be some list items", response.get( "list" ).size() > 0 );
-            assertNull( "Entities must not exist", response.get( "entries" ) );
-        }
-    }
-
-
-    @Test
-    public void queryForUserUuids() throws Exception {
-
-        UserRepo.INSTANCE.load( resource(), access_token );
-        refreshIndex("test-organization", "test-app");
-
-        Status status = null;
-
-
-        String ql = "uuid = " + UserRepo.INSTANCE.getByUserName( "user1" );
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
-                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-
-        Map<String, String> payload = hashMap( "name", "Austin" ).map( "state", "TX" );
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/curts" ).queryParam( "access_token", access_token )
-                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                         .post( String.class, payload ));
-
-        UUID userId = UUID.fromString( node.get( "entities" ).get( 0 ).get( "uuid" ).asText() );
-
-        assertNotNull( userId );
-
-        refreshIndex("test-organization", "test-app");
-
-        ql = "uuid = " + userId;
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/curts" ).queryParam( "ql", ql )
-                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertNotNull( node.get( "entities" ).get( 0 ).get( "uuid" ) );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/extensions/TestResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/extensions/TestResource.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/extensions/TestResource.java
deleted file mode 100644
index e50d905..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/extensions/TestResource.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users.extensions;
-
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-
-import org.junit.Ignore;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-import org.apache.usergrid.rest.applications.users.AbstractUserExtensionResource;
-
-
-@Ignore("Not a test")
-@Component("org.apache.usergrid.rest.applications.users.extensions.TestResource")
-@Scope("prototype")
-@Produces(MediaType.APPLICATION_JSON)
-public class TestResource extends AbstractUserExtensionResource {
-
-    private static Logger log = LoggerFactory.getLogger( TestResource.class );
-
-
-    public TestResource() {
-        log.info( "TestResource" );
-    }
-
-
-    @GET
-    public String sayHello() {
-        return "{\"message\" : \"hello\"" + ( getUserResource().getUserUuid() != null ?
-                                              ", \"user\" : \"" + getUserResource().getUserUuid() + "\"" : "" ) + " }";
-    }
-}


[3/8] incubator-usergrid git commit: organized rest IT

Posted by ro...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/MatrixQueryTests.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/MatrixQueryTests.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/MatrixQueryTests.java
new file mode 100644
index 0000000..25bc33b
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/MatrixQueryTests.java
@@ -0,0 +1,202 @@
+/*
+ * 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.queries;
+
+import java.util.Map;
+import java.util.UUID;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+import org.apache.usergrid.rest.test.resource.app.UsersCollection;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+import org.junit.Rule;
+import org.junit.Test;
+
+
+public class MatrixQueryTests extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    public void simpleMatrix() throws Exception {
+
+        /**
+         * Create 3 users which we will use for sub searching
+         */
+        UsersCollection users = context.users();
+
+        Map user1 =
+                hashMap( "username", "user1" ).map( "email", "testuser1@usergrid.com" ).map( "fullname", "Bob Smith" );
+
+        users.create( user1 );
+
+
+        Map user2 =
+                hashMap( "username", "user2" ).map( "email", "testuser2@usergrid.com" ).map( "fullname", "Fred Smith" );
+
+        users.create( user2 );
+
+
+        Map user3 = hashMap( "username", "user3" ).map( "email", "testuser3@usergrid.com" )
+                .map( "fullname", "Frank Grimes" );
+
+        users.create( user3 );
+
+
+        //now create 4 restaurants
+
+        CustomCollection restaurants = context.collection( "restaurants" );
+
+
+        Map restaurant1 = hashMap( "name", "Old Major" );
+
+        UUID restaurant1Id = getEntityId( restaurants.create( restaurant1 ), 0 );
+
+        Map restaurant2 = hashMap( "name", "tag" );
+
+        UUID restaurant2Id = getEntityId( restaurants.create( restaurant2 ), 0 );
+
+        Map restaurant3 = hashMap( "name", "Squeaky Bean" );
+
+        UUID restaurant3Id = getEntityId( restaurants.create( restaurant3 ), 0 );
+
+        Map restaurant4 = hashMap( "name", "Lola" );
+
+        UUID restaurant4Id = getEntityId( restaurants.create( restaurant4 ), 0 );
+
+
+        //now like our 3 users
+
+
+        //user 1 likes old major
+        users.user( "user1" ).connection( "likes" ).entity( restaurant1Id ).post();
+
+        users.user( "user1" ).connection( "likes" ).entity( restaurant2Id ).post();
+
+
+        //user 2 likes tag and squeaky bean
+        users.user( "user2" ).connection( "likes" ).entity( restaurant2Id ).post();
+
+        users.user( "user2" ).connection( "likes" ).entity( restaurant3Id ).post();
+
+        //user 3 likes  Lola (it shouldn't appear in the results)
+
+        users.user( "user3" ).connection( "likes" ).entity( restaurant4Id ).post();
+
+
+        //now query with matrix params
+
+
+//        JsonNode testGetUsers = context.collection( "users" ).get().get( "entities" );
+//
+//        JsonNode likesNode =
+//                context.collection( "users" ).entity( "user1" ).connection( "likes" ).get().get( "entities" );
+//
+//
+//        JsonNode queryResponse = context.collection( "users" ).withMatrix(
+//                hashMap( "ql", "where fullname contains 'Smith'" ).map( "limit", "1000" ) ).connection( "likes" ).get();
+//
+//        assertEquals( "Old Major", getEntityName( queryResponse, 0 ) );
+//
+//        assertEquals( "tag", getEntityName( queryResponse, 1 ) );
+//
+//        assertEquals( "Squeaky Bean", getEntityName( queryResponse, 2 ) );
+//
+//        /**
+//         * No additional elements in the response
+//         */
+//        assertNull( getEntity( queryResponse, 3 ) );
+    }
+
+
+//    @Test
+//    public void largeRootElements() {
+//
+//
+//        // create 4 restaurants
+//
+//        CustomCollection restaurants = context.collection( "restaurants" );
+//
+//
+//        Map restaurant1 = hashMap( "name", "Old Major" );
+//
+//        UUID restaurant1Id = getEntityId( restaurants.create( restaurant1 ), 0 );
+//
+//        Map restaurant2 = hashMap( "name", "tag" );
+//
+//        UUID restaurant2Id = getEntityId( restaurants.create( restaurant2 ), 0 );
+//
+//        Map restaurant3 = hashMap( "name", "Squeaky Bean" );
+//
+//        UUID restaurant3Id = getEntityId( restaurants.create( restaurant3 ), 0 );
+//
+//
+//        /**
+//         * Create 3 users which we will use for sub searching
+//         */
+//        UsersCollection users = context.users();
+//
+//
+//        int max = 1000;
+//        int count = ( int ) (max * 1.1);
+//
+//        for ( int i = 0; i < count; i++ ) {
+//
+//            String username = "user" + i;
+//            String email = username + "@usergrid.com";
+//
+//            Map user1 = hashMap( "username", username ).map( "email", email ).map( "fullname", i + " Smith" );
+//
+//            users.create( user1 );
+//
+//            /**
+//             * Change our links every other time.  This way we should get all 3
+//             */
+//
+//            if ( i % 2 == 0 ) {
+//                users.user( username ).connection( "likes" ).entity( restaurant1Id ).post();
+//
+//                users.user( username ).connection( "likes" ).entity( restaurant2Id ).post();
+//            }
+//            else {
+//
+//                users.user( username ).connection( "likes" ).entity( restaurant2Id ).post();
+//
+//                users.user( username ).connection( "likes" ).entity( restaurant3Id ).post();
+//            }
+//        }
+//
+//
+//
+//        //set our limit to 1k.  We should get only 3 results, but this should run
+//        JsonNode queryResponse = context.collection( "users" ).withMatrix(
+//                hashMap( "ql", "where fullname contains 'Smith'" ).map( "limit", "1000" ) ).connection( "likes" ).get();
+//
+//        assertEquals( "Old Major", getEntityName( queryResponse, 0 ) );
+//
+//        assertEquals( "tag", getEntityName( queryResponse, 1 ) );
+//
+//        assertEquals( "Squeaky Bean", getEntityName( queryResponse, 2 ) );
+//
+//        /**
+//         * No additional elements in the response
+//         */
+//        assertNull( getEntity( queryResponse, 3 ) );
+//    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/OrderByTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/OrderByTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/OrderByTest.java
new file mode 100644
index 0000000..481f753
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/OrderByTest.java
@@ -0,0 +1,172 @@
+/*
+ * 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.queries;
+
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import static org.junit.Assert.assertEquals;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class OrderByTest extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    // USERGRID-1400
+    public void orderByShouldNotAffectResults() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        long created = 0;
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+        for ( int i = 0; i < 20; i++ ) {
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+            if ( i == 5 ) {
+                created = activity.findValue( "created" ).longValue();
+            }
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where created > " + created;
+        JsonNode node = activities.withQuery( query ).get();
+        assertEquals( 10, node.get( "entities" ).size() );
+
+        query = query + " order by created desc";
+        node = activities.withQuery( query ).get();
+        assertEquals( 10, node.get( "entities" ).size() );
+    }
+
+
+    @Test
+    // USERGRID-1520
+    public void orderByComesBeforeLimitResult() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+        int checkResultsNum = 0;
+
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+        for ( int i = 0; i < 20; i++ ) {
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where created > " + 1 + " order by created desc";
+
+        JsonNode incorrectNode = activities.withQuery( query ).withLimit( 5 ).get();
+
+        assertEquals( 5, incorrectNode.get( "entities" ).size() );
+
+        while ( checkResultsNum < 5 ) {
+            assertEquals( activities.entityIndex( query, checkResultsNum ),
+                    activities.entityIndexLimit( query, 5, checkResultsNum ) );
+            checkResultsNum++;
+        }
+    }
+
+  /*
+   * public JsonNode entityIndex(JsonNode container, int index) { return
+   * container.get("entities").get(index); }
+   */
+
+
+    @Test
+    // USERGRID-1521
+    public void orderByReturnCorrectResults() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        int size = 200;
+
+        Map<String, String> actor = hashMap( "displayName", "Erin" );
+        Map<String, Object> props = new HashMap<String, Object>();
+
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+        List<JsonNode> activites = new ArrayList<JsonNode>( size );
+
+        for ( int i = 0; i < size; i++ ) {
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props ).get( "entities" ).get( 0 );
+            activites.add( activity );
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        long lastCreated = activites.get( activites.size() - 1 ).get( "created" ).asLong();
+
+        String errorQuery = String.format( "select * where created <= %d order by created desc", lastCreated );
+        String cursor = null;
+        int index = size - 1;
+
+        do {
+            JsonNode response = activities.withQuery( errorQuery ).get();
+            JsonNode cursorNode = response.get( "cursor" );
+
+            cursor = cursorNode != null ? cursorNode.asText() : null;
+
+            JsonNode entities = response.get( "entities" );
+
+            int returnSize = entities.size();
+
+            for ( int i = 0; i < returnSize; i++, index-- ) {
+                assertEquals( activites.get( index ), entities.get( i ) );
+            }
+
+            activities = activities.withCursor( cursor );
+        }
+        while ( cursor != null && cursor.length() > 0 );
+
+        assertEquals( "Paged to last result", -1, index );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ActivityResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ActivityResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ActivityResourceIT.java
deleted file mode 100644
index 0a9b23d..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ActivityResourceIT.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.java.client.Client.Query;
-import org.apache.usergrid.java.client.entities.Entity;
-import org.apache.usergrid.java.client.entities.User;
-import org.apache.usergrid.java.client.response.ApiResponse;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-
-/** @author tnine */
-@Concurrent()
-public class ActivityResourceIT extends AbstractRestIT {
-    private static Logger log = LoggerFactory.getLogger( ActivityResourceIT.class );
-
-    private static final String GROUP = "testGroup";
-
-    private static final String USER = "edanuff";
-
-    private static boolean groupCreated = false;
-
-
-    public ActivityResourceIT() throws Exception {
-
-    }
-
-
-    @Before
-    public void setupGroup() {
-        if ( groupCreated ) {
-            return;
-        }
-
-        client.createGroup( GROUP );
-
-        refreshIndex("test-organization", "test-app");
-
-        groupCreated = true;
-    }
-
-
-    @Test
-    public void postNullActivityToGroup() {
-
-        boolean fail = false;
-        try {
-            ApiResponse groupActivity = client.postGroupActivity( GROUP, null );
-            fail = (groupActivity.getError() != null);
-            
-        }
-        catch ( Exception e ) {
-            fail = true;
-        }
-        assertTrue( fail );
-    }
-
-
-    @Test
-    public void postGroupActivity() {
-
-        // don't populate the user, it will use the currently authenticated user.
-
-        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
-        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
-
-        client.postGroupActivity( GROUP, "POST", 
-            activityTitle, activityDesc, "testCategory", null, null, null, null, null );
-
-        refreshIndex("test-organization", "test-app");
-
-        Query results = client.queryActivityFeedForGroup( GROUP );
-
-        ApiResponse response = results.getResponse();
-
-        Entity result = response.getEntities().get( 0 );
-
-        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
-        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
-        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
-
-        // now pull the activity directly, we should find it
-
-        results = client.queryActivity();
-
-        response = results.getResponse();
-
-        result = response.getEntities().get( 0 );
-
-        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
-        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
-        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
-    }
-
-
-    @Test
-    public void postUserActivity() {
-
-        // don't populate the user, it will use the currently authenticated
-        // user.
-
-        User current = client.getLoggedInUser();
-
-        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
-        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
-
-        client.postUserActivity( "POST", activityTitle, activityDesc, "testCategory", current, null, null, null, null );
-
-        refreshIndex("test-organization", "test-app");
-
-        Query results = client.queryActivityFeedForUser( USER );
-
-        ApiResponse response = results.getResponse();
-
-        Entity result = response.getEntities().get( 0 );
-
-        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
-        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
-        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
-        assertEquals( current.getUuid().toString(), result.getProperties().get( "actor" ).get( "uuid" ).asText() );
-
-        // now pull the activity directly, we should find it
-
-        results = client.queryActivity();
-
-        response = results.getResponse();
-
-        result = response.getEntities().get( 0 );
-
-        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
-        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
-        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
-    }
-
-
-    @Test
-    public void postActivity() {
-
-        // don't populate the user, it will use the currently authenticated
-        // user.
-
-        User current = client.getLoggedInUser();
-
-        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
-        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
-
-        client.postActivity( "POST", activityTitle, activityDesc, "testCategory", current, null, null, null, null );
-
-        refreshIndex("test-organization", "test-app");
-
-        Query results = client.queryActivity();
-
-        ApiResponse response = results.getResponse();
-
-        Entity result = response.getEntities().get( 0 );
-
-        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
-        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
-        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
-
-        //ACTOR isn't coming back, why?
-        assertEquals( current.getUuid().toString(), result.getProperties().get( "actor" ).get( "uuid" ).asText() );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/CollectionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/CollectionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/CollectionsResourceIT.java
deleted file mode 100644
index 0027f2e..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/CollectionsResourceIT.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Assert;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * @author zznate
- * @author tnine
- */
-@Concurrent()
-public class CollectionsResourceIT extends AbstractRestIT {
-
-    private static Logger log = LoggerFactory.getLogger( CollectionsResourceIT.class );
-
-
-    @Test
-    public void postToBadPath() throws IOException {
-        Map<String, String> payload = hashMap( "name", "Austin" ).map( "state", "TX" );
-        JsonNode node = null;
-        try {
-            node = mapper.readTree( resource().path( "/test-organization/test-organization/test-app/cities" )
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
-        }
-        catch ( UniformInterfaceException e ) {
-            assertEquals( "Should receive a 400 Not Found", 400, e.getResponse().getStatus() );
-        }
-    }
-
-
-    @Test
-    public void postToEmptyCollection() throws IOException {
-        Map<String, String> payload = new HashMap<String, String>();
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/cities" ).queryParam( "access_token", access_token )
-                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .post( String.class, payload ));
-        assertNull( getEntity( node, 0 ) );
-        assertNull( node.get( "count" ) );
-    }
-
-
-    /**
-     * emails with "me" in them are causing errors. Test we can post to a colleciton after creating a user with this
-     * email
-     * <p/>
-     * USERGRID-689
-     */
-    @Test
-    public void permissionWithMeInString() throws Exception {
-        // user is created get a token
-        createUser( "sumeet.agarwal@usergrid.com", "sumeet.agarwal@usergrid.com", "secret", "Sumeet Agarwal" );
-        refreshIndex("test-organization", "test-app");
-
-        String token = userToken( "sumeet.agarwal@usergrid.com", "secret" );
-
-
-        //create a permission with the path "me" in it
-        Map<String, String> data = new HashMap<String, String>();
-
-        data.put( "permission", "get,post,put,delete:/users/sumeet.agarwal@usergrid.com/**" );
-
-        String path = "/test-organization/test-app/users/sumeet.agarwal@usergrid.com/permissions";
-        JsonNode posted = mapper.readTree( resource().path( path ).queryParam( "access_token", token ).accept( MediaType.APPLICATION_JSON )
-                        .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-
-
-        //now post data
-        data = new HashMap<String, String>();
-
-        data.put( "name", "profile-sumeet" );
-        data.put( "firstname", "sumeet" );
-        data.put( "lastname", "agarwal" );
-        data.put( "mobile", "122" );
-
-
-        posted = mapper.readTree( resource().path( "/test-organization/test-app/nestprofiles" ).queryParam( "access_token", token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, data ));
-
-        refreshIndex("test-organization", "test-app");
-
-        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/nestprofiles" ).queryParam( "access_token", token )
-                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .get( String.class ));
-
-        assertNotNull( getEntity( response, 0 ) );
-        assertNotNull( response.get( "count" ) );
-    }
-
-
-    @Test
-    public void stringWithSpaces() throws IOException {
-        Map<String, String> payload = hashMap( "summaryOverview", "My Summary" ).map( "caltype", "personal" );
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
-
-
-        UUID id = getEntityId( node, 0 );
-
-        //post a second entity
-
-
-        payload = hashMap( "summaryOverview", "Your Summary" ).map( "caltype", "personal" );
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, payload ));
-
-
-        refreshIndex("test-organization", "test-app");
-
-        //query for the first entity
-
-        String query = "summaryOverview = 'My Summary'";
-
-
-        JsonNode queryResponse = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" )
-                .queryParam( "access_token", access_token ).queryParam( "ql", query )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-
-        UUID returnedId = getEntityId( queryResponse, 0 );
-
-        assertEquals( id, returnedId );
-
-        assertEquals( 1, queryResponse.get( "entities" ).size() );
-    }
-
-
-    /**
-     * Test to verify "name property returns twice in AppServices response" is fixed.
-     * https://apigeesc.atlassian.net/browse/USERGRID-2318
-     */
-    @Test
-    public void testNoDuplicateFields() throws Exception {
-
-        {
-            // create an "app_user" object with name fred
-            Map<String, String> payload = hashMap( "type", "app_user" ).map( "name", "fred" );
-
-            JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/app_users" )
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
-
-            String uuidString = node.get( "entities" ).get( 0 ).get( "uuid" ).asText();
-            UUID entityId = UUIDUtils.tryGetUUID( uuidString );
-            Assert.assertNotNull( entityId );
-        }
-
-        refreshIndex("test-organization", "test-app");
-
-        {
-            // check REST API response for duplicate name property
-            // have to look at raw response data, Jackson will remove dups
-            String s = resource().path( "/test-organization/test-app/app_users/fred" )
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
-
-            int firstFred = s.indexOf( "fred" );
-            int secondFred = s.indexOf( "fred", firstFred + 4 );
-            Assert.assertEquals( "Should not be more than one name property", -1, secondFred );
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ConnectionResourceTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ConnectionResourceTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ConnectionResourceTest.java
deleted file mode 100644
index 5ab5ccd..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/ConnectionResourceTest.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class ConnectionResourceTest extends AbstractRestIT {
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    public void connectionsQueryTest() throws IOException {
-
-
-        CustomCollection activities = context.collection( "peeps" );
-
-        Map stuff = hashMap( "type", "chicken" );
-
-        activities.create( stuff );
-
-
-        Map<String, Object> payload = new LinkedHashMap<String, Object>();
-        payload.put( "username", "todd" );
-
-        Map<String, Object> objectOfDesire = new LinkedHashMap<String, Object>();
-        objectOfDesire.put( "codingmunchies", "doritoes" );
-
-        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, payload );
-
-        payload.put( "username", "scott" );
-
-
-        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, payload );
-    /*finish setting up the two users */
-
-
-        refreshIndex("test-organization", "test-app");
-
-        ClientResponse toddWant = resource().path( "/test-organization/test-app/users/todd/likes/peeps" )
-                .queryParam( "access_token", access_token ).accept( MediaType.TEXT_HTML )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( ClientResponse.class, objectOfDesire );
-
-        assertEquals( 200, toddWant.getStatus() );
-
-        refreshIndex("test-organization", "test-app");
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/peeps" ).queryParam( "access_token", access_token )
-                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .get( String.class ));
-
-        String uuid = node.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
-
-
-        try {
-            node = mapper.readTree( resource().path( "/test-organization/test-app/users/scott/likes/" + uuid )
-                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-            assert ( false );
-        }
-        catch ( UniformInterfaceException uie ) {
-            assertEquals( 404, uie.getResponse().getClientResponseStatus().getStatusCode() );
-        }
-    }
-
-
-    @Test
-    public void connectionsLoopbackTest() throws IOException {
-
-        CustomCollection things = context.collection( "things" );
-
-        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
-
-        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
-
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //create the connection
-        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
-
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //test we have the "likes" in our connection meta data response
-
-        JsonNode response = things.entity( "thing1" ).get();
-
-        String url = getEntity( response, 0 ).get( "metadata" ).get( "connections" ).get( "likes" ).asText();
-
-
-        assertNotNull( "Connection url returned in entity", url );
-
-        //trim off the start /
-        url = url.substring( 1 );
-
-
-        //now that we know the URl is correct, follow it
-
-        response = context.collection( url ).get();
-
-        UUID returnedUUID = getEntityId( response, 0 );
-
-        assertEquals( thing2Id, returnedUUID );
-
-
-        //now follow the loopback, which should be pointers to the other entity
-
-        url = getEntity( response, 0 ).get( "metadata" ).get( "connecting" ).get( "likes" ).asText();
-
-        assertNotNull( "Incoming edge URL provited", url );
-
-        //trim off the start /
-        url = url.substring( 1 );
-
-        //now we should get thing1 from the loopback url
-
-        response = context.collection( url ).get();
-
-        UUID returned = getEntityId( response, 0 );
-
-        assertEquals( "Should point to thing1 as an incoming entity connection", thing1Id, returned );
-    }
-
-
-    @Test
-    public void connectionsUUIDTest() throws IOException {
-
-        CustomCollection things = context.collection( "things" );
-
-        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
-
-        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
-
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //create the connection
-        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
-
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //test we have the "likes" in our connection meta data response
-
-        JsonNode response = things.entity( "thing1" ).get();
-
-        String url = getEntity( response, 0 ).get( "metadata" ).get( "connections" ).get( "likes" ).asText();
-
-
-        assertNotNull( "Connection url returned in entity", url );
-
-        //trim off the start /
-        url = url.substring( 1 );
-
-
-        //now that we know the URl is correct, follow it
-
-        response = context.collection( url ).get();
-
-        UUID returnedUUID = getEntityId( response, 0 );
-
-        assertEquals( thing2Id, returnedUUID );
-
-        //get on the collection works, now get it directly by uuid
-
-        //now we should get thing1 from the loopback url
-
-        response = things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).get();
-
-        UUID returned = getEntityId( response, 0 );
-
-        assertEquals( "Should point to thing2 as an entity connection", thing2Id, returned );
-    }
-
-    @Test //USERGRID-3011
-    public void connectionsDeleteSecondEntityInConnectionTest() throws IOException {
-
-        CustomCollection things = context.collection( "things" );
-
-        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
-
-        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //create the connection
-        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
-
-        JsonNode response = things.entity( "thing2" ).delete();
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        JsonNode node = things.entity ( "thing2" ).get();
-
-        assertNull(node);
-
-    }
-
-    @Test //USERGRID-3011
-    public void connectionsDeleteFirstEntityInConnectionTest() throws IOException {
-
-        CustomCollection things = context.collection( "things" );
-
-        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
-
-        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        //create the connection
-        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
-
-        JsonNode response = things.entity( "thing1" ).delete();
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        JsonNode node = things.entity ( "thing1" ).get();
-
-        assertNull(node);
-
-    }
-
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/GroupResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/GroupResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/GroupResourceIT.java
deleted file mode 100644
index 6278067..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/GroupResourceIT.java
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.java.client.Client.Query;
-import org.apache.usergrid.java.client.response.ApiResponse;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-
-/** @author tnine */
-@Concurrent()
-public class GroupResourceIT extends AbstractRestIT {
-    private static Logger log = LoggerFactory.getLogger( GroupResourceIT.class );
-
-    private static final String GROUP = "testGroup";
-
-    private static final String USER = "edanuff";
-
-    private static boolean groupCreated = false;
-
-
-    public GroupResourceIT() throws Exception {
-
-    }
-
-
-    @Before
-    public void setupGroup() {
-        if ( groupCreated ) {
-            return;
-        }
-
-        try {
-            client.createGroup( GROUP );
-            groupCreated = true;
-        }
-        catch ( Exception e ) {
-            log.error( "Error creating group " + GROUP, e );
-        }
-        refreshIndex("test-organization", "test-app");
-
-    }
-
-
-    @Test
-    public void failGroupNameValidation() {
-
-        ApiResponse response = client.createGroup( "groupName/withslash" );
-        assertNull( response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        {
-            boolean failed = false;
-            try {
-                ApiResponse groupResponse = client.createGroup( "groupName withspace" );
-                failed = groupResponse.getError() != null;
-            } catch ( Exception e ) {
-                failed = true;
-            }
-            assertTrue( failed );
-        }
-    }
-
-
-    @Test
-    public void postGroupActivity() {
-
-        // don't populate the user, it will use the currently authenticated
-        // user.
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String groupPath = "groupPath" + id;
-        String groupTitle = "groupTitle " + id;
-        String groupName = "groupName" + id;
-
-        ApiResponse response = client.createGroup( groupPath, groupTitle, groupName );
-
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        UUID newId = response.getEntities().get( 0 ).getUuid();
-
-        Query results = client.queryGroups( String.format( "name='%s'", groupName ) );
-
-        response = results.getResponse();
-
-        UUID entityId = response.getEntities().get( 0 ).getUuid();
-
-        assertEquals( newId, entityId );
-
-        results = client.queryGroups( String.format( "title='%s'", groupTitle ) );
-
-        response = results.getResponse();
-
-        entityId = response.getEntities().get( 0 ).getUuid();
-
-        assertEquals( newId, entityId );
-
-        results = client.queryGroups( String.format( "title contains '%s'", id ) );
-
-        response = results.getResponse();
-
-        entityId = response.getEntities().get( 0 ).getUuid();
-
-        assertEquals( newId, entityId );
-
-        results = client.queryGroups( String.format( "path='%s'", groupPath ) );
-
-        response = results.getResponse();
-
-        entityId = response.getEntities().get( 0 ).getUuid();
-
-        assertEquals( newId, entityId );
-    }
-
-
-    @Test
-    public void addRemovePermission() throws IOException {
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String groupName = "groupname" + id;
-
-        ApiResponse response = client.createGroup( groupName );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        refreshIndex("test-organization", "test-app");
-
-        UUID createdId = response.getEntities().get( 0 ).getUuid();
-
-        // add Permission
-
-        String json = "{\"permission\":\"delete:/test\"}";
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, json ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-        assertEquals( node.get( "data" ).get( 0 ).asText(), "delete:/test" );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertEquals( node.get( "data" ).get( 0 ).asText(), "delete:/test" );
-
-
-        // remove Permission
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
-                .queryParam( "access_token", access_token ).queryParam( "permission", "delete%3A%2Ftest" )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "data" ).size() == 0 );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "data" ).size() == 0 );
-    }
-
-
-    @Test
-    public void addRemoveRole() throws IOException {
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String groupName = "groupname" + id;
-        String roleName = "rolename" + id;
-
-        ApiResponse response = client.createGroup( groupName );
-        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
-
-        UUID createdId = response.getEntities().get( 0 ).getUuid();
-
-        refreshIndex("test-organization", "test-app");
-
-        // create Role
-
-        String json = "{\"title\":\"" + roleName + "\",\"name\":\"" + roleName + "\"}";
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
-                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .post( String.class, json ));
-
-        // check it
-        assertNull( node.get( "errors" ) );
-
-
-        refreshIndex("test-organization", "test-app");
-
-        // add Role
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles/" + roleName )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        refreshIndex("test-organization", "test-app");
-
-        // check it
-        assertNull( node.get( "errors" ) );
-        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
-
-        // check root roles
-        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        // remove Role
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles/" + roleName )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-        assertNull( node.get( "errors" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "entities" ).size() == 0 );
-
-        // check root roles - role should remain
-        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertTrue( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
-
-        // now kill the root role
-        node = mapper.readTree( resource().path( "/test-organization/test-app/roles/" + roleName )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-        assertNull( node.get( "errors" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        // now it should be gone
-        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        assertNull( node.get( "errors" ) );
-        assertFalse( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/MatrixQueryTests.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/MatrixQueryTests.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/MatrixQueryTests.java
deleted file mode 100644
index 475c8fb..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/MatrixQueryTests.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-import java.util.Map;
-import java.util.UUID;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-import org.apache.usergrid.rest.test.resource.app.UsersCollection;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-import org.junit.Rule;
-import org.junit.Test;
-
-
-public class MatrixQueryTests extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    public void simpleMatrix() throws Exception {
-
-        /**
-         * Create 3 users which we will use for sub searching
-         */
-        UsersCollection users = context.users();
-
-        Map user1 =
-                hashMap( "username", "user1" ).map( "email", "testuser1@usergrid.com" ).map( "fullname", "Bob Smith" );
-
-        users.create( user1 );
-
-
-        Map user2 =
-                hashMap( "username", "user2" ).map( "email", "testuser2@usergrid.com" ).map( "fullname", "Fred Smith" );
-
-        users.create( user2 );
-
-
-        Map user3 = hashMap( "username", "user3" ).map( "email", "testuser3@usergrid.com" )
-                .map( "fullname", "Frank Grimes" );
-
-        users.create( user3 );
-
-
-        //now create 4 restaurants
-
-        CustomCollection restaurants = context.collection( "restaurants" );
-
-
-        Map restaurant1 = hashMap( "name", "Old Major" );
-
-        UUID restaurant1Id = getEntityId( restaurants.create( restaurant1 ), 0 );
-
-        Map restaurant2 = hashMap( "name", "tag" );
-
-        UUID restaurant2Id = getEntityId( restaurants.create( restaurant2 ), 0 );
-
-        Map restaurant3 = hashMap( "name", "Squeaky Bean" );
-
-        UUID restaurant3Id = getEntityId( restaurants.create( restaurant3 ), 0 );
-
-        Map restaurant4 = hashMap( "name", "Lola" );
-
-        UUID restaurant4Id = getEntityId( restaurants.create( restaurant4 ), 0 );
-
-
-        //now like our 3 users
-
-
-        //user 1 likes old major
-        users.user( "user1" ).connection( "likes" ).entity( restaurant1Id ).post();
-
-        users.user( "user1" ).connection( "likes" ).entity( restaurant2Id ).post();
-
-
-        //user 2 likes tag and squeaky bean
-        users.user( "user2" ).connection( "likes" ).entity( restaurant2Id ).post();
-
-        users.user( "user2" ).connection( "likes" ).entity( restaurant3Id ).post();
-
-        //user 3 likes  Lola (it shouldn't appear in the results)
-
-        users.user( "user3" ).connection( "likes" ).entity( restaurant4Id ).post();
-
-
-        //now query with matrix params
-
-
-//        JsonNode testGetUsers = context.collection( "users" ).get().get( "entities" );
-//
-//        JsonNode likesNode =
-//                context.collection( "users" ).entity( "user1" ).connection( "likes" ).get().get( "entities" );
-//
-//
-//        JsonNode queryResponse = context.collection( "users" ).withMatrix(
-//                hashMap( "ql", "where fullname contains 'Smith'" ).map( "limit", "1000" ) ).connection( "likes" ).get();
-//
-//        assertEquals( "Old Major", getEntityName( queryResponse, 0 ) );
-//
-//        assertEquals( "tag", getEntityName( queryResponse, 1 ) );
-//
-//        assertEquals( "Squeaky Bean", getEntityName( queryResponse, 2 ) );
-//
-//        /**
-//         * No additional elements in the response
-//         */
-//        assertNull( getEntity( queryResponse, 3 ) );
-    }
-
-
-//    @Test
-//    public void largeRootElements() {
-//
-//
-//        // create 4 restaurants
-//
-//        CustomCollection restaurants = context.collection( "restaurants" );
-//
-//
-//        Map restaurant1 = hashMap( "name", "Old Major" );
-//
-//        UUID restaurant1Id = getEntityId( restaurants.create( restaurant1 ), 0 );
-//
-//        Map restaurant2 = hashMap( "name", "tag" );
-//
-//        UUID restaurant2Id = getEntityId( restaurants.create( restaurant2 ), 0 );
-//
-//        Map restaurant3 = hashMap( "name", "Squeaky Bean" );
-//
-//        UUID restaurant3Id = getEntityId( restaurants.create( restaurant3 ), 0 );
-//
-//
-//        /**
-//         * Create 3 users which we will use for sub searching
-//         */
-//        UsersCollection users = context.users();
-//
-//
-//        int max = 1000;
-//        int count = ( int ) (max * 1.1);
-//
-//        for ( int i = 0; i < count; i++ ) {
-//
-//            String username = "user" + i;
-//            String email = username + "@usergrid.com";
-//
-//            Map user1 = hashMap( "username", username ).map( "email", email ).map( "fullname", i + " Smith" );
-//
-//            users.create( user1 );
-//
-//            /**
-//             * Change our links every other time.  This way we should get all 3
-//             */
-//
-//            if ( i % 2 == 0 ) {
-//                users.user( username ).connection( "likes" ).entity( restaurant1Id ).post();
-//
-//                users.user( username ).connection( "likes" ).entity( restaurant2Id ).post();
-//            }
-//            else {
-//
-//                users.user( username ).connection( "likes" ).entity( restaurant2Id ).post();
-//
-//                users.user( username ).connection( "likes" ).entity( restaurant3Id ).post();
-//            }
-//        }
-//
-//
-//
-//        //set our limit to 1k.  We should get only 3 results, but this should run
-//        JsonNode queryResponse = context.collection( "users" ).withMatrix(
-//                hashMap( "ql", "where fullname contains 'Smith'" ).map( "limit", "1000" ) ).connection( "likes" ).get();
-//
-//        assertEquals( "Old Major", getEntityName( queryResponse, 0 ) );
-//
-//        assertEquals( "tag", getEntityName( queryResponse, 1 ) );
-//
-//        assertEquals( "Squeaky Bean", getEntityName( queryResponse, 2 ) );
-//
-//        /**
-//         * No additional elements in the response
-//         */
-//        assertNull( getEntity( queryResponse, 3 ) );
-//    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/OwnershipResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/OwnershipResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/OwnershipResourceIT.java
deleted file mode 100644
index d11f473..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/OwnershipResourceIT.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.Connection;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-import org.apache.usergrid.rest.test.resource.app.queue.DevicesCollection;
-import org.apache.usergrid.rest.test.security.TestAppUser;
-import org.apache.usergrid.rest.test.security.TestUser;
-import org.apache.usergrid.utils.MapUtils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-
-/**
- *
- */
-@Concurrent()
-public class OwnershipResourceIT extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    public void meVerify() throws Exception {
-
-        context.clearUser();
-
-        String email = "testuser1@usergrid.org";
-        TestUser user1 = new TestAppUser( email, "password", email ).create( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-        user1.login( context ).makeActive( context );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String token = user1.getToken();
-        JsonNode userNode = context.application().users().user( "me" ).get();
-        assertNotNull( userNode );
-
-        String uuid = userNode.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
-        assertNotNull( uuid );
-
-        setup.getMgmtSvc().revokeAccessTokenForAppUser( token );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        try {
-            context.application().users().user( "me" ).get();
-            fail();
-        }
-        catch ( Exception ex ) {
-            ex.printStackTrace();
-            assertTrue( ex.getMessage().contains( "401" ) );
-        }
-    }
-
-
-    @Test
-    public void contextualPathOwnership() throws IOException {
-
-        // anonymous user
-        context.clearUser();
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        TestUser user1 = new TestAppUser( "testuser1@usergrid.org", "password", "testuser1@usergrid.org" ).create( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-        user1.login( context );
-        user1.makeActive( context );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // create device 1 on user1 devices
-        context.application().users().user( "me" ).devices()
-               .create( MapUtils.hashMap( "name", "device1" ).map( "number", "5551112222" ) );
-
-        // anonymous user
-        context.clearUser();
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // create device 2 on user 2
-        TestUser user2 = new TestAppUser( "testuser2@usergrid.org", "password", "testuser2@usergrid.org" ).create( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-        user2.login( context );
-        user2.makeActive( context );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        context.application().users().user( "me" ).devices()
-               .create( MapUtils.hashMap( "name", "device2" ).map( "number", "5552223333" ) );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // now query on user 1.
-
-        DevicesCollection devices = context.withUser( user1 ).application().users().user( "me" ).devices();
-
-        JsonNode data = devices.device( "device1" ).get();
-        assertNotNull( data );
-        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can't see device2
-        data = devices.device( "device2" ).get();
-        assertNull( data );
-
-        // do a collection load, make sure we're not loading device 2
-        data = devices.get();
-
-        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
-        assertNull( getEntity( data, 1 ) );
-
-        // log in as user 2 and check it
-        devices = context.withUser( user2 ).application().users().user( "me" ).devices();
-
-        data = devices.device( "device2" ).get();
-        assertNotNull( data );
-        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can't see device1
-        data = devices.device( "device1" ).get();
-        assertNull( data );
-
-        // do a collection load, make sure we're not loading device 1
-        data = devices.get();
-
-        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
-        assertNull( getEntity( data, 1 ) );
-
-        // we should see both devices when loaded from the root application
-
-        // test for user 1
-
-        devices = context.withUser( user1 ).application().devices();
-        data = devices.device( "device1" ).get();
-
-        assertNotNull( data );
-        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = devices.device( "device2" ).get();
-
-        assertNotNull( data );
-        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // test for user 2
-        data = context.withUser( user2 ).application().devices().device( "device1" ).get();
-
-        assertNotNull( data );
-        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = devices.device( "device2" ).get();
-
-        assertNotNull( data );
-        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
-    }
-
-
-    @Test
-    public void contextualConnectionOwnership() throws IOException {
-
-        // anonymous user
-        context.clearUser();
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String email = "testuser1@usergrid.org";
-        TestUser user1 = new TestAppUser( email, "password", email ).create( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-        user1.login( context ).makeActive( context );
-
-        // create a 4peaks restaurant
-        JsonNode data = context.application()
-                .collection( "restaurants" ).create( MapUtils.hashMap( "name", "4peaks" ) );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // create our connection
-        data = context.application().users().user( "me" )
-                .connection( "likes" ).collection( "restaurants" ).entity( "4peaks" ).post();
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-       String peaksId = getEntity( data, 0 ).get( "uuid" ).asText();
-
-        // anonymous user
-        context.clearUser();
-
-        // create a restaurant and link it to user 2
-        email = "testuser2@usergrid.org";
-        TestUser user2 = new TestAppUser( email, "password", email ).create( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        user2.login( context ).makeActive( context );
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        data = context.application().collection( "restaurants" )
-                      .create( MapUtils.hashMap( "name", "arrogantbutcher" ) );
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        data = context.application().users().user( "me" ).connection( "likes" ).collection( "restaurants" )
-                      .entity( "arrogantbutcher" ).post();
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String arrogantButcherId = getEntity( data, 0 ).get( "uuid" ).asText();
-
-        // now query on user 1.
-
-        CustomCollection likeRestaurants =
-                context.withUser( user1 ).application().users().user( "me" ).connection( "likes" )
-                       .collection( "restaurants" );
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // check we can get it via id
-        data = likeRestaurants.entity( peaksId ).get();
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can get it by name
-        data = likeRestaurants.entity( "4peaks" ).get();
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can't see arrogantbutcher by name or id
-        data = likeRestaurants.entity( "arrogantbutcher" ).get();
-        assertNull( data );
-
-        data = likeRestaurants.entity( arrogantButcherId ).get();
-        assertNull( data );
-
-        // do a collection load, make sure we're not entities we shouldn't see
-        data = likeRestaurants.get();
-
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-        assertNull( getEntity( data, 1 ) );
-
-        // log in as user 2 and check it
-        likeRestaurants = context.withUser( user2 ).application().users().user( "me" ).connection( "likes" )
-                                 .collection( "restaurants" );
-
-        data = likeRestaurants.entity( arrogantButcherId ).get();
-        assertNotNull( data );
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = likeRestaurants.entity( "arrogantbutcher" ).get();
-        assertNotNull( data );
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can't see 4peaks
-        data = likeRestaurants.entity( "4peaks" ).get();
-        assertNull( data );
-
-        data = likeRestaurants.entity( peaksId ).get();
-        assertNull( data );
-
-        // do a collection load, make sure we're not loading device 1
-        data = likeRestaurants.get();
-
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-        assertNull( getEntity( data, 1 ) );
-
-        // we should see both devices when loaded from the root application
-
-        // test for user 1
-
-        CustomCollection restaurants = context.withUser( user1 ).application().collection( "restaurants" );
-        data = restaurants.entity( "4peaks" ).get();
-
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = restaurants.entity( "arrogantbutcher" ).get();
-
-        assertNotNull( data );
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // test for user 2
-        restaurants = context.withUser( user1 ).application().collection( "restaurants" );
-        data = restaurants.entity( "4peaks" ).get();
-
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = restaurants.entity( "arrogantbutcher" ).get();
-
-        assertNotNull( data );
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-    }
-
-
-    @Test
-    public void contextualConnectionOwnershipGuestAccess() throws IOException {
-
-        //set up full GET,PUT,POST,DELETE access for guests
-        context.application().collection( "roles" ).entity( "guest" ).collection( "permissions" )
-               .create( MapUtils.hashMap( "permission", "get,put,post,delete:/**" ) );
-
-
-        // anonymous user
-        context.clearUser();
-
-
-        JsonNode city = context.application().collection( "cities" ).create( MapUtils.hashMap( "name", "tempe" ) );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String cityId = getEntity( city, 0 ).get( "uuid" ).asText();
-
-        // create a 4peaks restaurant
-        JsonNode data = context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" )
-                               .collection( "restaurants" ).create( MapUtils.hashMap( "name", "4peaks" ) );
-
-        String peaksId = getEntity( data, 0 ).get( "uuid" ).asText();
-
-        data = context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" )
-                      .collection( "restaurants" ).create( MapUtils.hashMap( "name", "arrogantbutcher" ) );
-
-        String arrogantButcherId = getEntity( data, 0 ).get( "uuid" ).asText();
-
-        // now query on user 1.
-
-        Connection likeRestaurants =
-                context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // check we can get it via id with no collection name
-        data = likeRestaurants.entity( peaksId ).get();
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = likeRestaurants.entity( arrogantButcherId ).get();
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // check we can get it via id with a collection name
-        data = likeRestaurants.collection( "restaurants" ).entity( peaksId ).get();
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = likeRestaurants.collection( "restaurants" ).entity( arrogantButcherId ).get();
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-
-        // do a delete either token should work
-        data = likeRestaurants.collection( "restaurants" ).entity( peaksId ).delete();
-
-        assertNotNull( data );
-        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
-
-        data = likeRestaurants.collection( "restaurants" ).entity( arrogantButcherId ).delete();
-
-        assertNotNull( data );
-        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
-    }
-}


[2/8] incubator-usergrid git commit: organized rest IT

Posted by ro...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/PermissionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/PermissionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/PermissionsResourceIT.java
deleted file mode 100644
index 993d88b..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/PermissionsResourceIT.java
+++ /dev/null
@@ -1,768 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import java.util.Iterator;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.java.client.entities.Group;
-import org.apache.usergrid.management.ApplicationInfo;
-import org.apache.usergrid.management.OrganizationOwnerInfo;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.ClientResponse.Status;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * Tests permissions of adding and removing users from roles as well as groups
- *
- * @author tnine
- */
-@Concurrent()
-public class PermissionsResourceIT extends AbstractRestIT {
-
-    private static final String ROLE = "permtestrole";
-
-    private static final String USER = "edanuff";
-
-
-    public PermissionsResourceIT() throws Exception {
-
-    }
-
-
-    @Test
-    public void deleteUserFromRole() throws IOException {
-        Map<String, String> data = hashMap( "name", ROLE );
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
-                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .post( String.class, data ));
-
-        assertNull( node.get( "error" ) );
-
-        assertEquals( ROLE, getEntity( node, 0 ).get( "name" ).asText() );
-
-        refreshIndex("test-organization", "test-app");
-
-        // add the user to the role
-        node = mapper.readTree( resource().path( "/test-organization/test-app/roles/" + ROLE + "/users/" + USER )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertNull( node.get( "error" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        // now check the user has the role
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        // check if the role was assigned
-        assertEquals( ROLE, getEntity( node, 0 ).get( "name" ).asText() );
-
-        // now delete the role
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles/" + ROLE )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        refreshIndex("test-organization", "test-app");
-
-        // check if the role was deleted
-
-        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles" )
-                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        // check if the role was assigned
-        assertNull( getEntity( node, 0 ) );
-    }
-
-
-    @Test
-    public void deleteUserGroup() throws IOException {
-
-        // don't populate the user, it will use the currently authenticated
-        // user.
-
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String groupPath = "groupPath" + id;
-
-        Map<String, String> data = hashMap( "type", "group" ).map( "path", groupPath );
-
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/groups" )
-                .queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, data ));
-
-        assertNull( node.get( "error" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        node = mapper.readTree( 
-            resource().path( "/test-organization/test-app/groups/" + groupPath + "/users/" + USER )
-                .queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class ));
-
-        assertNull( node.get( "error" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        Map<String, Group> groups = client.getGroupsForUser( USER );
-
-        assertNotNull( groups.get( groupPath ) );
-
-        // now delete the group
-
-        node = mapper.readTree( 
-            resource().path( "/test-organization/test-app/groups/" + groupPath + "/users/" + USER )
-                .queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE )
-                .delete( String.class ));
-
-        assertNull( node.get( "error" ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        groups = client.getGroupsForUser( USER );
-
-        assertNull( groups.get( groupPath ) );
-    }
-
-
-    /**
-     * For the record, you should NEVER allow the guest role to add roles. This is a gaping security hole and a VERY BAD
-     * IDEA! That being said, this should technically work, and needs testing.
-     */
-    @Test
-    public void dictionaryPermissions() throws Exception {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String applicationName = "testapp";
-        String orgname = "dictionaryPermissions";
-        String username = "permissionadmin" + id;
-        String password = "password";
-        String email = String.format( "email%s@usergrid.com", id );
-
-        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
-                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
-                                                  true, false );
-
-        // create the app
-        ApplicationInfo appInfo =
-                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
-
-        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
-
-        // add the perms to the guest to allow users in the role to create roles
-        // themselves
-        addPermission( orgname, applicationName, adminToken, "guest", "get,put,post:/roles/**" );
-
-        Map<String, String> data = hashMap( "name", "usercreatedrole" );
-
-        // create a role as the user
-        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .post( String.class, data ));
-
-        assertNull( getError( node ) );
-
-        refreshIndex(orgname, applicationName);
-
-        // now try to add permission as the user, this should work
-        addPermission( orgname, applicationName, "usercreatedrole", "get,put,post:/foo/**" );
-    }
-
-
-    /**
-     * Tests a real world example with the following steps. Creates an application.
-     * <p/>
-     * Creates a new role "reviewer"
-     * <p/>
-     * Grants a permission to GET, POST, and PUT the reviews url for the reviewer role
-     * <p/>
-     * Grants a permission GET on the reviewer for the
-     * <p/>
-     * Create a user reviewer1 and add them to the reviewer role
-     * <p/>
-     * Test access with reviewer1
-     * <p/>
-     * Create a group reviewergroup and add the "reviewer" group to it
-     * <p/>
-     * Create a user reviewer 2 and add them to the "reveiwergroup"
-     */
-    @Test
-    public void applicationPermissions() throws Exception {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String applicationName = "test";
-        String orgname = "applicationpermissions";
-        String username = "permissionadmin" + id;
-        String password = "password";
-        String email = String.format( "email%s@usergrid.com", id );
-
-        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
-                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
-                                                  true, false );
-
-        // create the app
-        ApplicationInfo appInfo =
-                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
-
-        // now create the new role
-        Map<String, String> data = hashMap( "name", "reviewer" );
-
-        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
-
-        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-
-        assertNull( getError( node ) );
-
-        // delete the default role to test permissions later
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles/default", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-
-        assertNull( getError( node ) );
-        refreshIndex(orgname, applicationName);
-
-        // grant the perms to reviewer
-        addPermission( orgname, applicationName, adminToken, "reviewer", "get,put,post:/reviews/**" );
-
-        // grant get to guest
-        addPermission( orgname, applicationName, adminToken, "guest", "get:/reviews/**" );
-
-        UUID userId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "reviewer1",
-                "reviewer1@usergrid.com" );
-
-        refreshIndex(orgname, applicationName);
-
-        // grant this user the "reviewer" role
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/users/reviewer1/roles/reviewer", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        assertNull( getError( node ) );
-
-        refreshIndex(orgname, applicationName);
-
-        String reviewer1Token = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userId, 0 );
-
-        Map<String, String> review =
-                hashMap( "rating", "4" ).map( "name", "noca" ).map( "review", "Excellent service and food" );
-
-        // post a review as the reviewer1 user
-        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
-
-        review = hashMap( "rating", "4" ).map( "name", "4peaks" ).map( "review", "Huge beer selection" );
-
-        refreshIndex(orgname, applicationName);
-
-        // put a review as the reviewer1 user
-        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, review );
-
-        refreshIndex(orgname, applicationName);
-
-        // get the reviews
-
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( "noca", getEntity( node, 0 ).get( "name" ).asText() );
-        assertEquals( "4peaks", getEntity( node, 1 ).get( "name" ).asText() );
-
-        // can't delete, not in the grants
-
-        ClientResponse.Status status = null;
-
-        try {
-            resource().path( String.format( "/%s/%s/reviews/noca", orgname, applicationName ) )
-                    .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        refreshIndex(orgname, applicationName);
-
-        status = null;
-
-        try {
-            resource().path( String.format( "/%s/%s/reviews/4peaks", orgname, applicationName ) )
-                    .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        refreshIndex(orgname, applicationName);
-
-        // now test some groups
-        UUID secondUserId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "reviewer2",
-                "reviewer2@usergrid.com" );
-
-        Map<String, String> group = hashMap( "path", "reviewergroup" );
-
-        // /now create the group
-        resource().path( String.format( "/%s/%s/groups", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, group );
-
-        refreshIndex(orgname, applicationName);
-
-        // link the group to the role
-        resource().path( String.format( "/%s/%s/groups/reviewergroup/roles/reviewer", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, group );
-
-        refreshIndex(orgname, applicationName);
-
-        // add the user to the group
-        resource().path( String.format( "/%s/%s/users/reviewer2/groups/reviewergroup", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class );
-
-        refreshIndex(orgname, applicationName);
-
-        // post 2 reviews. Should get permissions from the group
-
-        String secondUserToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), secondUserId, 0 );
-
-        review = hashMap( "rating", "4" ).map( "name", "cowboyciao" ).map( "review", "Great atmosphoere" );
-
-        // post a review as the reviewer2 user
-        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
-
-        review = hashMap( "rating", "4" ).map( "name", "currycorner" ).map( "review", "Authentic" );
-
-        refreshIndex(orgname, applicationName);
-
-        // post a review as the reviewer2 user
-        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
-
-        refreshIndex(orgname, applicationName);
-
-        // get all reviews as a user
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
-                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertEquals( "noca", getEntity( node, 0 ).get( "name" ).asText() );
-        assertEquals( "4peaks", getEntity( node, 1 ).get( "name" ).asText() );
-        assertEquals( "cowboyciao", getEntity( node, 2 ).get( "name" ).asText() );
-        assertEquals( "currycorner", getEntity( node, 3 ).get( "name" ).asText() );
-
-        // issue a delete, it shouldn't work, no permissions
-
-        status = null;
-
-        try {
-            resource().path( String.format( "/%s/%s/reviews/cowboyciao", orgname, applicationName ) )
-                    .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        refreshIndex(orgname, applicationName);
-
-        status = null;
-
-        try {
-            resource().path( String.format( "/%s/%s/reviews/currycorner", orgname, applicationName ) )
-                    .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-
-        assertEquals( Status.UNAUTHORIZED, status );
-    }
-
-
-    /**
-     * Tests the scenario where we have roles declarations such as: <ul> <li>GET /users/[star]/reviews "any user can
-     * read any others book review"</li> <li>POST /users/[user1]/reviews "cannot post as user2 to user1's reviews"</li>
-     * <ii>POST /users/[star]/reviews/feedback/* "can post as user2 to user1's feedback/good or /bad</ii> </ul>
-     * <p/>
-     * Scenario is as follows: Create an application
-     * <p/>
-     * Add two application users - user1 - user2
-     * <p/>
-     * Create a book collection for user1
-     */
-    @Test
-    public void wildcardMiddlePermission() throws Exception {
-
-         Map<String, String> params = buildOrgAppParams();
-        String orgname =params.get( "orgName" ) ;
-        String applicationName = params.get( "appName" ) ;
-        
-        OrganizationOwnerInfo orgs = setup.getMgmtSvc().createOwnerAndOrganization( params.get( "orgName" ),
-                params.get( "username" ), "noname", params.get( "email" ), params.get( "password" ), true, false );
-
-        // create the app
-        ApplicationInfo appInfo =
-                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), params.get( "appName" ) );
-        assertNotNull( appInfo );
-
-        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
-
-        JsonNode node = mapper.readTree( resource()
-                .path( String.format( "/%s/%s/roles/default", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-        Map<String, String> data = hashMap( "name", "reviewer" );
-
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-        assertNull( getError( node ) );
-
-        refreshIndex(orgname, applicationName);
-
-        // allow access to reviews
-        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
-                "get,put,post:/reviews/**" );
-        // allow access to all user's connections
-        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
-                "get,put,post:/users/${user}/**" );
-        // allow access to the review relationship
-        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
-                "get,put,post:/books/*/review/*" );
-
-        assertNull( getError( node ) );
-        // create userOne
-        UUID userOneId =
-                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "wildcardpermuserone",
-                        "wildcardpermuserone@apigee.com" );
-        assertNotNull( userOneId );
-
-        // create userTwo
-        UUID userTwoId =
-                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "wildcardpermusertwo",
-                        "wildcardpermusertwo@apigee.com" );
-        assertNotNull( userTwoId );
-
-        refreshIndex(orgname, applicationName);
-
-        // assign userOne the reviewer role
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/%s/roles/reviewer", params.get( "orgName" ), params.get( "appName" ),
-                        userOneId.toString() ) ).queryParam( "access_token", adminToken )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        refreshIndex(orgname, applicationName);
-
-        Map<String, String> book = hashMap( "title", "Ready Player One" ).map( "author", "Earnest Cline" );
-
-        // create a book as admin
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/books", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, book ));
-
-        logNode( node );
-        assertEquals( "Ready Player One", getEntity( node, 0 ).get( "title" ).textValue() );
-        String bookId = getEntity( node, 0 ).get( "uuid" ).textValue();
-
-        refreshIndex(orgname, applicationName);
-
-        String userOneToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userOneId, 0 );
-        // post a review of the book as user1
-        // POST https://api.usergrid.com/my-org/my-app/users/$user1/reviewed/books/$uuid
-        Map<String, String> review =
-                hashMap( "heading", "Loved It" ).map( "body", "80s Awesomeness set in the future" );
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review ));
-        String reviewId = getEntity( node, 0 ).get( "uuid" ).textValue();
-
-        refreshIndex(orgname, applicationName);
-
-        // POST https://api.usergrid.com/my-org/my-app/users/me/wrote/review/${reviewId}
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/me/wrote/review/%s", params.get( "orgName" ), params.get( "appName" ),
-                        reviewId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        refreshIndex(orgname, applicationName);
-
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/me/reviewed/books/%s", params.get( "orgName" ), params.get( "appName" ),
-                        bookId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-        logNode( node );
-
-        refreshIndex(orgname, applicationName);
-
-        // POST https://api.usergrid.com/my-org/my-app/books/${bookId}/review/${reviewId}
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/books/%s/review/%s", params.get( "orgName" ), params.get( "appName" ), bookId,
-                        reviewId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-        logNode( node );
-
-        refreshIndex(orgname, applicationName);
-
-        // now try to post the same thing to books to verify as userOne the failure
-        Status status = null;
-        try {
-            node = mapper.readTree( resource().path( String.format( "/%s/%s/books", params.get( "orgName" ), params.get( "appName" ) ) )
-                    .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-            logNode( node );
-        }
-        catch ( UniformInterfaceException uie ) {
-            status = uie.getResponse().getClientResponseStatus();
-        }
-        assertEquals( Status.UNAUTHORIZED, status );
-
-        refreshIndex(orgname, applicationName);
-
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/me/reviewed/books", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        logNode( node );
-
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/reviews/%s", params.get( "orgName" ), params.get( "appName" ), reviewId ) )
-                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        logNode( node );
-
-        node = mapper.readTree( resource()
-                .path( String.format( "/%s/%s/users/me/wrote", params.get( "orgName" ), params.get( "appName" ) ) )
-                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-        logNode( node );
-    }
-
-
-    /**
-     * Tests the scenario where we have role declaration such as: <ul> <li>POST /users/[star]/following/users/${user}" a
-     * user can add himself to any other user following list"</li> </ul>
-     * <p/>
-     * Scenario is as follows: Create an application
-     * <p/>
-     * Add two application users - examplepatient - exampledoctor
-     * <p/>
-     * examplepatient add himself to exampledoctor following list
-     */
-    @Test
-    @Ignore("Why is this ignored?")
-    public void wildcardFollowingPermission() throws Exception {
-        UUID id = UUIDUtils.newTimeUUID();
-
-        String applicationName = "test";
-        String orgname = "followingpermissions";
-        String username = "permissionadmin" + id;
-        String password = "password";
-        String email = String.format( "email%s@usergrid.com", id );
-
-        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
-                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
-                                                  true, false );
-
-        // create the app
-        ApplicationInfo appInfo =
-                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
-        assertNotNull( appInfo );
-
-        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
-
-        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles/default", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
-        Map<String, String> data = hashMap( "name", "patient" );
-
-        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
-        assertNull( getError( node ) );
-        //allow patients to add doctors as their followers
-        addPermission( orgname, applicationName, adminToken, "patient",
-                "delete,post:/users/*/following/users/${user}" );
-
-        assertNull( getError( node ) );
-        // create examplepatient
-        UUID patientId =
-                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "examplepatient",
-                        "examplepatient@apigee.com" );
-        assertNotNull( patientId );
-
-        // create exampledoctor
-        UUID doctorId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "exampledoctor",
-                "exampledoctor@apigee.com" );
-        assertNotNull( doctorId );
-
-
-        // assign examplepatient the patient role
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/%s/roles/patient", orgname, applicationName, patientId.toString() ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-
-        String patientToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), patientId, 0 );
-
-        node = mapper.readTree( resource().path( String
-                .format( "/%s/%s/users/%s/following/users/%s", orgname, applicationName, "exampledoctor",
-                        "examplepatient" ) ).queryParam( "access_token", patientToken )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
-        logNode( node );
-    }
-
-
-    private Map<String, String> buildOrgAppParams() {
-        UUID id = UUIDUtils.newTimeUUID();
-        Map<String, String> props =
-                hashMap( "username", "wcpermadmin" ).map( "orgName", "orgnamewcperm" ).map( "appName", "test" )
-                        .map( "password", "password" )
-                        .map( "email", String.format( "email%s@apigee.com", id.toString() ) );
-
-        return props;
-    }
-
-
-    /**
-     * Create the user, check there are no errors
-     *
-     * @return the userid
-     */
-    private UUID createRoleUser( UUID orgId, UUID appId, String adminToken, String username, String email )
-            throws Exception {
-
-        Map<String, String> props = hashMap( "email", email ).map( "username", username ).map( "name", username )
-                .map( "password", "password" );
-
-        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/users", orgId, appId ) )
-                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, props ));
-
-        assertNull( getError( node ) );
-
-        UUID userId = UUID.fromString( getEntity( node, 0 ).get( "uuid" ).asText() );
-
-        // manually activate user
-        setup.getMgmtSvc().activateAppUser( appId, userId );
-
-        return userId;
-    }
-
-
-    /** Test adding the permission to the role */
-    private void addPermission( String orgname, String appname, String adminToken, String rolename, String grant ) throws IOException {
-        Map<String, String> props = hashMap( "permission", grant );
-
-        String rolePath = String.format( "/%s/%s/roles/%s/permissions", orgname, appname, rolename );
-
-        JsonNode node = mapper.readTree( resource().path( rolePath ).queryParam( "access_token", adminToken )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .put( String.class, props ));
-
-        assertNull( getError( node ) );
-
-        node = mapper.readTree( resource().path( rolePath ).queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
-                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        ArrayNode data = ( ArrayNode ) node.get( "data" );
-
-        Iterator<JsonNode> iterator = data.elements();
-
-        while ( iterator.hasNext() ) {
-            if ( grant.equals( iterator.next().asText() ) ) {
-                return;
-            }
-        }
-
-        fail( String.format( "didn't find grant %s in the results", grant ) );
-    }
-
-
-    /** Test adding the permission to the role */
-    private void addPermission( String orgname, String appname, String rolename, String grant ) throws IOException {
-        Map<String, String> props = hashMap( "permission", grant );
-
-        String rolePath = String.format( "/%s/%s/roles/%s/permissions", orgname, appname, rolename );
-
-        JsonNode node = mapper.readTree( resource().path( rolePath ).accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                        .put( String.class, props ));
-
-        assertNull( getError( node ) );
-
-        node = mapper.readTree( resource().path( rolePath ).accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
-                .get( String.class ));
-
-        ArrayNode data = ( ArrayNode ) node.get( "data" );
-
-        Iterator<JsonNode> iterator = data.elements();
-
-        while ( iterator.hasNext() ) {
-            if ( grant.equals( iterator.next().asText() ) ) {
-                return;
-            }
-        }
-
-        fail( String.format( "didn't find grant %s in the results", grant ) );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/RetrieveUsersTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/RetrieveUsersTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/RetrieveUsersTest.java
deleted file mode 100644
index 9c7a968..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/users/RetrieveUsersTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.users;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import static org.junit.Assert.assertEquals;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class RetrieveUsersTest extends AbstractRestIT {
-    private static final Logger log = LoggerFactory.getLogger( RetrieveUsersTest.class );
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test // USERGRID-1222
-    public void queryForUsername() throws IOException {
-        CustomCollection users = context.collection( "users" );
-
-        Map props = new HashMap();
-
-        props.put( "username", "Alica" );
-        users.create( props );
-
-        props.put( "username", "Bob" );
-        users.create( props );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select *";
-        String incorrectQuery = "select * where username = 'Alica'";
-
-        assertEquals( users.entityValue( query, "username", 0 ), users.entityValue( incorrectQuery, "username", 0 ) );
-    }
-
-
-    @Test // USERGRID-1727
-    public void userEntityDictionaryHasRoles() throws IOException {
-        CustomCollection users = context.collection( "users" );
-
-        Map props = new HashMap();
-        props.put( "username", "Nina" );
-
-        JsonNode response = users.create( props );
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        JsonNode entity = response.get( "entities" ).get( 0 );
-        JsonNode metadata = entity.get( "metadata" );
-        JsonNode sets = metadata.get( "sets" );
-        JsonNode rolenames = sets.get( "rolenames" );
-        Assert.assertTrue( "rolenames URL ends with /roles", rolenames.asText().endsWith( "/roles" ) );
-    }
-}


[7/8] incubator-usergrid git commit: removed awscluster changes

Posted by ro...@apache.org.
removed awscluster changes


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

Branch: refs/heads/two-dot-o-rest-refactor
Commit: cc08a047855d404cbe601c9c8f0a344cda90d8f0
Parents: 3993f08
Author: amuramoto <am...@apigee.com>
Authored: Wed Sep 17 14:11:16 2014 -0700
Committer: amuramoto <am...@apigee.com>
Committed: Wed Sep 17 14:11:16 2014 -0700

----------------------------------------------------------------------
 .../main/dist/init_instance/init_db_server.sh   |  3 ---
 .../main/dist/init_instance/init_rest_server.sh | 20 ++++++++++----------
 .../dist/init_instance/install_elasticsearch.sh |  8 ++++----
 3 files changed, 14 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/cc08a047/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/init_db_server.sh b/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
index 3ffca66..b9c4f56 100644
--- a/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
+++ b/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
@@ -67,9 +67,6 @@ cd /usr/share/usergrid/init_instance
 cd /usr/share/usergrid/init_instance
 ./create_keyspaces.sh
 
-#Increase file descriptors for Elasticsearch
-sed -i.bak "s/#@student        -       maxlogins       4/*\t\t\-\tnofile\t\t${NOFILE}\nroot\t\t\-\tnofile\t\t10000"/ /etc/security/limits.conf
-
 # tag last so we can see in the console that the script ran to completion
 cd /usr/share/usergrid/scripts
 groovy tag_instance.groovy

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/cc08a047/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh b/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
index 5cdf10a..fdc83cd 100644
--- a/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
+++ b/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
@@ -51,8 +51,7 @@ cd /usr/share/usergrid/init_instance
 ./install_yourkit.sh
 
 # set Tomcat memory and threads based on instance type
-export NOFILE=50000
-export TOMCAT_CONNECTIONS=10000
+export NOFILE=100000
 case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
 'm1.small' )
     export TOMCAT_RAM=1250M
@@ -70,29 +69,30 @@ case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
     export TOMCAT_RAM=12G
     export TOMCAT_THREADS=2000
 ;;
-'m3.large' )
-    export TOMCAT_RAM=6G
-    export TOMCAT_THREADS=6000
-;;
 'm3.xlarge' )
     export TOMCAT_RAM=12G
-    export TOMCAT_THREADS=8000
+    export TOMCAT_THREADS=3300
+;;
+'m3.large' )
+    export TOMCAT_RAM=6G
+    export TOMCAT_THREADS=1600
 ;;
 'c3.2xlarge' )
     export TOMCAT_RAM=12G
-    export TOMCAT_THREADS=10000
+    export TOMCAT_THREADS=2000
 ;;
 'c3.4xlarge' )
     export TOMCAT_RAM=24G
-    export TOMCAT_THREADS=12000
+    export TOMCAT_THREADS=4000
 esac
 
+export TOMCAT_CONNECTIONS=10000
 sed -i.bak "s/Xmx128m/Xmx${TOMCAT_RAM} -Xms${TOMCAT_RAM} -Dlog4j\.configuration=file:\/usr\/share\/usergrid\/lib\/log4j\.properties/g" /etc/default/tomcat7
 sed -i.bak "s/<Connector/<Connector maxThreads=\"${TOMCAT_THREADS}\" acceptCount=\"${TOMCAT_THREADS}\" maxConnections=\"${TOMCAT_CONNECTIONS}\"/g" /var/lib/tomcat7/conf/server.xml
 
 # set file limits
 sed -i.bak "s/# \/etc\/init\.d\/tomcat7 -- startup script for the Tomcat 6 servlet engine/ulimit -n ${NOFILE}/" /etc/init.d/tomcat7
-sed -i.bak "s/#@student        -       maxlogins       4/*\t\t\-\tnofile\t\t${NOFILE}\nroot\t\t\-\tnofile\t\t${NOFILE}"/ /etc/security/limits.conf
+sed -i.bak "s/@student/a *\t\thard\tnofile\t\t${NOFILE}\n*\t\tsoft\tnofile\t\t${NOFILE}" /etc/security/limits.conf
 echo "$NOFILE" | sudo tee > /proc/sys/fs/nr_open
 echo "$NOFILE" | sudo tee > /proc/sys/fs/file-max
 cat >> /etc/pam.d/su << EOF

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/cc08a047/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
index 51f7c60..d398591 100644
--- a/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
+++ b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
@@ -57,16 +57,16 @@ case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
     export ES_HEAP_SIZE=5G
 ;;
 'm3.xlarge' )
-    export ES_HEAP_SIZE=10G
+    export ES_HEAP_SIZE=5G
 ;;
 'm3.large' )
-    export ES_HEAP_SIZE=5G
+    export ES_HEAP_SIZE=2G
 ;;
 'c3.2xlarge' )
-    export ES_HEAP_SIZE=10G
+    export ES_HEAP_SIZE=4G
 ;;
 'c3.4xlarge' )
-    export ES_HEAP_SIZE=15G
+    export ES_HEAP_SIZE=12G
 esac
 
 cat >> /etc/default/elasticsearch << EOF


[4/8] incubator-usergrid git commit: organized rest IT

Posted by ro...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/RetrieveUsersTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/RetrieveUsersTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/RetrieveUsersTest.java
new file mode 100644
index 0000000..da7d59e
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/RetrieveUsersTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.collection.users;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import static org.junit.Assert.assertEquals;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class RetrieveUsersTest extends AbstractRestIT {
+    private static final Logger log = LoggerFactory.getLogger( RetrieveUsersTest.class );
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test // USERGRID-1222
+    public void queryForUsername() throws IOException {
+        CustomCollection users = context.collection( "users" );
+
+        Map props = new HashMap();
+
+        props.put( "username", "Alica" );
+        users.create( props );
+
+        props.put( "username", "Bob" );
+        users.create( props );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select *";
+        String incorrectQuery = "select * where username = 'Alica'";
+
+        assertEquals( users.entityValue( query, "username", 0 ), users.entityValue( incorrectQuery, "username", 0 ) );
+    }
+
+
+    @Test // USERGRID-1727
+    public void userEntityDictionaryHasRoles() throws IOException {
+        CustomCollection users = context.collection( "users" );
+
+        Map props = new HashMap();
+        props.put( "username", "Nina" );
+
+        JsonNode response = users.create( props );
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        JsonNode entity = response.get( "entities" ).get( 0 );
+        JsonNode metadata = entity.get( "metadata" );
+        JsonNode sets = metadata.get( "sets" );
+        JsonNode rolenames = sets.get( "rolenames" );
+        Assert.assertTrue( "rolenames URL ends with /roles", rolenames.asText().endsWith( "/roles" ) );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/UserResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/UserResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/UserResourceIT.java
new file mode 100644
index 0000000..43e2b4f
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/UserResourceIT.java
@@ -0,0 +1,1418 @@
+/*
+ * 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.collection.users;
+
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.java.client.Client.Query;
+import org.apache.usergrid.java.client.entities.Activity;
+import org.apache.usergrid.java.client.entities.Activity.ActivityObject;
+import org.apache.usergrid.java.client.entities.Entity;
+import org.apache.usergrid.java.client.entities.User;
+import org.apache.usergrid.java.client.response.ApiResponse;
+
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.management.ApplicationInfo;
+import org.apache.usergrid.management.OrganizationInfo;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.applications.utils.UserRepo;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import com.sun.jersey.api.client.ClientResponse.Status;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.apache.usergrid.rest.applications.utils.TestUtils.getIdFromSearchResults;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+
+/**
+ * @author zznate
+ * @author tnine
+ */
+@Concurrent()
+public class UserResourceIT extends AbstractRestIT {
+
+    private static Logger log = LoggerFactory.getLogger( UserResourceIT.class );
+
+
+    @Test
+    public void usernameQuery() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "username = 'unq_user*'";
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user1" ), getIdFromSearchResults( node, 0 ) );
+        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user2" ), getIdFromSearchResults( node, 1 ) );
+        assertEquals( UserRepo.INSTANCE.getByUserName( "unq_user3" ), getIdFromSearchResults( node, 2 ) );
+    }
+
+
+    @Test
+    public void nameQuery() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "name = 'John*'";
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( UserRepo.INSTANCE.getByUserName( "user2" ), getIdFromSearchResults( node, 0 ) );
+        assertEquals( UserRepo.INSTANCE.getByUserName( "user3" ), getIdFromSearchResults( node, 1 ) );
+    }
+
+
+    @Test
+    public void nameQueryByUUIDs() throws Exception {
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "select uuid name = 'John*'";
+
+        ApplicationInfo appInfo = setup.getMgmtSvc().getApplicationInfo( "test-organization/test-app" );
+        OrganizationInfo orgInfo = setup.getMgmtSvc().getOrganizationByName( "test-organization" );
+
+        resource().path( "/" + orgInfo.getUuid() + "/" + appInfo.getId() + "/users" ).queryParam( "ql", ql )
+                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
+    }
+
+
+    @Test
+    public void nameFullTextQuery() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "name contains 'Smith' order by name ";
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( UserRepo.INSTANCE.getByUserName( "user1" ), getIdFromSearchResults( node, 0 ) );
+        assertEquals( UserRepo.INSTANCE.getByUserName( "user2" ), getIdFromSearchResults( node, 1 ) );
+        assertEquals( UserRepo.INSTANCE.getByUserName( "user3" ), getIdFromSearchResults( node, 2 ) );
+    }
+
+
+    /**
+     * Tests that when a full text index is run on a field that isn't full text indexed an error is thrown
+     */
+    @Ignore("No longer relevant because all text fields are full-text indexed with Core Persistence")
+    @Test(expected = UniformInterfaceException.class)
+    public void fullTextQueryNotFullTextIndexed() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "username contains 'user' ";
+
+        resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
+    }
+
+
+    /**
+     * Tests that when a full text index is run on a field that isn't full text indexed an error is thrown
+     */
+    @Ignore("This test is being ignored as users ")
+    @Test(expected = UniformInterfaceException.class)
+    public void fullQueryNotIndexed() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        String ql = "picture = 'foo' ";
+
+        resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
+    }
+
+
+    /**
+     * Test that when activity is pushed with not actor, it's set to the user who created it
+     */
+    @Test
+    public void emtpyActorActivity() throws IOException {
+        UserRepo.INSTANCE.load( resource(), access_token );
+        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
+        refreshIndex("test-organization", "test-app");
+
+        Activity activity = new Activity();
+        activity.setProperty( "email", "rod@rodsimpson.com" );
+        activity.setProperty( "verb", "POST" );
+        activity.setProperty( "content", "Look! more new content" );
+
+        ApiResponse response = client.postUserActivity( userId.toString(), activity );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        Entity entity = response.getEntities().get( 0 );
+
+        UUID activityId = entity.getUuid();
+
+        assertNotNull( activityId );
+
+        JsonNode actor = getActor( entity );
+
+        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
+
+        assertEquals( userId, actorId );
+
+        assertEquals( "user1@apigee.com", actor.get( "email" ).asText() );
+    }
+
+
+    /**
+     * Insert the uuid and email if they're empty in the request
+     */
+    @Test
+    public void noUUIDorEmail() throws IOException {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
+
+        Activity activity = new Activity();
+        activity.setProperty( "email", "rod@rodsimpson.com" );
+        activity.setProperty( "verb", "POST" );
+        activity.setProperty( "content", "Look! more new content" );
+
+        // same as above, but with actor partially filled out
+
+        ActivityObject actorPost = new ActivityObject();
+        actorPost.setDisplayName( "Dino" );
+
+        activity.setActor( actorPost );
+
+        ApiResponse response = client.postUserActivity( userId.toString(), activity );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        Entity entity = response.getEntities().get( 0 );
+
+        UUID activityId = entity.getUuid();
+
+        assertNotNull( activityId );
+
+        JsonNode actor = getActor( entity );
+
+        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
+
+        assertEquals( userId, actorId );
+
+        assertEquals( "user1@apigee.com", actor.get( "email" ).asText() );
+    }
+
+
+    /**
+     * Don't touch the UUID when it's already set in the JSON
+     */
+    @Test
+    public void ignoreUUIDandEmail() throws IOException {
+        UserRepo.INSTANCE.load( resource(), access_token );
+        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
+        refreshIndex("test-organization", "test-app");
+
+        UUID testUUID = UUIDUtils.newTimeUUID();
+        String testEmail = "foo@bar.com";
+
+        // same as above, but with actor partially filled out
+        Activity activity = new Activity();
+        activity.setProperty( "email", "rod@rodsimpson.com" );
+        activity.setProperty( "verb", "POST" );
+        activity.setProperty( "content", "Look! more new content" );
+
+        // same as above, but with actor partially filled out
+
+        ActivityObject actorPost = new ActivityObject();
+        actorPost.setDisplayName( "Dino" );
+        actorPost.setUuid( testUUID );
+        actorPost.setDynamicProperty( "email", testEmail );
+
+        activity.setActor( actorPost );
+
+        ApiResponse response = client.postUserActivity( userId.toString(), activity );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        Entity entity = response.getEntities().get( 0 );
+
+        UUID activityId = entity.getUuid();
+
+        assertNotNull( activityId );
+
+        JsonNode actor = getActor( entity );
+
+        UUID actorId = UUIDUtils.tryGetUUID( actor.get( "uuid" ).textValue() );
+
+        assertEquals( testUUID, actorId );
+
+        assertEquals( testEmail, actor.get( "email" ).asText() );
+    }
+
+
+    /**
+     * Test that when activity is pushed with not actor, it's set to the user who created it
+     */
+    @Test
+    public void userActivitiesDefaultOrder() throws IOException {
+        UserRepo.INSTANCE.load( resource(), access_token );
+        UUID userId = UserRepo.INSTANCE.getByUserName( "user1" );
+        refreshIndex("test-organization", "test-app");
+
+        Activity activity = new Activity();
+        activity.setProperty( "email", "rod@rodsimpson.com" );
+        activity.setProperty( "verb", "POST" );
+        activity.setProperty( "content", "activity 1" );
+
+        ApiResponse response = client.postUserActivity( userId.toString(), activity );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        Entity entity = response.getFirstEntity();
+
+        UUID firstActivityId = entity.getUuid();
+
+        activity = new Activity();
+        activity.setProperty( "email", "rod@rodsimpson.com" );
+        activity.setProperty( "verb", "POST" );
+        activity.setProperty( "content", "activity 2" );
+
+        response = client.postUserActivity( userId.toString(), activity );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        entity = response.getFirstEntity();
+
+        UUID secondActivityId = entity.getUuid();
+
+        Query query = client.queryActivity();
+
+        entity = query.getResponse().getEntities().get( 0 );
+
+        assertEquals( secondActivityId, entity.getUuid() );
+
+        entity = query.getResponse().getEntities().get( 1 );
+
+        assertEquals( firstActivityId, entity.getUuid() );
+    }
+
+
+    @Test
+    public void getUserWIthEmailUsername() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username = "username-email" + "@usergrid.org";
+        String name = "name" + id;
+        String email = "email" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username, name, email, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        Entity userEntity = response.getEntities().get( 0 );
+
+        // get the user with username property that has an email value
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + username )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( username, node.get( "entities" ).get( 0 ).get( "username" ).asText() );
+        assertEquals( name, node.get( "entities" ).get( 0 ).get( "name" ).asText() );
+        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).asText() );
+
+        // get the user with email property value
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + email )
+                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( username, node.get( "entities" ).get( 0 ).get( "username" ).asText() );
+        assertEquals( name, node.get( "entities" ).get( 0 ).get( "name" ).asText() );
+        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).asText() );
+    }
+
+
+    /**
+     * Tests that when querying all users, we get the same result size when using "order by"
+     */
+    @Test
+    public void resultSizeSame() throws IOException {
+        UserRepo.INSTANCE.load( resource(), access_token );
+
+        refreshIndex("test-organization", "test-app");
+
+        UUID userId1 = UserRepo.INSTANCE.getByUserName( "user1" );
+        UUID userId2 = UserRepo.INSTANCE.getByUserName( "user2" );
+        UUID userId3 = UserRepo.INSTANCE.getByUserName( "user3" );
+
+        Query query = client.queryUsers();
+
+        ApiResponse response = query.getResponse();
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        int nonOrderedSize = response.getEntities().size();
+
+        query = client.queryUsers( "order by username" );
+
+        response = query.getResponse();
+
+        int orderedSize = response.getEntities().size();
+
+        assertEquals( "Sizes match", nonOrderedSize, orderedSize );
+
+        int firstEntityIndex = getEntityIndex( userId1, response );
+
+        int secondEntityIndex = getEntityIndex( userId2, response );
+
+        int thirdEntityIndex = getEntityIndex( userId3, response );
+
+        assertTrue( "Ordered correctly", firstEntityIndex < secondEntityIndex );
+
+        assertTrue( "Ordered correctly", secondEntityIndex < thirdEntityIndex );
+    }
+
+
+    private int getEntityIndex( UUID entityId, ApiResponse response ) {
+        List<Entity> entities = response.getEntities();
+
+        for ( int i = 0; i < entities.size(); i++ ) {
+            if ( entityId.equals( entities.get( i ).getUuid() ) ) {
+                return i;
+            }
+        }
+
+        return -1;
+    }
+
+
+    @Test
+    public void clientNameQuery() {
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username = "username" + id;
+        String name = "name" + id;
+
+        ApiResponse response = client.createUser( username, name, id + "@usergrid.org", "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID createdId = response.getEntities().get( 0 ).getUuid();
+
+        Query results = client.queryUsers( String.format( "name = '%s'", name ) );
+        User user = results.getResponse().getEntities( User.class ).get( 0 );
+
+        assertEquals( createdId, user.getUuid() );
+    }
+
+
+    @Test
+    public void deleteUser() throws IOException  {
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username = "username" + id;
+        String name = "name" + id;
+
+        ApiResponse response = client.createUser( username, name, id + "@usergrid.org", "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID createdId = response.getEntities().get( 0 ).getUuid();
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        assertNull( node.get( "errors" ) );
+
+        Query results = client.queryUsers( String.format( "username = '%s'", name ) );
+        assertEquals( 0, results.getResponse().getEntities( User.class ).size() );
+
+        // now create that same user again, it should work
+        response = client.createUser( username, name, id + "@usergrid.org", "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        createdId = response.getEntities().get( 0 ).getUuid();
+
+        assertNotNull( createdId );
+    }
+
+
+    @Test
+    public void singularCollectionName() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username = "username1" + id;
+        String name = "name1" + id;
+        String email = "email1" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username, name, email, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        username = "username2" + id;
+        name = "name2" + id;
+        email = "email2" + id + "@usergrid.org";
+
+        response = client.createUser( username, name, email, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        // now create a connection of "likes" between the first user and the
+        // second using pluralized form
+
+        // plural collection name
+        String path = String.format( "/test-organization/test-app/users/%s/conn1/%s", firstCreatedId, secondCreatedId );
+
+        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+        // singular collection name
+        path = String.format( "/test-organization/test-app/user/%s/conn2/%s", firstCreatedId, secondCreatedId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+        path = String.format( "/test-organization/test-app/users/%s/conn1", firstCreatedId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        path = String.format( "/test-organization/test-app/user/%s/conn1", firstCreatedId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        path = String.format( "/test-organization/test-app/users/%s/conn2", firstCreatedId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        path = String.format( "/test-organization/test-app/user/%s/conn2", firstCreatedId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+    }
+
+
+    @Test
+    public void connectionByNameAndType() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username1 = "username1" + id;
+        String name1 = "name1" + id;
+        String email1 = "email1" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username1, name1, email1, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        String username2 = "username2" + id;
+        String name2 = "name2" + id;
+        String email2 = "email2" + id + "@usergrid.org";
+
+        response = client.createUser( username2, name2, email2, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        // now create a connection of "likes" between the first user and the
+        // second using pluralized form
+
+        // named entity in collection name
+        String path = String.format( "/test-organization/test-app/users/%s/conn1/users/%s", firstCreatedId, username2 );
+
+        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        // named entity in collection name
+        path = String.format( "/test-organization/test-app/users/%s/conn2/users/%s", username1, username2 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+    }
+
+
+    /**
+     * Usergrid-1222 test
+     */
+    @Test
+    public void connectionQuerybyEmail() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String name = "name1" + id;
+        String email = "email1" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( email, name, email, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID userId = response.getEntities().get( 0 ).getUuid();
+
+        Entity role = new Entity( "role" );
+        role.setProperty( "name", "connectionQuerybyEmail1" );
+
+        response = client.createEntity( role );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        UUID roleId1 = response.getEntities().get( 0 ).getUuid();
+
+        //add permissions to the role
+
+        Map<String, String> perms = new HashMap<String, String>();
+        perms.put( "permission", "get:/stuff/**" );
+
+        String path = String.format( "/test-organization/test-app/roles/%s/permissions", roleId1 );
+
+        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, perms ));
+
+
+        //Create the second role
+        role = new Entity( "role" );
+        role.setProperty( "name", "connectionQuerybyEmail2" );
+
+        response = client.createEntity( role );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        UUID roleId2 = response.getEntities().get( 0 ).getUuid();
+
+        //add permissions to the role
+
+        perms = new HashMap<String, String>();
+        perms.put( "permission", "get:/stuff/**" );
+
+        path = String.format( "/test-organization/test-app/roles/%s/permissions", roleId2 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, perms ));
+
+        refreshIndex("test-organization", "test-app");
+
+        //connect the entities where role is the root
+        path = String.format( "/test-organization/test-app/roles/%s/users/%s", roleId1, userId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        // now create a connection of "likes" between the first user and the
+        // second using pluralized form
+
+        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+
+        //connect the second role
+        path = String.format( "/test-organization/test-app/roles/%s/users/%s", roleId2, userId );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+
+        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+        //query the second role, it should work
+        path = String.format( "/test-organization/test-app/roles/%s/users", roleId2 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
+                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .get( String.class ));
+
+        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+
+        //query the first role, it should work
+        path = String.format( "/test-organization/test-app/roles/%s/users", roleId1 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
+                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .get( String.class ));
+
+        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+
+        //now delete the first role
+        path = String.format( "/test-organization/test-app/roles/%s", roleId1 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        //query the first role, it should 404
+        path = String.format( "/test-organization/test-app/roles/%s/users", roleId1 );
+
+        refreshIndex("test-organization", "test-app");
+
+        try {
+            node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
+                             .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .get( String.class ));
+        }
+        catch ( UniformInterfaceException e ) {
+            assertEquals( Status.NOT_FOUND, e.getResponse().getClientResponseStatus() );
+        }
+
+        //query the second role, it should work
+        path = String.format( "/test-organization/test-app/roles/%s/users", roleId2 );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token )
+                         .queryParam( "ql", "select%20*%20where%20username%20=%20'" + email + "'" )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .get( String.class ));
+
+        assertEquals( userId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+    }
+
+
+    @Test
+    public void connectionByNameAndDynamicType() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username1 = "username1" + id;
+        String name1 = "name1" + id;
+        String email1 = "email1" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username1, name1, email1, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID firstCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        String name = "pepperoni";
+
+        Entity pizza = new Entity();
+        pizza.setProperty( "name", name );
+        pizza.setType( "pizza" );
+
+        response = client.createEntity( pizza );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        UUID secondCreatedId = response.getEntities().get( 0 ).getUuid();
+
+        refreshIndex("test-organization", "test-app");
+
+        // now create a connection of "likes" between the first user and the
+        // second using pluralized form
+
+        // named entity in collection name
+        String path = String.format( "/test-organization/test-app/users/%s/conn1/pizzas/%s", firstCreatedId,
+                secondCreatedId );
+
+        JsonNode node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                          .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+        // named entity in collection name
+        path = String.format( "/test-organization/test-app/users/%s/conn2/pizzas/%s", username1, name );
+
+        node = mapper.readTree( resource().path( path ).queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertEquals( secondCreatedId.toString(), getEntity( node, 0 ).get( "uuid" ).asText() );
+    }
+
+
+    @Test
+    public void nameUpdate() throws IOException {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String username = "username" + id;
+        String name = "name" + id;
+        String email = "email" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username, name, email, "password" );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        Entity userEntity = response.getEntities().get( 0 );
+
+        // attempt to log in
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/token" ).queryParam( "username", username )
+                                  .queryParam( "password", "password" ).queryParam( "grant_type", "password" )
+                                  .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                                  .get( String.class ));
+
+        assertEquals( username, node.get( "user" ).get( "username" ).asText() );
+        assertEquals( name, node.get( "user" ).get( "name" ).asText() );
+        assertEquals( email, node.get( "user" ).get( "email" ).asText() );
+
+        // now update the name and email
+        String newName = "newName";
+        String newEmail = "newEmail" + UUIDUtils.newTimeUUID() + "@usergrid.org";
+
+        userEntity.setProperty( "name", newName );
+        userEntity.setProperty( "email", newEmail );
+        userEntity.setProperty( "password", "newp2ssword" );
+        userEntity.setProperty( "pin", "newp1n" );
+
+        node = mapper.readTree( resource().path( String.format( "/test-organization/test-app/users/%s", username ) )
+                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, userEntity.getProperties() ));
+
+        refreshIndex("test-organization", "test-app");
+
+        // now see if we've updated
+        node = mapper.readTree( resource().path( "/test-organization/test-app/token" ).queryParam( "username", username )
+                         .queryParam( "password", "password" ).queryParam( "grant_type", "password" )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .get( String.class ));
+
+        assertEquals( username, node.get( "user" ).get( "username" ).asText() );
+        assertEquals( newName, node.get( "user" ).get( "name" ).asText() );
+        assertEquals( newEmail, node.get( "user" ).get( "email" ).asText() );
+        assertNull( newEmail, node.get( "user" ).get( "password" ) );
+        assertNull( newEmail, node.get( "user" ).get( "pin" ) );
+    }
+
+
+    /**
+     *
+     * @return
+     */
+    public JsonNode getActor( Entity entity ) {
+        return entity.getProperties().get( "actor" );
+    }
+
+
+    @Test
+    public void test_POST_batch() throws IOException {
+
+        log.info( "UserResourceIT.test_POST_batch" );
+
+        JsonNode node = null;
+
+        List<Map<String, Object>> batch = new ArrayList<Map<String, Object>>();
+
+        Map<String, Object> properties = new LinkedHashMap<String, Object>();
+        properties.put( "username", "test_user_1" );
+        properties.put( "email", "user1@test.com" );
+        batch.add( properties );
+
+        properties = new LinkedHashMap<String, Object>();
+        properties.put( "username", "test_user_2" );
+        batch.add( properties );
+
+        properties = new LinkedHashMap<String, Object>();
+        properties.put( "username", "test_user_3" );
+        batch.add( properties );
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "access_token", access_token )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .post( String.class, batch ));
+
+        assertNotNull( node );
+        logNode( node );
+    }
+
+
+    @Test
+    public void deactivateUser() throws IOException {
+
+        UUID newUserUuid = UUIDUtils.newTimeUUID();
+
+        String userName = String.format( "test%s", newUserUuid );
+
+        Map<String, String> payload =
+                hashMap( "email", String.format( "%s@anuff.com", newUserUuid ) ).map( "username", userName )
+                                                                                .map( "name", "Ed Anuff" )
+                                                                                .map( "password", "sesame" )
+                                                                                .map( "pin", "1234" );
+
+        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
+                  .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                  .post( String.class, payload );
+
+        refreshIndex("test-organization", "test-app");
+
+        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
+                          .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                          .get( String.class ));
+
+        // disable the user
+
+        Map<String, String> data = new HashMap<String, String>();
+
+        response = mapper.readTree( resource().path( String.format( "/test-organization/test-app/users/%s/deactivate", userName ) )
+                             .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                             .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+
+        JsonNode entity = getEntity( response, 0 );
+
+        assertFalse( entity.get( "activated" ).asBoolean() );
+        assertNotNull( entity.get( "deactivated" ) );
+    }
+
+
+    @Test
+    public void test_PUT_password_fail() {
+
+        boolean fail = false;
+        try {
+            ApiResponse changeResponse = client.changePassword( "edanuff", "foo", "bar" );
+            fail = changeResponse.getError() != null;
+        }
+        catch ( Exception e ) {
+            fail = true;
+        }
+        assertTrue( fail );
+    }
+
+
+    @Test
+    public void test_GET_user_ok() throws InterruptedException, IOException {
+
+        // TODO figure out what is being overridden? why 400?
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" )
+                .queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE )
+                .get( String.class ));
+
+        String uuid = node.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
+        String email = node.get( "entities" ).get( 0 ).get( "email" ).textValue();
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + uuid )
+                .queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE )
+                .get( String.class ));
+        
+        logNode( node );
+        assertEquals( email, node.get( "entities" ).get( 0 ).get( "email" ).textValue() );
+    }
+
+
+    @Test
+    public void test_PUT_password_ok() {
+
+        ApiResponse response = client.changePassword( "edanuff", "sesame", "sesame1" );
+
+        assertNull( response.getError() );
+
+        response = client.authorizeAppUser( "ed@anuff.com", "sesame1" );
+
+        assertNull( response.getError() );
+
+        // if this was successful, we need to re-set the password for other
+        // tests
+        response = client.changePassword( "edanuff", "sesame1", "sesame" );
+
+        assertNull( response.getError() );
+    }
+
+
+    @Test
+    public void setUserPasswordAsAdmin()  throws IOException {
+
+        String newPassword = "foo";
+
+        Map<String, String> data = new HashMap<String, String>();
+        data.put( "newpassword", newPassword );
+
+        // change the password as admin. The old password isn't required
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/password" )
+                                  .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+
+        assertNull( getError( node ) );
+
+        ApiResponse response = client.authorizeAppUser( "ed@anuff.com", newPassword );
+
+        assertNull( response.getError() );
+    }
+
+
+    @Test
+    public void passwordMismatchErrorUser() {
+        String origPassword = "foo";
+        String newPassword = "bar";
+
+        Map<String, String> data = new HashMap<String, String>();
+        data.put( "newpassword", origPassword );
+
+        // now change the password, with an incorrect old password
+
+        data.put( "oldpassword", origPassword );
+        data.put( "newpassword", newPassword );
+
+        Status responseStatus = null;
+        try {
+            resource().path( "/test-organization/test-app/users/edanuff/password" ).accept( MediaType.APPLICATION_JSON )
+                      .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data );
+        }
+        catch ( UniformInterfaceException uie ) {
+            responseStatus = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertNotNull( responseStatus );
+
+        assertEquals( Status.BAD_REQUEST, responseStatus );
+    }
+
+
+    @Test
+    public void addRemoveRole() throws IOException  {
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String roleName = "rolename" + id;
+
+        String username = "username" + id;
+        String name = "name" + id;
+        String email = "email" + id + "@usergrid.org";
+
+        ApiResponse response = client.createUser( username, name, email, "password" );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+        refreshIndex("test-organization", "test-app");
+
+        UUID createdId = response.getEntities().get( 0 ).getUuid();
+
+        // create Role
+
+        String json = "{\"title\":\"" + roleName + "\",\"name\":\"" + roleName + "\"}";
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" )
+            .queryParam( "access_token", access_token )
+            .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+            .post( String.class, json ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        // add Role
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles/" + roleName )
+            .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+            .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+        assertNotNull( node.get( "entities" ) );
+        assertNotNull( node.get( "entities" ).get( 0 ) );
+        assertNotNull( node.get( "entities" ).get( 0 ).get( "name" ) );
+        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles" )
+            .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+            .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertNotNull( node.get( "entities" ) );
+        assertNotNull( node.get( "entities" ).get( 0 ) );
+        assertNotNull( node.get( "entities" ).get( 0 ).get( "name" ) );
+        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
+
+
+        // remove Role
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles/" + roleName )
+                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + createdId + "/roles" )
+                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "entities" ).size() == 0 );
+    }
+
+
+    @Test
+    public void revokeToken() throws Exception {
+
+        String token1 = super.userToken( "edanuff", "sesame" );
+        String token2 = super.userToken( "edanuff", "sesame" );
+
+        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token1 )
+                          .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                          .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token2 )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        // now revoke the tokens
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/revoketokens" )
+                             .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
+                             .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        // the tokens shouldn't work
+
+        Status status = null;
+
+        try {
+            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token1 )
+                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                              .get( String.class ));
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        status = null;
+
+        try {
+            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token2 )
+                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                              .get( String.class ));
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        String token3 = super.userToken( "edanuff", "sesame" );
+        String token4 = super.userToken( "edanuff", "sesame" );
+
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token3 )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token4 )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        // now revoke the token3
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff/revoketoken" )
+                             .queryParam( "access_token", token3 ).queryParam( "token", token3 )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .post( String.class ));
+
+        // the token3 shouldn't work
+
+        status = null;
+
+        try {
+            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token3 )
+                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                              .get( String.class ));
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        status = null;
+
+        try {
+            response = mapper.readTree( resource().path( "/test-organization/test-app/users/edanuff" ).queryParam( "access_token", token4 )
+                              .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                              .get( String.class ));
+
+            status = Status.OK;
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.OK, status );
+    }
+
+
+    @Test
+    public void getToken() throws Exception {
+
+        createUser( "test_1", "test_1@test.com", "test123", "Test1 User" ); // client.setApiUrl(apiUrl);
+        createUser( "test_2", "test_2@test.com", "test123", "Test2 User" ); // client.setApiUrl(apiUrl);
+        createUser( "test_3", "test_3@test.com", "test123", "Test3 User" ); // client.setApiUrl(apiUrl);
+        refreshIndex("test-organization", "test-app");
+
+        ApplicationInfo appInfo = setup.getMgmtSvc().getApplicationInfo( "test-organization/test-app" );
+
+        String clientId = setup.getMgmtSvc().getClientIdForApplication( appInfo.getId() );
+        String clientSecret = setup.getMgmtSvc().getClientSecretForApplication( appInfo.getId() );
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1/token" ).queryParam( "client_id", clientId )
+                          .queryParam( "client_secret", clientSecret ).accept( MediaType.APPLICATION_JSON )
+                          .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        String user_token_from_client_credentials = node.get( "access_token" ).asText();
+
+        UUID userId = UUID.fromString( node.get( "user" ).get( "uuid" ).asText() );
+        setup.getMgmtSvc().activateAppUser( appInfo.getId(), userId );
+
+        String user_token_from_java = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userId, 1000000 );
+
+        assertNotNull( user_token_from_client_credentials );
+
+        refreshIndex("test-organization", "test-app");
+
+        Status status = null;
+
+        // bad access token
+        try {
+            resource().path( "/test-organization/test-app/users/test_1/token" ).queryParam( "access_token", "blah" )
+                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                      .get( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+            log.info( "Error Response Body: " + uie.getResponse().getEntity( String.class ) );
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        try {
+            resource().path( "/test-organization/test-app/users/test_2/token" )
+                      .queryParam( "access_token", user_token_from_client_credentials )
+                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                      .get( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+            log.info( "Error Response Body: " + uie.getResponse().getEntity( String.class ) );
+        }
+
+        assertEquals( Status.FORBIDDEN, status );
+
+
+        JsonNode response = null;
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1" )
+                             .queryParam( "access_token", user_token_from_client_credentials )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/test_1" )
+                             .queryParam( "access_token", user_token_from_java ).accept( MediaType.APPLICATION_JSON )
+                             .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+
+        setup.getMgmtSvc().deactivateUser( appInfo.getId(), userId );
+
+        refreshIndex("test-organization", "test-app");
+
+        try {
+            resource().path( "/test-organization/test-app/token" ).queryParam( "grant_type", "password" )
+                      .queryParam( "username", "test_1" ).queryParam( "password", "test123" )
+                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                      .get( String.class );
+            fail( "request for deactivated user should fail" );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+            JsonNode body = mapper.readTree( uie.getResponse().getEntity( String.class ));
+            assertEquals( "user not activated", body.findPath( "error_description" ).textValue() );
+        }
+    }
+
+
+    @Test
+    public void delegatePutOnNotFound() throws Exception {
+        String randomName = "user1_" + UUIDUtils.newTimeUUID().toString();
+        createUser( randomName, randomName + "@apigee.com", "password", randomName );
+        refreshIndex("test-organization", "test-app");
+
+        // should update a field
+        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" + randomName )
+                                      .queryParam( "access_token", adminAccessToken )
+                                      .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                                      .get( String.class ));
+        logNode( response );
+        assertNotNull( getEntity( response, 0 ) );
+        // PUT on user
+
+        // PUT a new user
+        randomName = "user2_" + UUIDUtils.newTimeUUID().toString();
+        Map<String, String> payload =
+                hashMap( "email", randomName + "@apigee.com" ).map( "username", randomName ).map( "name", randomName )
+                                                              .map( "password", "password" ).map( "pin", "1234" );
+
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", adminAccessToken )
+                             .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                             .put( String.class, payload ));
+
+        refreshIndex("test-organization", "test-app");
+
+        logNode( response );
+        response = mapper.readTree( resource().path( "/test-organization/test-app/users/" + randomName )
+                             .queryParam( "access_token", adminAccessToken ).accept( MediaType.APPLICATION_JSON )
+                             .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+        logNode( response );
+    }
+
+
+    /**
+     * Test that property queries return properties and entity queries return entities.
+     * https://apigeesc.atlassian.net/browse/USERGRID-1715?
+     */
+    @Test
+    public void queryForUuids() throws Exception {
+
+        {
+            final JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "ql",
+                    "select *" )               // query for entities
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+            assertNotNull( "Entities must exist", response.get( "entities" ) );
+            assertTrue( "Must be some entities", response.get( "entities" ).size() > 0 );
+            assertEquals( "Must be users", "user", response.get( "entities" ).get( 0 ).get( "type" ).asText() );
+            assertNull( "List must not exist", response.get( "list" ) );
+        }
+
+        {
+            final JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/users/" ).queryParam( "ql",
+                    "select uuid" )            // query for uuid properties
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+            assertNotNull( "List must exist", response.get( "list" ) );
+            assertTrue( "Must be some list items", response.get( "list" ).size() > 0 );
+            assertNull( "Entities must not exist", response.get( "entries" ) );
+        }
+    }
+
+
+    @Test
+    public void queryForUserUuids() throws Exception {
+
+        UserRepo.INSTANCE.load( resource(), access_token );
+        refreshIndex("test-organization", "test-app");
+
+        Status status = null;
+
+
+        String ql = "uuid = " + UserRepo.INSTANCE.getByUserName( "user1" );
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/users" ).queryParam( "ql", ql )
+                                  .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                                  .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+
+        Map<String, String> payload = hashMap( "name", "Austin" ).map( "state", "TX" );
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/curts" ).queryParam( "access_token", access_token )
+                         .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                         .post( String.class, payload ));
+
+        UUID userId = UUID.fromString( node.get( "entities" ).get( 0 ).get( "uuid" ).asText() );
+
+        assertNotNull( userId );
+
+        refreshIndex("test-organization", "test-app");
+
+        ql = "uuid = " + userId;
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/curts" ).queryParam( "ql", ql )
+                         .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                         .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertNotNull( node.get( "entities" ).get( 0 ).get( "uuid" ) );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/extensions/TestResource.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/extensions/TestResource.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/extensions/TestResource.java
new file mode 100644
index 0000000..b74a162
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/extensions/TestResource.java
@@ -0,0 +1,51 @@
+/*
+ * 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.collection.users.extensions;
+
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+
+import org.junit.Ignore;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+import org.apache.usergrid.rest.applications.users.AbstractUserExtensionResource;
+
+
+@Ignore("Not a test")
+@Component("TestResource")
+@Scope("prototype")
+@Produces(MediaType.APPLICATION_JSON)
+public class TestResource extends AbstractUserExtensionResource {
+
+    private static Logger log = LoggerFactory.getLogger( TestResource.class );
+
+
+    public TestResource() {
+        log.info( "TestResource" );
+    }
+
+
+    @GET
+    public String sayHello() {
+        return "{\"message\" : \"hello\"" + ( getUserResource().getUserUuid() != null ?
+                                              ", \"user\" : \"" + getUserResource().getUserUuid() + "\"" : "" ) + " }";
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/events/ApplicationRequestCounterIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/events/ApplicationRequestCounterIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/events/ApplicationRequestCounterIT.java
new file mode 100644
index 0000000..bf63844
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/events/ApplicationRequestCounterIT.java
@@ -0,0 +1,97 @@
+/*
+ * 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.events;
+
+
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.persistence.EntityManager;
+import org.apache.usergrid.persistence.EntityManagerFactory;
+import org.apache.usergrid.persistence.index.query.Query;
+import org.apache.usergrid.persistence.Results;
+import org.apache.usergrid.persistence.index.query.CounterResolution;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.services.ServiceManager;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+
+/**
+ * Invoke application request counters
+ *
+ * @author realbeast
+ */
+@Concurrent()
+public class ApplicationRequestCounterIT extends AbstractRestIT {
+    private static final Logger log = LoggerFactory.getLogger( ApplicationRequestCounterIT.class );
+    long ts = System.currentTimeMillis() - ( 24 * 60 * 60 * 1000 );
+
+
+    @Test
+    public void applicationrequestInternalCounters() throws Exception {
+        // Get application id
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertNotNull( node.get( "entities" ) );
+
+        String uuid = node.get( "application" ).asText();
+        assertEquals( true, UUIDUtils.isUUID( uuid ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        UUID applicationId = UUID.fromString( uuid );
+        EntityManagerFactory emf = setup.getEmf();
+        EntityManager em = emf.getEntityManager( applicationId );
+
+        int beforeTotalCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS );
+        int beforeCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS_PER.concat( "get" ) );
+
+        // call
+        node = mapper.readTree( resource().path( "/test-organization/test-app/counters" ).queryParam( "resolution", "all" )
+                .queryParam( "counter", "application.requests" ).queryParam( "access_token", adminToken() )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertNotNull( node.get( "counters" ) );
+
+        int afterTotalCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS );
+        int afterCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS_PER.concat( "get" ) );
+
+        assertEquals( 1, afterCall - beforeCall );
+        assertEquals( 1, afterTotalCall - beforeTotalCall );
+    }
+
+
+    private int getCounter( EntityManager em, String key ) throws Exception {
+        Query query = new Query();
+        query.addCounterFilter( key + ":*:*:*" );
+        query.setStartTime( ts );
+        query.setFinishTime( System.currentTimeMillis() );
+        query.setResolution( CounterResolution.ALL );
+        Results r = em.getAggregateCounters( query );
+        return ( int ) r.getCounters().get( 0 ).getValues().get( 0 ).getValue();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/AndOrQueryTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/AndOrQueryTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/AndOrQueryTest.java
new file mode 100644
index 0000000..942044d
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/AndOrQueryTest.java
@@ -0,0 +1,203 @@
+/*
+ * 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.queries;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.apache.commons.lang.RandomStringUtils;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import static org.junit.Assert.assertEquals;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class AndOrQueryTest extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test //USERGRID-900
+    public void queriesWithAndPastLimit() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        long created = 0;
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+
+        for ( int i = 0; i < 2000; i++ ) {
+            if ( i < 1000 ) {
+                props.put( "madeup", false );
+            }
+            else {
+                props.put( "madeup", true );
+            }
+
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+            if ( i == 0 ) {
+                created = activity.findValue( "created" ).longValue();
+            }
+        }
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String errorQuery = "select * where created >= " + created + "AND madeup = true";
+        JsonNode incorrectNode = activities.withQuery( errorQuery ).get();
+
+        assertEquals( 10, incorrectNode.get( "entities" ).size() );
+    }
+
+
+    @Test //USERGRID-1475
+    public void displayFullQueriesInLimit() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+        props.put( "actor", actor );
+        props.put( "content", "bragh" );
+
+        for ( int i = 0; i < 20; i++ ) {
+
+            if ( i < 10 ) {
+                props.put( "verb", "go" );
+            }
+            else {
+                props.put( "verb", "stop" );
+            }
+
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+        }
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String query = "select * where not verb = 'go'";
+        JsonNode incorrectNode = activities.query( query, "limit", Integer.toString( 10 ) );
+
+        assertEquals( 10, incorrectNode.get( "entities" ).size() );
+
+        for ( int i = 0; i < 10; i++ ) {
+            assertEquals( 19 - i, incorrectNode.get( "entities" ).get( i ).get( "ordinal" ).intValue() );
+            assertEquals( "stop", incorrectNode.get( "entities" ).get( i ).get( "verb" ).textValue() );
+        }
+    }
+
+
+    @Test //USERGRID-1615
+    public void queryReturnCount() throws Exception {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+
+        int numValuesTested = 20;
+
+
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+        JsonNode[] correctValues = activities.createEntitiesWithOrdinal( props, numValuesTested );
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String inCorrectQuery = "select * where verb = 'go' and ordinal >= 10 ";
+
+        activities.verificationOfQueryResults( correctValues, true, inCorrectQuery );
+    }
+
+
+    @Test //Check to make sure that asc works
+    public void queryCheckAsc() throws Exception {
+
+        CustomCollection madeupStuff = context.collection( "imagination" + RandomStringUtils.randomAlphabetic(5));
+        Map character = hashMap( "WhoHelpedYou", "Ruff" );
+
+        JsonNode[] correctValues;
+        correctValues = madeupStuff.createEntitiesWithOrdinal( character, 10 );
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String inquisitiveQuery = "select * where Ordinal gte 0 and Ordinal lte 10 "
+                + "or WhoHelpedYou eq 'Ruff' ORDER BY Ordinal asc";
+
+        int totalEntitiesContained = madeupStuff.verificationOfQueryResults( correctValues, false, inquisitiveQuery );
+
+        assertEquals( 10, totalEntitiesContained );
+    }
+
+
+    @Ignore("Test to make sure all 1000 exist with a regular query")
+    public void queryReturnCheck() throws Exception {
+        CustomCollection madeupStuff = context.collection( "imagination" );
+        Map character = hashMap( "WhoHelpedYou", "Ruff" );
+
+        int numOfEntities = 1000;
+
+        JsonNode[] correctValues = madeupStuff.createEntitiesWithOrdinal( character, numOfEntities );
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String inquisitiveQuery = "select * where Ordinal >= 0 and Ordinal <= 2000 or WhoHelpedYou = 'Ruff'";
+
+        int totalEntitiesContained = madeupStuff.verificationOfQueryResults( correctValues, true, inquisitiveQuery );
+
+        assertEquals( numOfEntities, totalEntitiesContained );
+    }
+
+
+    @Ignore
+    public void queryReturnCheckWithShortHand() throws IOException {
+        CustomCollection madeupStuff = context.collection( "imagination" );
+        Map character = hashMap( "WhoHelpedYou", "Ruff" );
+
+        madeupStuff.createEntitiesWithOrdinal( character, 1000 );
+
+        this.refreshIndex( context.getAppUuid() );
+
+        String inquisitiveQuery = "select * where Ordinal gte 0 and Ordinal lte 2000 or WhoHelpedYou eq 'Ruff'";
+
+        int totalEntitiesContained = madeupStuff.countEntities( inquisitiveQuery );
+
+        assertEquals( 1000, totalEntitiesContained );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/BadGrammarQueryTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/BadGrammarQueryTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/BadGrammarQueryTest.java
new file mode 100644
index 0000000..0ac0558
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/BadGrammarQueryTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.queries;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * @author tnine
+ */
+public class BadGrammarQueryTest extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    public void catchBadQueryGrammar() throws IOException {
+
+        CustomCollection things = context.collection( "things" );
+
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+        props.put( "actor", actor );
+        props.put( "content", "bragh" );
+
+        JsonNode activity = things.create( props );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where name != 'go'";
+
+        ClientResponse.Status status = null;
+
+        try {
+
+            JsonNode incorrectNode = things.query( query, "limit", Integer.toString( 10 ) );
+            fail( "This should throw an exception" );
+        }
+        catch ( UniformInterfaceException uie ) {
+             status = uie.getResponse().getClientResponseStatus();
+
+
+        }
+
+        assertEquals( 400, status.getStatusCode() );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/GeoPagingTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/GeoPagingTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/GeoPagingTest.java
new file mode 100644
index 0000000..9224029
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/queries/GeoPagingTest.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.rest.applications.queries;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import static org.junit.Assert.assertEquals;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class GeoPagingTest extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test //("Test uses up to many resources to run reliably") // USERGRID-1403
+    public void groupQueriesWithGeoPaging() throws IOException {
+
+        CustomCollection groups = context.application().collection( "test1groups" );
+
+        int maxRangeLimit = 2000;
+        long[] index = new long[maxRangeLimit];
+        Map actor = hashMap( "displayName", "Erin" );
+
+        Map props = new HashMap();
+
+        props.put( "actor", actor );
+        Map location = hashMap( "latitude", 37 );
+        location.put( "longitude", -75 );
+        props.put( "location", location );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+        for ( int i = 0; i < 5; i++ ) {
+            String newPath = String.format( "/kero" + i );
+            props.put( "path", newPath );
+            props.put( "ordinal", i );
+            JsonNode activity = groups.create( props );
+            index[i] = activity.findValue( "created" ).longValue();
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where location within 20000 of 37,-75 "
+                + " and created > " + index[2] 
+                + " and created < " + index[4] + "";
+
+        JsonNode node = groups.withQuery( query ).get();
+        assertEquals( 1, node.get( "entities" ).size() );
+
+        assertEquals( index[3], node.get( "entities" ).get( 0 ).get( "created" ).longValue() );
+    }
+
+
+    @Test // USERGRID-1401
+    public void groupQueriesWithConsistentResults() throws IOException {
+
+        CustomCollection groups = context.application().collection( "test2groups" );
+
+        int maxRangeLimit = 20;
+        JsonNode[] saved = new JsonNode[maxRangeLimit];
+
+        Map<String, String> actor = hashMap( "displayName", "Erin" );
+        Map<String, Object> props = new HashMap<String, Object>();
+
+        props.put( "actor", actor );
+        Map<String, Integer> location = hashMap( "latitude", 37 );
+        location.put( "longitude", -75 );
+        props.put( "location", location );
+        props.put( "verb", "go" );
+        props.put( "content", "bragh" );
+
+        for ( int i = 0; i < 20; i++ ) {
+            String newPath = String.format( "/kero" + i );
+            props.put( "path", newPath );
+            props.put( "ordinal", i );
+            JsonNode activity = groups.create( props ).get( "entities" ).get( 0 );
+            saved[i] = activity;
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        JsonNode node = null;
+        for ( int consistent = 0; consistent < 20; consistent++ ) {
+
+            String query = String.format( 
+                "select * where location within 100 of 37, -75 and ordinal >= %d and ordinal < %d", 
+                saved[7].get( "ordinal" ).asLong(), saved[10].get( "ordinal" ).asLong() );
+
+            node = groups.withQuery( query ).get(); //groups.query(query);
+
+            JsonNode entities = node.get( "entities" );
+
+            assertEquals( 3, entities.size() );
+
+            for ( int i = 0; i < 3; i++ ) {
+                // shouldn't start at 10 since you're excluding it above in the query, it should return 9,8,7
+                assertEquals( saved[7 + i], entities.get( i ) );
+            }
+        }
+    }
+}


[5/8] incubator-usergrid git commit: organized rest IT

Posted by ro...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GroupResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GroupResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GroupResourceIT.java
new file mode 100644
index 0000000..0dd6dc8
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GroupResourceIT.java
@@ -0,0 +1,295 @@
+/*
+ * 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.collection.groups;
+
+
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.java.client.Client.Query;
+import org.apache.usergrid.java.client.response.ApiResponse;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+
+/** @author tnine */
+@Concurrent()
+public class GroupResourceIT extends AbstractRestIT {
+    private static Logger log = LoggerFactory.getLogger( GroupResourceIT.class );
+
+    private static final String GROUP = "testGroup";
+
+    private static final String USER = "edanuff";
+
+    private static boolean groupCreated = false;
+
+
+    public GroupResourceIT() throws Exception {
+
+    }
+
+
+    @Before
+    public void setupGroup() {
+        if ( groupCreated ) {
+            return;
+        }
+
+        try {
+            client.createGroup( GROUP );
+            groupCreated = true;
+        }
+        catch ( Exception e ) {
+            log.error( "Error creating group " + GROUP, e );
+        }
+        refreshIndex("test-organization", "test-app");
+
+    }
+
+
+    @Test
+    public void failGroupNameValidation() {
+
+        ApiResponse response = client.createGroup( "groupName/withslash" );
+        assertNull( response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        {
+            boolean failed = false;
+            try {
+                ApiResponse groupResponse = client.createGroup( "groupName withspace" );
+                failed = groupResponse.getError() != null;
+            } catch ( Exception e ) {
+                failed = true;
+            }
+            assertTrue( failed );
+        }
+    }
+
+
+    @Test
+    public void postGroupActivity() {
+
+        // don't populate the user, it will use the currently authenticated
+        // user.
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String groupPath = "groupPath" + id;
+        String groupTitle = "groupTitle " + id;
+        String groupName = "groupName" + id;
+
+        ApiResponse response = client.createGroup( groupPath, groupTitle, groupName );
+
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        UUID newId = response.getEntities().get( 0 ).getUuid();
+
+        Query results = client.queryGroups( String.format( "name='%s'", groupName ) );
+
+        response = results.getResponse();
+
+        UUID entityId = response.getEntities().get( 0 ).getUuid();
+
+        assertEquals( newId, entityId );
+
+        results = client.queryGroups( String.format( "title='%s'", groupTitle ) );
+
+        response = results.getResponse();
+
+        entityId = response.getEntities().get( 0 ).getUuid();
+
+        assertEquals( newId, entityId );
+
+        results = client.queryGroups( String.format( "title contains '%s'", id ) );
+
+        response = results.getResponse();
+
+        entityId = response.getEntities().get( 0 ).getUuid();
+
+        assertEquals( newId, entityId );
+
+        results = client.queryGroups( String.format( "path='%s'", groupPath ) );
+
+        response = results.getResponse();
+
+        entityId = response.getEntities().get( 0 ).getUuid();
+
+        assertEquals( newId, entityId );
+    }
+
+
+    @Test
+    public void addRemovePermission() throws IOException {
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String groupName = "groupname" + id;
+
+        ApiResponse response = client.createGroup( groupName );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        refreshIndex("test-organization", "test-app");
+
+        UUID createdId = response.getEntities().get( 0 ).getUuid();
+
+        // add Permission
+
+        String json = "{\"permission\":\"delete:/test\"}";
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, json ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+        assertEquals( node.get( "data" ).get( 0 ).asText(), "delete:/test" );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertEquals( node.get( "data" ).get( 0 ).asText(), "delete:/test" );
+
+
+        // remove Permission
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
+                .queryParam( "access_token", access_token ).queryParam( "permission", "delete%3A%2Ftest" )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "data" ).size() == 0 );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/permissions" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "data" ).size() == 0 );
+    }
+
+
+    @Test
+    public void addRemoveRole() throws IOException {
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String groupName = "groupname" + id;
+        String roleName = "rolename" + id;
+
+        ApiResponse response = client.createGroup( groupName );
+        assertNull( "Error was: " + response.getErrorDescription(), response.getError() );
+
+        UUID createdId = response.getEntities().get( 0 ).getUuid();
+
+        refreshIndex("test-organization", "test-app");
+
+        // create Role
+
+        String json = "{\"title\":\"" + roleName + "\",\"name\":\"" + roleName + "\"}";
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
+                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .post( String.class, json ));
+
+        // check it
+        assertNull( node.get( "errors" ) );
+
+
+        refreshIndex("test-organization", "test-app");
+
+        // add Role
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles/" + roleName )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        refreshIndex("test-organization", "test-app");
+
+        // check it
+        assertNull( node.get( "errors" ) );
+        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertEquals( node.get( "entities" ).get( 0 ).get( "name" ).asText(), roleName );
+
+        // check root roles
+        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        // remove Role
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles/" + roleName )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+        assertNull( node.get( "errors" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/groups/" + createdId + "/roles" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "entities" ).size() == 0 );
+
+        // check root roles - role should remain
+        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertTrue( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
+
+        // now kill the root role
+        node = mapper.readTree( resource().path( "/test-organization/test-app/roles/" + roleName )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+        assertNull( node.get( "errors" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        // now it should be gone
+        node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        assertNull( node.get( "errors" ) );
+        assertFalse( node.get( "entities" ).findValuesAsText( "name" ).contains( roleName ) );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingEntitiesTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingEntitiesTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingEntitiesTest.java
new file mode 100644
index 0000000..93a061d
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingEntitiesTest.java
@@ -0,0 +1,141 @@
+/*
+ * 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.collection.paging;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import org.apache.commons.lang.ArrayUtils;
+
+import static org.junit.Assert.assertEquals;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class PagingEntitiesTest extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test //USERGRID-266
+    public void pageThroughConnectedEntities() throws IOException {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        long created = 0;
+        int maxSize = 100;
+        long[] verifyCreated = new long[maxSize];
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+
+
+        props.put( "actor", actor );
+        props.put( "verb", "go" );
+
+        for ( int i = 0; i < maxSize; i++ ) {
+
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+            verifyCreated[i] = activity.findValue( "created" ).longValue();
+            if ( i == 0 ) {
+                created = activity.findValue( "created" ).longValue();
+            }
+        }
+        ArrayUtils.reverse( verifyCreated );
+        
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where created >= " + created;
+
+
+        JsonNode node = activities.query( query, "limit", "2" ); //activities.query(query,"");
+        int index = 0;
+        while ( node.get( "entities" ).get( "created" ) != null ) {
+            assertEquals( 2, node.get( "entities" ).size() );
+
+            if ( node.get( "cursor" ) != null ) {
+                node = activities.query( query, "cursor", node.get( "cursor" ).toString() );
+            }
+
+            else {
+                break;
+            }
+        }
+    }
+
+
+    @Test //USERGRID-1253
+    public void pagingQueryReturnCorrectResults() throws Exception {
+
+        CustomCollection activities = context.collection( "activities" );
+
+        long created = 0;
+        int maxSize = 23;
+        long[] verifyCreated = new long[maxSize];
+        Map actor = hashMap( "displayName", "Erin" );
+        Map props = new HashMap();
+
+        props.put( "actor", actor );
+        props.put( "content", "bragh" );
+
+        for ( int i = 0; i < maxSize; i++ ) {
+
+            if ( i > 17 && i < 23 ) {
+                props.put( "verb", "stop" );
+            }
+            else {
+                props.put( "verb", "go" );
+            }
+            props.put( "ordinal", i );
+            JsonNode activity = activities.create( props );
+            verifyCreated[i] = activity.findValue( "created" ).longValue();
+            if ( i == 18 ) {
+                created = activity.findValue( "created" ).longValue();
+            }
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String query = "select * where created >= " + created + " or verb = 'stop'";
+
+        JsonNode node = activities.withQuery( query ).get();
+
+        for ( int index = 0; index < 5; index++ ) {
+            assertEquals( verifyCreated[maxSize - 1 - index],
+                    node.get( "entities" ).get( index ).get( "created" ).longValue() );
+        }
+
+        int totalEntitiesContained = activities.countEntities( query );
+
+        assertEquals( 5, totalEntitiesContained );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingResourceIT.java
new file mode 100644
index 0000000..397dd0f
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/paging/PagingResourceIT.java
@@ -0,0 +1,239 @@
+/*
+ * 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.collection.paging;
+
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.java.client.entities.Entity;
+import org.apache.usergrid.java.client.response.ApiResponse;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+import org.apache.usergrid.rest.test.resource.EntityResource;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/** Simple tests to test querying at the REST tier */
+@Concurrent()
+public class PagingResourceIT extends AbstractRestIT {
+
+    private static final Logger logger = LoggerFactory.getLogger( PagingResourceIT.class );
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    public void collectionPaging() throws Exception {
+
+        CustomCollection things = context.application().collection( "test1things" );
+
+        int size = 40;
+
+        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
+
+        for ( int i = 0; i < size; i++ ) {
+            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
+            things.create( entity );
+
+            created.add( entity );
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // now page them all
+        ApiResponse response = null;
+        Iterator<Map<String, String>> entityItr = created.iterator();
+
+        do {
+
+            response = parse( things.get() );
+
+            for ( Entity e : response.getEntities() ) {
+                assertTrue( entityItr.hasNext() );
+                assertEquals( entityItr.next().get( "name" ), e.getProperties().get( "name" ).asText() );
+                logger.debug("Got item value {}", e.getProperties().get( "name" ).asText());
+            }
+
+            logger.debug("response cursor: " + response.getCursor() );
+            
+            things = things.withCursor( response.getCursor() );
+        }
+        while ( response != null && response.getCursor() != null );
+
+        assertFalse("Should have paged them all", entityItr.hasNext() );
+    }
+
+
+    @Test
+    @Ignore("ignored because currently startPaging is only be supported for queues and not for  "
+            + "generic collections as this test assumes. "
+            + "see also: https://issues.apache.org/jira/browse/USERGRID-211 ")
+    public void startPaging() throws Exception {
+
+        CustomCollection things = context.application().collection( "test2things" );
+
+        int size = 40;
+
+        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
+
+        for ( int i = 0; i < size; i++ ) {
+            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
+            things.create( entity );
+
+            created.add( entity );
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // now page them all
+        ApiResponse response = null;
+
+        UUID start = null;
+        int index = 0;
+
+        do {
+
+            response = parse( things.get() );
+
+            for ( Entity e : response.getEntities() ) {
+                logger.debug("Getting item {} value {}", index, e.getProperties().get( "name" ).asText());
+                assertEquals( created.get( index ).get( "name" ), e.getProperties().get( "name" ).asText() );
+                index++;
+            }
+
+            // decrement since we'll get this one again
+            index--;
+
+            start = response.getEntities().get( response.getEntities().size() - 1 ).getUuid();
+
+            things = things.withStart( start );
+        }
+        while ( response != null && response.getEntities().size() > 1 );
+
+        // we paged them all
+        assertEquals( created.size() - 1, index );
+    }
+
+
+    @Test
+    public void collectionBatchDeleting() throws Exception {
+
+        CustomCollection things = context.application().collection( "test3things" );
+
+        int size = 40;
+
+        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
+
+        for ( int i = 0; i < size; i++ ) {
+            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
+            things.create( entity );
+
+            created.add( entity );
+        }
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        ApiResponse response;
+        int deletePageSize = 10;
+
+        things = things.withLimit( deletePageSize );
+
+        for ( int i = 0; i < size / deletePageSize; i++ ) {
+            response = parse( things.delete() );
+
+            refreshIndex(context.getOrgName(), context.getAppName());
+
+            assertEquals( "Only 10 entities should have been deleted", 10, response.getEntityCount() );
+        }
+
+        response = parse( things.get() );
+
+        assertEquals( "All entities should have been removed", 0, response.getEntityCount() );
+
+        //now do 1 more delete, we should get any results
+
+        response = parse( things.delete() );
+
+        assertEquals( "No more entities deleted", 0, response.getEntityCount() );
+    }
+
+
+    @Test
+    public void emptyQlandLimitIgnored() throws Exception {
+
+        CustomCollection things = context.application().collection( "test4things" );
+
+        Map<String, String> data = hashMap( "name", "thing1" );
+        JsonNode response = things.create( data );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        JsonNode entity = getEntity( response, 0 );
+
+        String uuid = entity.get( "uuid" ).asText();
+
+        EntityResource entityRequest = things.entity( "thing1" ).withParam( "ql", "" ).withParam( "limit", "" );
+
+        JsonNode returnedEntity = getEntity( entityRequest.get(), 0 );
+
+        assertEquals( entity, returnedEntity );
+
+        entityRequest = things.entity( uuid ).withParam( "ql", "" ).withParam( "limit", "" );
+
+        returnedEntity = getEntity( entityRequest.get(), 0 );
+
+        assertEquals( entity, returnedEntity );
+
+        // now do a delete
+        returnedEntity = getEntity( entityRequest.delete(), 0 );
+
+        assertEquals( entity, returnedEntity );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // verify it's gone
+        returnedEntity = getEntity( things.entity( uuid ).get(), 0 );
+
+        assertNull( returnedEntity );
+    }
+
+
+    private static ObjectMapper mapper = new ObjectMapper();
+
+
+    private static final ApiResponse parse( JsonNode response ) throws Exception {
+        String jsonResponseString = mapper.writeValueAsString( response );
+        return mapper.readValue( jsonResponseString, ApiResponse.class );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/ConnectionResourceTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/ConnectionResourceTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/ConnectionResourceTest.java
new file mode 100644
index 0000000..e034443
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/ConnectionResourceTest.java
@@ -0,0 +1,271 @@
+/*
+ * 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.collection.users;
+
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * // TODO: Document this
+ *
+ * @author ApigeeCorporation
+ * @since 4.0
+ */
+public class ConnectionResourceTest extends AbstractRestIT {
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    public void connectionsQueryTest() throws IOException {
+
+
+        CustomCollection activities = context.collection( "peeps" );
+
+        Map stuff = hashMap( "type", "chicken" );
+
+        activities.create( stuff );
+
+
+        Map<String, Object> payload = new LinkedHashMap<String, Object>();
+        payload.put( "username", "todd" );
+
+        Map<String, Object> objectOfDesire = new LinkedHashMap<String, Object>();
+        objectOfDesire.put( "codingmunchies", "doritoes" );
+
+        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, payload );
+
+        payload.put( "username", "scott" );
+
+
+        resource().path( "/test-organization/test-app/users" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, payload );
+    /*finish setting up the two users */
+
+
+        refreshIndex("test-organization", "test-app");
+
+        ClientResponse toddWant = resource().path( "/test-organization/test-app/users/todd/likes/peeps" )
+                .queryParam( "access_token", access_token ).accept( MediaType.TEXT_HTML )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( ClientResponse.class, objectOfDesire );
+
+        assertEquals( 200, toddWant.getStatus() );
+
+        refreshIndex("test-organization", "test-app");
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/peeps" ).queryParam( "access_token", access_token )
+                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .get( String.class ));
+
+        String uuid = node.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
+
+
+        try {
+            node = mapper.readTree( resource().path( "/test-organization/test-app/users/scott/likes/" + uuid )
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+            assert ( false );
+        }
+        catch ( UniformInterfaceException uie ) {
+            assertEquals( 404, uie.getResponse().getClientResponseStatus().getStatusCode() );
+        }
+    }
+
+
+    @Test
+    public void connectionsLoopbackTest() throws IOException {
+
+        CustomCollection things = context.collection( "things" );
+
+        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
+
+        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
+
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //create the connection
+        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
+
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //test we have the "likes" in our connection meta data response
+
+        JsonNode response = things.entity( "thing1" ).get();
+
+        String url = getEntity( response, 0 ).get( "metadata" ).get( "connections" ).get( "likes" ).asText();
+
+
+        assertNotNull( "Connection url returned in entity", url );
+
+        //trim off the start /
+        url = url.substring( 1 );
+
+
+        //now that we know the URl is correct, follow it
+
+        response = context.collection( url ).get();
+
+        UUID returnedUUID = getEntityId( response, 0 );
+
+        assertEquals( thing2Id, returnedUUID );
+
+
+        //now follow the loopback, which should be pointers to the other entity
+
+        url = getEntity( response, 0 ).get( "metadata" ).get( "connecting" ).get( "likes" ).asText();
+
+        assertNotNull( "Incoming edge URL provited", url );
+
+        //trim off the start /
+        url = url.substring( 1 );
+
+        //now we should get thing1 from the loopback url
+
+        response = context.collection( url ).get();
+
+        UUID returned = getEntityId( response, 0 );
+
+        assertEquals( "Should point to thing1 as an incoming entity connection", thing1Id, returned );
+    }
+
+
+    @Test
+    public void connectionsUUIDTest() throws IOException {
+
+        CustomCollection things = context.collection( "things" );
+
+        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
+
+        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
+
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //create the connection
+        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
+
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //test we have the "likes" in our connection meta data response
+
+        JsonNode response = things.entity( "thing1" ).get();
+
+        String url = getEntity( response, 0 ).get( "metadata" ).get( "connections" ).get( "likes" ).asText();
+
+
+        assertNotNull( "Connection url returned in entity", url );
+
+        //trim off the start /
+        url = url.substring( 1 );
+
+
+        //now that we know the URl is correct, follow it
+
+        response = context.collection( url ).get();
+
+        UUID returnedUUID = getEntityId( response, 0 );
+
+        assertEquals( thing2Id, returnedUUID );
+
+        //get on the collection works, now get it directly by uuid
+
+        //now we should get thing1 from the loopback url
+
+        response = things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).get();
+
+        UUID returned = getEntityId( response, 0 );
+
+        assertEquals( "Should point to thing2 as an entity connection", thing2Id, returned );
+    }
+
+    @Test //USERGRID-3011
+    public void connectionsDeleteSecondEntityInConnectionTest() throws IOException {
+
+        CustomCollection things = context.collection( "things" );
+
+        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
+
+        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //create the connection
+        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
+
+        JsonNode response = things.entity( "thing2" ).delete();
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        JsonNode node = things.entity ( "thing2" ).get();
+
+        assertNull(node);
+
+    }
+
+    @Test //USERGRID-3011
+    public void connectionsDeleteFirstEntityInConnectionTest() throws IOException {
+
+        CustomCollection things = context.collection( "things" );
+
+        UUID thing1Id = getEntityId( things.create( hashMap( "name", "thing1" ) ), 0 );
+
+        UUID thing2Id = getEntityId( things.create( hashMap( "name", "thing2" ) ), 0 );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        //create the connection
+        things.entity( thing1Id ).connection( "likes" ).entity( thing2Id ).post();
+
+        JsonNode response = things.entity( "thing1" ).delete();
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        JsonNode node = things.entity ( "thing1" ).get();
+
+        assertNull(node);
+
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/OwnershipResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/OwnershipResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/OwnershipResourceIT.java
new file mode 100644
index 0000000..a514781
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/OwnershipResourceIT.java
@@ -0,0 +1,379 @@
+/*
+ * 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.collection.users;
+
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.rest.TestContextSetup;
+import org.apache.usergrid.rest.test.resource.Connection;
+import org.apache.usergrid.rest.test.resource.CustomCollection;
+import org.apache.usergrid.rest.test.resource.app.queue.DevicesCollection;
+import org.apache.usergrid.rest.test.security.TestAppUser;
+import org.apache.usergrid.rest.test.security.TestUser;
+import org.apache.usergrid.utils.MapUtils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+
+/**
+ *
+ */
+@Concurrent()
+public class OwnershipResourceIT extends AbstractRestIT {
+
+    @Rule
+    public TestContextSetup context = new TestContextSetup( this );
+
+
+    @Test
+    public void meVerify() throws Exception {
+
+        context.clearUser();
+
+        String email = "testuser1@usergrid.org";
+        TestUser user1 = new TestAppUser( email, "password", email ).create( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+        user1.login( context ).makeActive( context );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String token = user1.getToken();
+        JsonNode userNode = context.application().users().user( "me" ).get();
+        assertNotNull( userNode );
+
+        String uuid = userNode.get( "entities" ).get( 0 ).get( "uuid" ).textValue();
+        assertNotNull( uuid );
+
+        setup.getMgmtSvc().revokeAccessTokenForAppUser( token );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        try {
+            context.application().users().user( "me" ).get();
+            fail();
+        }
+        catch ( Exception ex ) {
+            ex.printStackTrace();
+            assertTrue( ex.getMessage().contains( "401" ) );
+        }
+    }
+
+
+    @Test
+    public void contextualPathOwnership() throws IOException {
+
+        // anonymous user
+        context.clearUser();
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        TestUser user1 = new TestAppUser( "testuser1@usergrid.org", "password", "testuser1@usergrid.org" ).create( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+        user1.login( context );
+        user1.makeActive( context );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // create device 1 on user1 devices
+        context.application().users().user( "me" ).devices()
+               .create( MapUtils.hashMap( "name", "device1" ).map( "number", "5551112222" ) );
+
+        // anonymous user
+        context.clearUser();
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // create device 2 on user 2
+        TestUser user2 = new TestAppUser( "testuser2@usergrid.org", "password", "testuser2@usergrid.org" ).create( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+        user2.login( context );
+        user2.makeActive( context );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        context.application().users().user( "me" ).devices()
+               .create( MapUtils.hashMap( "name", "device2" ).map( "number", "5552223333" ) );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // now query on user 1.
+
+        DevicesCollection devices = context.withUser( user1 ).application().users().user( "me" ).devices();
+
+        JsonNode data = devices.device( "device1" ).get();
+        assertNotNull( data );
+        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can't see device2
+        data = devices.device( "device2" ).get();
+        assertNull( data );
+
+        // do a collection load, make sure we're not loading device 2
+        data = devices.get();
+
+        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
+        assertNull( getEntity( data, 1 ) );
+
+        // log in as user 2 and check it
+        devices = context.withUser( user2 ).application().users().user( "me" ).devices();
+
+        data = devices.device( "device2" ).get();
+        assertNotNull( data );
+        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can't see device1
+        data = devices.device( "device1" ).get();
+        assertNull( data );
+
+        // do a collection load, make sure we're not loading device 1
+        data = devices.get();
+
+        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
+        assertNull( getEntity( data, 1 ) );
+
+        // we should see both devices when loaded from the root application
+
+        // test for user 1
+
+        devices = context.withUser( user1 ).application().devices();
+        data = devices.device( "device1" ).get();
+
+        assertNotNull( data );
+        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = devices.device( "device2" ).get();
+
+        assertNotNull( data );
+        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // test for user 2
+        data = context.withUser( user2 ).application().devices().device( "device1" ).get();
+
+        assertNotNull( data );
+        assertEquals( "device1", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = devices.device( "device2" ).get();
+
+        assertNotNull( data );
+        assertEquals( "device2", getEntity( data, 0 ).get( "name" ).asText() );
+    }
+
+
+    @Test
+    public void contextualConnectionOwnership() throws IOException {
+
+        // anonymous user
+        context.clearUser();
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String email = "testuser1@usergrid.org";
+        TestUser user1 = new TestAppUser( email, "password", email ).create( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+        user1.login( context ).makeActive( context );
+
+        // create a 4peaks restaurant
+        JsonNode data = context.application()
+                .collection( "restaurants" ).create( MapUtils.hashMap( "name", "4peaks" ) );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // create our connection
+        data = context.application().users().user( "me" )
+                .connection( "likes" ).collection( "restaurants" ).entity( "4peaks" ).post();
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+       String peaksId = getEntity( data, 0 ).get( "uuid" ).asText();
+
+        // anonymous user
+        context.clearUser();
+
+        // create a restaurant and link it to user 2
+        email = "testuser2@usergrid.org";
+        TestUser user2 = new TestAppUser( email, "password", email ).create( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        user2.login( context ).makeActive( context );
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        data = context.application().collection( "restaurants" )
+                      .create( MapUtils.hashMap( "name", "arrogantbutcher" ) );
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        data = context.application().users().user( "me" ).connection( "likes" ).collection( "restaurants" )
+                      .entity( "arrogantbutcher" ).post();
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String arrogantButcherId = getEntity( data, 0 ).get( "uuid" ).asText();
+
+        // now query on user 1.
+
+        CustomCollection likeRestaurants =
+                context.withUser( user1 ).application().users().user( "me" ).connection( "likes" )
+                       .collection( "restaurants" );
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // check we can get it via id
+        data = likeRestaurants.entity( peaksId ).get();
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can get it by name
+        data = likeRestaurants.entity( "4peaks" ).get();
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can't see arrogantbutcher by name or id
+        data = likeRestaurants.entity( "arrogantbutcher" ).get();
+        assertNull( data );
+
+        data = likeRestaurants.entity( arrogantButcherId ).get();
+        assertNull( data );
+
+        // do a collection load, make sure we're not entities we shouldn't see
+        data = likeRestaurants.get();
+
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+        assertNull( getEntity( data, 1 ) );
+
+        // log in as user 2 and check it
+        likeRestaurants = context.withUser( user2 ).application().users().user( "me" ).connection( "likes" )
+                                 .collection( "restaurants" );
+
+        data = likeRestaurants.entity( arrogantButcherId ).get();
+        assertNotNull( data );
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = likeRestaurants.entity( "arrogantbutcher" ).get();
+        assertNotNull( data );
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can't see 4peaks
+        data = likeRestaurants.entity( "4peaks" ).get();
+        assertNull( data );
+
+        data = likeRestaurants.entity( peaksId ).get();
+        assertNull( data );
+
+        // do a collection load, make sure we're not loading device 1
+        data = likeRestaurants.get();
+
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+        assertNull( getEntity( data, 1 ) );
+
+        // we should see both devices when loaded from the root application
+
+        // test for user 1
+
+        CustomCollection restaurants = context.withUser( user1 ).application().collection( "restaurants" );
+        data = restaurants.entity( "4peaks" ).get();
+
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = restaurants.entity( "arrogantbutcher" ).get();
+
+        assertNotNull( data );
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // test for user 2
+        restaurants = context.withUser( user1 ).application().collection( "restaurants" );
+        data = restaurants.entity( "4peaks" ).get();
+
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = restaurants.entity( "arrogantbutcher" ).get();
+
+        assertNotNull( data );
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+    }
+
+
+    @Test
+    public void contextualConnectionOwnershipGuestAccess() throws IOException {
+
+        //set up full GET,PUT,POST,DELETE access for guests
+        context.application().collection( "roles" ).entity( "guest" ).collection( "permissions" )
+               .create( MapUtils.hashMap( "permission", "get,put,post,delete:/**" ) );
+
+
+        // anonymous user
+        context.clearUser();
+
+
+        JsonNode city = context.application().collection( "cities" ).create( MapUtils.hashMap( "name", "tempe" ) );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        String cityId = getEntity( city, 0 ).get( "uuid" ).asText();
+
+        // create a 4peaks restaurant
+        JsonNode data = context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" )
+                               .collection( "restaurants" ).create( MapUtils.hashMap( "name", "4peaks" ) );
+
+        String peaksId = getEntity( data, 0 ).get( "uuid" ).asText();
+
+        data = context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" )
+                      .collection( "restaurants" ).create( MapUtils.hashMap( "name", "arrogantbutcher" ) );
+
+        String arrogantButcherId = getEntity( data, 0 ).get( "uuid" ).asText();
+
+        // now query on user 1.
+
+        Connection likeRestaurants =
+                context.application().collection( "cities" ).entity( "tempe" ).connection( "likes" );
+
+        refreshIndex(context.getOrgName(), context.getAppName());
+
+        // check we can get it via id with no collection name
+        data = likeRestaurants.entity( peaksId ).get();
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = likeRestaurants.entity( arrogantButcherId ).get();
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // check we can get it via id with a collection name
+        data = likeRestaurants.collection( "restaurants" ).entity( peaksId ).get();
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = likeRestaurants.collection( "restaurants" ).entity( arrogantButcherId ).get();
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+
+        // do a delete either token should work
+        data = likeRestaurants.collection( "restaurants" ).entity( peaksId ).delete();
+
+        assertNotNull( data );
+        assertEquals( "4peaks", getEntity( data, 0 ).get( "name" ).asText() );
+
+        data = likeRestaurants.collection( "restaurants" ).entity( arrogantButcherId ).delete();
+
+        assertNotNull( data );
+        assertEquals( "arrogantbutcher", getEntity( data, 0 ).get( "name" ).asText() );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/PermissionsResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/PermissionsResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/PermissionsResourceIT.java
new file mode 100644
index 0000000..a07622e
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/users/PermissionsResourceIT.java
@@ -0,0 +1,768 @@
+/*
+ * 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.collection.users;
+
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.java.client.entities.Group;
+import org.apache.usergrid.management.ApplicationInfo;
+import org.apache.usergrid.management.OrganizationOwnerInfo;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.ClientResponse.Status;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * Tests permissions of adding and removing users from roles as well as groups
+ *
+ * @author tnine
+ */
+@Concurrent()
+public class PermissionsResourceIT extends AbstractRestIT {
+
+    private static final String ROLE = "permtestrole";
+
+    private static final String USER = "edanuff";
+
+
+    public PermissionsResourceIT() throws Exception {
+
+    }
+
+
+    @Test
+    public void deleteUserFromRole() throws IOException {
+        Map<String, String> data = hashMap( "name", ROLE );
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/roles" ).queryParam( "access_token", access_token )
+                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .post( String.class, data ));
+
+        assertNull( node.get( "error" ) );
+
+        assertEquals( ROLE, getEntity( node, 0 ).get( "name" ).asText() );
+
+        refreshIndex("test-organization", "test-app");
+
+        // add the user to the role
+        node = mapper.readTree( resource().path( "/test-organization/test-app/roles/" + ROLE + "/users/" + USER )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertNull( node.get( "error" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        // now check the user has the role
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        // check if the role was assigned
+        assertEquals( ROLE, getEntity( node, 0 ).get( "name" ).asText() );
+
+        // now delete the role
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles/" + ROLE )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        refreshIndex("test-organization", "test-app");
+
+        // check if the role was deleted
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/users/" + USER + "/roles" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        // check if the role was assigned
+        assertNull( getEntity( node, 0 ) );
+    }
+
+
+    @Test
+    public void deleteUserGroup() throws IOException {
+
+        // don't populate the user, it will use the currently authenticated
+        // user.
+
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String groupPath = "groupPath" + id;
+
+        Map<String, String> data = hashMap( "type", "group" ).map( "path", groupPath );
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/groups" )
+                .queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, data ));
+
+        assertNull( node.get( "error" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        node = mapper.readTree( 
+            resource().path( "/test-organization/test-app/groups/" + groupPath + "/users/" + USER )
+                .queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class ));
+
+        assertNull( node.get( "error" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        Map<String, Group> groups = client.getGroupsForUser( USER );
+
+        assertNotNull( groups.get( groupPath ) );
+
+        // now delete the group
+
+        node = mapper.readTree( 
+            resource().path( "/test-organization/test-app/groups/" + groupPath + "/users/" + USER )
+                .queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE )
+                .delete( String.class ));
+
+        assertNull( node.get( "error" ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        groups = client.getGroupsForUser( USER );
+
+        assertNull( groups.get( groupPath ) );
+    }
+
+
+    /**
+     * For the record, you should NEVER allow the guest role to add roles. This is a gaping security hole and a VERY BAD
+     * IDEA! That being said, this should technically work, and needs testing.
+     */
+    @Test
+    public void dictionaryPermissions() throws Exception {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String applicationName = "testapp";
+        String orgname = "dictionaryPermissions";
+        String username = "permissionadmin" + id;
+        String password = "password";
+        String email = String.format( "email%s@usergrid.com", id );
+
+        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
+                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
+                                                  true, false );
+
+        // create the app
+        ApplicationInfo appInfo =
+                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
+
+        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
+
+        // add the perms to the guest to allow users in the role to create roles
+        // themselves
+        addPermission( orgname, applicationName, adminToken, "guest", "get,put,post:/roles/**" );
+
+        Map<String, String> data = hashMap( "name", "usercreatedrole" );
+
+        // create a role as the user
+        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, data ));
+
+        assertNull( getError( node ) );
+
+        refreshIndex(orgname, applicationName);
+
+        // now try to add permission as the user, this should work
+        addPermission( orgname, applicationName, "usercreatedrole", "get,put,post:/foo/**" );
+    }
+
+
+    /**
+     * Tests a real world example with the following steps. Creates an application.
+     * <p/>
+     * Creates a new role "reviewer"
+     * <p/>
+     * Grants a permission to GET, POST, and PUT the reviews url for the reviewer role
+     * <p/>
+     * Grants a permission GET on the reviewer for the
+     * <p/>
+     * Create a user reviewer1 and add them to the reviewer role
+     * <p/>
+     * Test access with reviewer1
+     * <p/>
+     * Create a group reviewergroup and add the "reviewer" group to it
+     * <p/>
+     * Create a user reviewer 2 and add them to the "reveiwergroup"
+     */
+    @Test
+    public void applicationPermissions() throws Exception {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String applicationName = "test";
+        String orgname = "applicationpermissions";
+        String username = "permissionadmin" + id;
+        String password = "password";
+        String email = String.format( "email%s@usergrid.com", id );
+
+        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
+                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
+                                                  true, false );
+
+        // create the app
+        ApplicationInfo appInfo =
+                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
+
+        // now create the new role
+        Map<String, String> data = hashMap( "name", "reviewer" );
+
+        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
+
+        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+
+        assertNull( getError( node ) );
+
+        // delete the default role to test permissions later
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles/default", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+
+        assertNull( getError( node ) );
+        refreshIndex(orgname, applicationName);
+
+        // grant the perms to reviewer
+        addPermission( orgname, applicationName, adminToken, "reviewer", "get,put,post:/reviews/**" );
+
+        // grant get to guest
+        addPermission( orgname, applicationName, adminToken, "guest", "get:/reviews/**" );
+
+        UUID userId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "reviewer1",
+                "reviewer1@usergrid.com" );
+
+        refreshIndex(orgname, applicationName);
+
+        // grant this user the "reviewer" role
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/users/reviewer1/roles/reviewer", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        assertNull( getError( node ) );
+
+        refreshIndex(orgname, applicationName);
+
+        String reviewer1Token = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userId, 0 );
+
+        Map<String, String> review =
+                hashMap( "rating", "4" ).map( "name", "noca" ).map( "review", "Excellent service and food" );
+
+        // post a review as the reviewer1 user
+        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
+
+        review = hashMap( "rating", "4" ).map( "name", "4peaks" ).map( "review", "Huge beer selection" );
+
+        refreshIndex(orgname, applicationName);
+
+        // put a review as the reviewer1 user
+        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, review );
+
+        refreshIndex(orgname, applicationName);
+
+        // get the reviews
+
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( "noca", getEntity( node, 0 ).get( "name" ).asText() );
+        assertEquals( "4peaks", getEntity( node, 1 ).get( "name" ).asText() );
+
+        // can't delete, not in the grants
+
+        ClientResponse.Status status = null;
+
+        try {
+            resource().path( String.format( "/%s/%s/reviews/noca", orgname, applicationName ) )
+                    .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        refreshIndex(orgname, applicationName);
+
+        status = null;
+
+        try {
+            resource().path( String.format( "/%s/%s/reviews/4peaks", orgname, applicationName ) )
+                    .queryParam( "access_token", reviewer1Token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        refreshIndex(orgname, applicationName);
+
+        // now test some groups
+        UUID secondUserId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "reviewer2",
+                "reviewer2@usergrid.com" );
+
+        Map<String, String> group = hashMap( "path", "reviewergroup" );
+
+        // /now create the group
+        resource().path( String.format( "/%s/%s/groups", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, group );
+
+        refreshIndex(orgname, applicationName);
+
+        // link the group to the role
+        resource().path( String.format( "/%s/%s/groups/reviewergroup/roles/reviewer", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, group );
+
+        refreshIndex(orgname, applicationName);
+
+        // add the user to the group
+        resource().path( String.format( "/%s/%s/users/reviewer2/groups/reviewergroup", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class );
+
+        refreshIndex(orgname, applicationName);
+
+        // post 2 reviews. Should get permissions from the group
+
+        String secondUserToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), secondUserId, 0 );
+
+        review = hashMap( "rating", "4" ).map( "name", "cowboyciao" ).map( "review", "Great atmosphoere" );
+
+        // post a review as the reviewer2 user
+        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
+
+        review = hashMap( "rating", "4" ).map( "name", "currycorner" ).map( "review", "Authentic" );
+
+        refreshIndex(orgname, applicationName);
+
+        // post a review as the reviewer2 user
+        resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review );
+
+        refreshIndex(orgname, applicationName);
+
+        // get all reviews as a user
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", orgname, applicationName ) )
+                .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        assertEquals( "noca", getEntity( node, 0 ).get( "name" ).asText() );
+        assertEquals( "4peaks", getEntity( node, 1 ).get( "name" ).asText() );
+        assertEquals( "cowboyciao", getEntity( node, 2 ).get( "name" ).asText() );
+        assertEquals( "currycorner", getEntity( node, 3 ).get( "name" ).asText() );
+
+        // issue a delete, it shouldn't work, no permissions
+
+        status = null;
+
+        try {
+            resource().path( String.format( "/%s/%s/reviews/cowboyciao", orgname, applicationName ) )
+                    .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        refreshIndex(orgname, applicationName);
+
+        status = null;
+
+        try {
+            resource().path( String.format( "/%s/%s/reviews/currycorner", orgname, applicationName ) )
+                    .queryParam( "access_token", secondUserToken ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+
+        assertEquals( Status.UNAUTHORIZED, status );
+    }
+
+
+    /**
+     * Tests the scenario where we have roles declarations such as: <ul> <li>GET /users/[star]/reviews "any user can
+     * read any others book review"</li> <li>POST /users/[user1]/reviews "cannot post as user2 to user1's reviews"</li>
+     * <ii>POST /users/[star]/reviews/feedback/* "can post as user2 to user1's feedback/good or /bad</ii> </ul>
+     * <p/>
+     * Scenario is as follows: Create an application
+     * <p/>
+     * Add two application users - user1 - user2
+     * <p/>
+     * Create a book collection for user1
+     */
+    @Test
+    public void wildcardMiddlePermission() throws Exception {
+
+         Map<String, String> params = buildOrgAppParams();
+        String orgname =params.get( "orgName" ) ;
+        String applicationName = params.get( "appName" ) ;
+        
+        OrganizationOwnerInfo orgs = setup.getMgmtSvc().createOwnerAndOrganization( params.get( "orgName" ),
+                params.get( "username" ), "noname", params.get( "email" ), params.get( "password" ), true, false );
+
+        // create the app
+        ApplicationInfo appInfo =
+                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), params.get( "appName" ) );
+        assertNotNull( appInfo );
+
+        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
+
+        JsonNode node = mapper.readTree( resource()
+                .path( String.format( "/%s/%s/roles/default", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+        Map<String, String> data = hashMap( "name", "reviewer" );
+
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+        assertNull( getError( node ) );
+
+        refreshIndex(orgname, applicationName);
+
+        // allow access to reviews
+        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
+                "get,put,post:/reviews/**" );
+        // allow access to all user's connections
+        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
+                "get,put,post:/users/${user}/**" );
+        // allow access to the review relationship
+        addPermission( params.get( "orgName" ), params.get( "appName" ), adminToken, "reviewer",
+                "get,put,post:/books/*/review/*" );
+
+        assertNull( getError( node ) );
+        // create userOne
+        UUID userOneId =
+                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "wildcardpermuserone",
+                        "wildcardpermuserone@apigee.com" );
+        assertNotNull( userOneId );
+
+        // create userTwo
+        UUID userTwoId =
+                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "wildcardpermusertwo",
+                        "wildcardpermusertwo@apigee.com" );
+        assertNotNull( userTwoId );
+
+        refreshIndex(orgname, applicationName);
+
+        // assign userOne the reviewer role
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/%s/roles/reviewer", params.get( "orgName" ), params.get( "appName" ),
+                        userOneId.toString() ) ).queryParam( "access_token", adminToken )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        refreshIndex(orgname, applicationName);
+
+        Map<String, String> book = hashMap( "title", "Ready Player One" ).map( "author", "Earnest Cline" );
+
+        // create a book as admin
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/books", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, book ));
+
+        logNode( node );
+        assertEquals( "Ready Player One", getEntity( node, 0 ).get( "title" ).textValue() );
+        String bookId = getEntity( node, 0 ).get( "uuid" ).textValue();
+
+        refreshIndex(orgname, applicationName);
+
+        String userOneToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), userOneId, 0 );
+        // post a review of the book as user1
+        // POST https://api.usergrid.com/my-org/my-app/users/$user1/reviewed/books/$uuid
+        Map<String, String> review =
+                hashMap( "heading", "Loved It" ).map( "body", "80s Awesomeness set in the future" );
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/reviews", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, review ));
+        String reviewId = getEntity( node, 0 ).get( "uuid" ).textValue();
+
+        refreshIndex(orgname, applicationName);
+
+        // POST https://api.usergrid.com/my-org/my-app/users/me/wrote/review/${reviewId}
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/me/wrote/review/%s", params.get( "orgName" ), params.get( "appName" ),
+                        reviewId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        refreshIndex(orgname, applicationName);
+
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/me/reviewed/books/%s", params.get( "orgName" ), params.get( "appName" ),
+                        bookId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+        logNode( node );
+
+        refreshIndex(orgname, applicationName);
+
+        // POST https://api.usergrid.com/my-org/my-app/books/${bookId}/review/${reviewId}
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/books/%s/review/%s", params.get( "orgName" ), params.get( "appName" ), bookId,
+                        reviewId ) ).queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+        logNode( node );
+
+        refreshIndex(orgname, applicationName);
+
+        // now try to post the same thing to books to verify as userOne the failure
+        Status status = null;
+        try {
+            node = mapper.readTree( resource().path( String.format( "/%s/%s/books", params.get( "orgName" ), params.get( "appName" ) ) )
+                    .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+            logNode( node );
+        }
+        catch ( UniformInterfaceException uie ) {
+            status = uie.getResponse().getClientResponseStatus();
+        }
+        assertEquals( Status.UNAUTHORIZED, status );
+
+        refreshIndex(orgname, applicationName);
+
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/me/reviewed/books", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        logNode( node );
+
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/reviews/%s", params.get( "orgName" ), params.get( "appName" ), reviewId ) )
+                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        logNode( node );
+
+        node = mapper.readTree( resource()
+                .path( String.format( "/%s/%s/users/me/wrote", params.get( "orgName" ), params.get( "appName" ) ) )
+                .queryParam( "access_token", userOneToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+        logNode( node );
+    }
+
+
+    /**
+     * Tests the scenario where we have role declaration such as: <ul> <li>POST /users/[star]/following/users/${user}" a
+     * user can add himself to any other user following list"</li> </ul>
+     * <p/>
+     * Scenario is as follows: Create an application
+     * <p/>
+     * Add two application users - examplepatient - exampledoctor
+     * <p/>
+     * examplepatient add himself to exampledoctor following list
+     */
+    @Test
+    @Ignore("Why is this ignored?")
+    public void wildcardFollowingPermission() throws Exception {
+        UUID id = UUIDUtils.newTimeUUID();
+
+        String applicationName = "test";
+        String orgname = "followingpermissions";
+        String username = "permissionadmin" + id;
+        String password = "password";
+        String email = String.format( "email%s@usergrid.com", id );
+
+        OrganizationOwnerInfo orgs = setup.getMgmtSvc()
+                                          .createOwnerAndOrganization( orgname, username, "noname", email, password,
+                                                  true, false );
+
+        // create the app
+        ApplicationInfo appInfo =
+                setup.getMgmtSvc().createApplication( orgs.getOrganization().getUuid(), applicationName );
+        assertNotNull( appInfo );
+
+        String adminToken = setup.getMgmtSvc().getAccessTokenForAdminUser( orgs.getOwner().getUuid(), 0 );
+
+        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/roles/default", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).delete( String.class ));
+        Map<String, String> data = hashMap( "name", "patient" );
+
+        node = mapper.readTree( resource().path( String.format( "/%s/%s/roles", orgname, applicationName ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+        assertNull( getError( node ) );
+        //allow patients to add doctors as their followers
+        addPermission( orgname, applicationName, adminToken, "patient",
+                "delete,post:/users/*/following/users/${user}" );
+
+        assertNull( getError( node ) );
+        // create examplepatient
+        UUID patientId =
+                createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "examplepatient",
+                        "examplepatient@apigee.com" );
+        assertNotNull( patientId );
+
+        // create exampledoctor
+        UUID doctorId = createRoleUser( orgs.getOrganization().getUuid(), appInfo.getId(), adminToken, "exampledoctor",
+                "exampledoctor@apigee.com" );
+        assertNotNull( doctorId );
+
+
+        // assign examplepatient the patient role
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/%s/roles/patient", orgname, applicationName, patientId.toString() ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+
+        String patientToken = setup.getMgmtSvc().getAccessTokenForAppUser( appInfo.getId(), patientId, 0 );
+
+        node = mapper.readTree( resource().path( String
+                .format( "/%s/%s/users/%s/following/users/%s", orgname, applicationName, "exampledoctor",
+                        "examplepatient" ) ).queryParam( "access_token", patientToken )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).post( String.class ));
+        logNode( node );
+    }
+
+
+    private Map<String, String> buildOrgAppParams() {
+        UUID id = UUIDUtils.newTimeUUID();
+        Map<String, String> props =
+                hashMap( "username", "wcpermadmin" ).map( "orgName", "orgnamewcperm" ).map( "appName", "test" )
+                        .map( "password", "password" )
+                        .map( "email", String.format( "email%s@apigee.com", id.toString() ) );
+
+        return props;
+    }
+
+
+    /**
+     * Create the user, check there are no errors
+     *
+     * @return the userid
+     */
+    private UUID createRoleUser( UUID orgId, UUID appId, String adminToken, String username, String email )
+            throws Exception {
+
+        Map<String, String> props = hashMap( "email", email ).map( "username", username ).map( "name", username )
+                .map( "password", "password" );
+
+        JsonNode node = mapper.readTree( resource().path( String.format( "/%s/%s/users", orgId, appId ) )
+                .queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).put( String.class, props ));
+
+        assertNull( getError( node ) );
+
+        UUID userId = UUID.fromString( getEntity( node, 0 ).get( "uuid" ).asText() );
+
+        // manually activate user
+        setup.getMgmtSvc().activateAppUser( appId, userId );
+
+        return userId;
+    }
+
+
+    /** Test adding the permission to the role */
+    private void addPermission( String orgname, String appname, String adminToken, String rolename, String grant ) throws IOException {
+        Map<String, String> props = hashMap( "permission", grant );
+
+        String rolePath = String.format( "/%s/%s/roles/%s/permissions", orgname, appname, rolename );
+
+        JsonNode node = mapper.readTree( resource().path( rolePath ).queryParam( "access_token", adminToken )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .put( String.class, props ));
+
+        assertNull( getError( node ) );
+
+        node = mapper.readTree( resource().path( rolePath ).queryParam( "access_token", adminToken ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+        ArrayNode data = ( ArrayNode ) node.get( "data" );
+
+        Iterator<JsonNode> iterator = data.elements();
+
+        while ( iterator.hasNext() ) {
+            if ( grant.equals( iterator.next().asText() ) ) {
+                return;
+            }
+        }
+
+        fail( String.format( "didn't find grant %s in the results", grant ) );
+    }
+
+
+    /** Test adding the permission to the role */
+    private void addPermission( String orgname, String appname, String rolename, String grant ) throws IOException {
+        Map<String, String> props = hashMap( "permission", grant );
+
+        String rolePath = String.format( "/%s/%s/roles/%s/permissions", orgname, appname, rolename );
+
+        JsonNode node = mapper.readTree( resource().path( rolePath ).accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .put( String.class, props ));
+
+        assertNull( getError( node ) );
+
+        node = mapper.readTree( resource().path( rolePath ).accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .get( String.class ));
+
+        ArrayNode data = ( ArrayNode ) node.get( "data" );
+
+        Iterator<JsonNode> iterator = data.elements();
+
+        while ( iterator.hasNext() ) {
+            if ( grant.equals( iterator.next().asText() ) ) {
+                return;
+            }
+        }
+
+        fail( String.format( "didn't find grant %s in the results", grant ) );
+    }
+}


[6/8] incubator-usergrid git commit: organized rest IT

Posted by ro...@apache.org.
organized rest IT


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

Branch: refs/heads/two-dot-o-rest-refactor
Commit: 3993f081d6fd09d5ad475b9cb379e74e690b8046
Parents: f42ebde
Author: amuramoto <am...@apigee.com>
Authored: Wed Sep 17 13:39:38 2014 -0700
Committer: amuramoto <am...@apigee.com>
Committed: Wed Sep 17 13:39:38 2014 -0700

----------------------------------------------------------------------
 .../main/dist/init_instance/init_db_server.sh   |    3 +
 .../main/dist/init_instance/init_rest_server.sh |   20 +-
 .../dist/init_instance/install_elasticsearch.sh |    8 +-
 .../usergrid/rest/ConcurrentRestITSuite.java    |   18 +-
 .../org/apache/usergrid/rest/RestITSuite.java   |   18 +-
 .../ApplicationRequestCounterIT.java            |   97 --
 .../rest/applications/DevicesResourceIT.java    |   87 --
 .../collection/BadGrammarQueryTest.java         |   79 -
 .../collection/CollectionsResourceIT.java       |  205 +++
 .../collection/PagingResourceIT.java            |  239 ---
 .../activities/ActivityResourceIT.java          |  188 +++
 .../collection/activities/AndOrQueryTest.java   |  203 ---
 .../collection/activities/OrderByTest.java      |  172 ---
 .../activities/PagingEntitiesTest.java          |  141 --
 .../collection/devices/DevicesResourceIT.java   |   87 ++
 .../collection/groups/GeoPagingTest.java        |  133 --
 .../collection/groups/GroupResourceIT.java      |  295 ++++
 .../collection/paging/PagingEntitiesTest.java   |  141 ++
 .../collection/paging/PagingResourceIT.java     |  239 +++
 .../users/ConnectionResourceTest.java           |  271 ++++
 .../collection/users/OwnershipResourceIT.java   |  379 +++++
 .../collection/users/PermissionsResourceIT.java |  768 ++++++++++
 .../collection/users/RetrieveUsersTest.java     |   87 ++
 .../collection/users/UserResourceIT.java        | 1418 ++++++++++++++++++
 .../users/extensions/TestResource.java          |   51 +
 .../events/ApplicationRequestCounterIT.java     |   97 ++
 .../applications/queries/AndOrQueryTest.java    |  203 +++
 .../queries/BadGrammarQueryTest.java            |   79 +
 .../applications/queries/GeoPagingTest.java     |  133 ++
 .../applications/queries/MatrixQueryTests.java  |  202 +++
 .../rest/applications/queries/OrderByTest.java  |  172 +++
 .../applications/users/ActivityResourceIT.java  |  188 ---
 .../users/CollectionsResourceIT.java            |  205 ---
 .../users/ConnectionResourceTest.java           |  271 ----
 .../applications/users/GroupResourceIT.java     |  295 ----
 .../applications/users/MatrixQueryTests.java    |  202 ---
 .../applications/users/OwnershipResourceIT.java |  379 -----
 .../users/PermissionsResourceIT.java            |  768 ----------
 .../applications/users/RetrieveUsersTest.java   |   87 --
 .../rest/applications/users/UserResourceIT.java | 1418 ------------------
 .../users/extensions/TestResource.java          |   51 -
 41 files changed, 5050 insertions(+), 5047 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/init_db_server.sh b/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
index b9c4f56..3ffca66 100644
--- a/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
+++ b/stack/awscluster/src/main/dist/init_instance/init_db_server.sh
@@ -67,6 +67,9 @@ cd /usr/share/usergrid/init_instance
 cd /usr/share/usergrid/init_instance
 ./create_keyspaces.sh
 
+#Increase file descriptors for Elasticsearch
+sed -i.bak "s/#@student        -       maxlogins       4/*\t\t\-\tnofile\t\t${NOFILE}\nroot\t\t\-\tnofile\t\t10000"/ /etc/security/limits.conf
+
 # tag last so we can see in the console that the script ran to completion
 cd /usr/share/usergrid/scripts
 groovy tag_instance.groovy

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh b/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
index fdc83cd..5cdf10a 100644
--- a/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
+++ b/stack/awscluster/src/main/dist/init_instance/init_rest_server.sh
@@ -51,7 +51,8 @@ cd /usr/share/usergrid/init_instance
 ./install_yourkit.sh
 
 # set Tomcat memory and threads based on instance type
-export NOFILE=100000
+export NOFILE=50000
+export TOMCAT_CONNECTIONS=10000
 case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
 'm1.small' )
     export TOMCAT_RAM=1250M
@@ -69,30 +70,29 @@ case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
     export TOMCAT_RAM=12G
     export TOMCAT_THREADS=2000
 ;;
-'m3.xlarge' )
-    export TOMCAT_RAM=12G
-    export TOMCAT_THREADS=3300
-;;
 'm3.large' )
     export TOMCAT_RAM=6G
-    export TOMCAT_THREADS=1600
+    export TOMCAT_THREADS=6000
+;;
+'m3.xlarge' )
+    export TOMCAT_RAM=12G
+    export TOMCAT_THREADS=8000
 ;;
 'c3.2xlarge' )
     export TOMCAT_RAM=12G
-    export TOMCAT_THREADS=2000
+    export TOMCAT_THREADS=10000
 ;;
 'c3.4xlarge' )
     export TOMCAT_RAM=24G
-    export TOMCAT_THREADS=4000
+    export TOMCAT_THREADS=12000
 esac
 
-export TOMCAT_CONNECTIONS=10000
 sed -i.bak "s/Xmx128m/Xmx${TOMCAT_RAM} -Xms${TOMCAT_RAM} -Dlog4j\.configuration=file:\/usr\/share\/usergrid\/lib\/log4j\.properties/g" /etc/default/tomcat7
 sed -i.bak "s/<Connector/<Connector maxThreads=\"${TOMCAT_THREADS}\" acceptCount=\"${TOMCAT_THREADS}\" maxConnections=\"${TOMCAT_CONNECTIONS}\"/g" /var/lib/tomcat7/conf/server.xml
 
 # set file limits
 sed -i.bak "s/# \/etc\/init\.d\/tomcat7 -- startup script for the Tomcat 6 servlet engine/ulimit -n ${NOFILE}/" /etc/init.d/tomcat7
-sed -i.bak "s/@student/a *\t\thard\tnofile\t\t${NOFILE}\n*\t\tsoft\tnofile\t\t${NOFILE}" /etc/security/limits.conf
+sed -i.bak "s/#@student        -       maxlogins       4/*\t\t\-\tnofile\t\t${NOFILE}\nroot\t\t\-\tnofile\t\t${NOFILE}"/ /etc/security/limits.conf
 echo "$NOFILE" | sudo tee > /proc/sys/fs/nr_open
 echo "$NOFILE" | sudo tee > /proc/sys/fs/file-max
 cat >> /etc/pam.d/su << EOF

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
----------------------------------------------------------------------
diff --git a/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
index d398591..51f7c60 100644
--- a/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
+++ b/stack/awscluster/src/main/dist/init_instance/install_elasticsearch.sh
@@ -57,16 +57,16 @@ case `(curl http://169.254.169.254/latest/meta-data/instance-type)` in
     export ES_HEAP_SIZE=5G
 ;;
 'm3.xlarge' )
-    export ES_HEAP_SIZE=5G
+    export ES_HEAP_SIZE=10G
 ;;
 'm3.large' )
-    export ES_HEAP_SIZE=2G
+    export ES_HEAP_SIZE=5G
 ;;
 'c3.2xlarge' )
-    export ES_HEAP_SIZE=4G
+    export ES_HEAP_SIZE=10G
 ;;
 'c3.4xlarge' )
-    export ES_HEAP_SIZE=12G
+    export ES_HEAP_SIZE=15G
 esac
 
 cat >> /etc/default/elasticsearch << EOF

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java b/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
index 4456054..c6d2705 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
@@ -23,18 +23,18 @@ import org.junit.runners.Suite;
 import org.apache.usergrid.cassandra.CassandraResource;
 import org.apache.usergrid.cassandra.Concurrent;
 import org.apache.usergrid.cassandra.ConcurrentSuite;
-import org.apache.usergrid.rest.applications.ApplicationRequestCounterIT;
+import org.apache.usergrid.rest.applications.events.ApplicationRequestCounterIT;
 import org.apache.usergrid.rest.applications.ApplicationResourceIT;
-import org.apache.usergrid.rest.applications.DevicesResourceIT;
+import org.apache.usergrid.rest.applications.collection.devices.DevicesResourceIT;
 import org.apache.usergrid.rest.applications.assets.AssetResourceIT;
-import org.apache.usergrid.rest.applications.collection.PagingResourceIT;
+import org.apache.usergrid.rest.applications.collection.paging.PagingResourceIT;
 import org.apache.usergrid.rest.applications.events.EventsResourceIT;
-import org.apache.usergrid.rest.applications.users.ActivityResourceIT;
-import org.apache.usergrid.rest.applications.users.CollectionsResourceIT;
-import org.apache.usergrid.rest.applications.users.GroupResourceIT;
-import org.apache.usergrid.rest.applications.users.OwnershipResourceIT;
-import org.apache.usergrid.rest.applications.users.PermissionsResourceIT;
-import org.apache.usergrid.rest.applications.users.UserResourceIT;
+import org.apache.usergrid.rest.applications.collection.activities.ActivityResourceIT;
+import org.apache.usergrid.rest.applications.collection.CollectionsResourceIT;
+import org.apache.usergrid.rest.applications.collection.groups.GroupResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.OwnershipResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.PermissionsResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.UserResourceIT;
 import org.apache.usergrid.rest.filters.ContentTypeResourceIT;
 import org.apache.usergrid.rest.management.ManagementResourceIT;
 import org.apache.usergrid.rest.management.RegistrationIT;

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java b/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
index dbf8834..a28fa89 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
@@ -22,17 +22,17 @@ import org.junit.runner.RunWith;
 import org.junit.runners.Suite;
 import org.apache.usergrid.cassandra.CassandraResource;
 import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.rest.applications.ApplicationRequestCounterIT;
-import org.apache.usergrid.rest.applications.DevicesResourceIT;
+import org.apache.usergrid.rest.applications.events.ApplicationRequestCounterIT;
+import org.apache.usergrid.rest.applications.collection.devices.DevicesResourceIT;
 import org.apache.usergrid.rest.applications.assets.AssetResourceIT;
-import org.apache.usergrid.rest.applications.collection.PagingResourceIT;
+import org.apache.usergrid.rest.applications.collection.paging.PagingResourceIT;
 import org.apache.usergrid.rest.applications.events.EventsResourceIT;
-import org.apache.usergrid.rest.applications.users.ActivityResourceIT;
-import org.apache.usergrid.rest.applications.users.CollectionsResourceIT;
-import org.apache.usergrid.rest.applications.users.GroupResourceIT;
-import org.apache.usergrid.rest.applications.users.OwnershipResourceIT;
-import org.apache.usergrid.rest.applications.users.PermissionsResourceIT;
-import org.apache.usergrid.rest.applications.users.UserResourceIT;
+import org.apache.usergrid.rest.applications.collection.activities.ActivityResourceIT;
+import org.apache.usergrid.rest.applications.collection.CollectionsResourceIT;
+import org.apache.usergrid.rest.applications.collection.groups.GroupResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.OwnershipResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.PermissionsResourceIT;
+import org.apache.usergrid.rest.applications.collection.users.UserResourceIT;
 import org.apache.usergrid.rest.filters.ContentTypeResourceIT;
 import org.apache.usergrid.rest.management.organizations.AdminEmailEncodingIT;
 import org.apache.usergrid.rest.management.users.organizations.UsersOrganizationsResourceIT;

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/ApplicationRequestCounterIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/ApplicationRequestCounterIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/ApplicationRequestCounterIT.java
deleted file mode 100644
index 007741a..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/ApplicationRequestCounterIT.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications;
-
-
-import java.util.UUID;
-
-import javax.ws.rs.core.MediaType;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.persistence.EntityManager;
-import org.apache.usergrid.persistence.EntityManagerFactory;
-import org.apache.usergrid.persistence.index.query.Query;
-import org.apache.usergrid.persistence.Results;
-import org.apache.usergrid.persistence.index.query.CounterResolution;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.services.ServiceManager;
-import org.apache.usergrid.utils.UUIDUtils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-
-/**
- * Invoke application request counters
- *
- * @author realbeast
- */
-@Concurrent()
-public class ApplicationRequestCounterIT extends AbstractRestIT {
-    private static final Logger log = LoggerFactory.getLogger( ApplicationRequestCounterIT.class );
-    long ts = System.currentTimeMillis() - ( 24 * 60 * 60 * 1000 );
-
-
-    @Test
-    public void applicationrequestInternalCounters() throws Exception {
-        // Get application id
-        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app" ).queryParam( "access_token", access_token )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertNotNull( node.get( "entities" ) );
-
-        String uuid = node.get( "application" ).asText();
-        assertEquals( true, UUIDUtils.isUUID( uuid ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        UUID applicationId = UUID.fromString( uuid );
-        EntityManagerFactory emf = setup.getEmf();
-        EntityManager em = emf.getEntityManager( applicationId );
-
-        int beforeTotalCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS );
-        int beforeCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS_PER.concat( "get" ) );
-
-        // call
-        node = mapper.readTree( resource().path( "/test-organization/test-app/counters" ).queryParam( "resolution", "all" )
-                .queryParam( "counter", "application.requests" ).queryParam( "access_token", adminToken() )
-                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
-
-        assertNotNull( node.get( "counters" ) );
-
-        int afterTotalCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS );
-        int afterCall = getCounter( em, ServiceManager.APPLICATION_REQUESTS_PER.concat( "get" ) );
-
-        assertEquals( 1, afterCall - beforeCall );
-        assertEquals( 1, afterTotalCall - beforeTotalCall );
-    }
-
-
-    private int getCounter( EntityManager em, String key ) throws Exception {
-        Query query = new Query();
-        query.addCounterFilter( key + ":*:*:*" );
-        query.setStartTime( ts );
-        query.setFinishTime( System.currentTimeMillis() );
-        query.setResolution( CounterResolution.ALL );
-        Results r = em.getAggregateCounters( query );
-        return ( int ) r.getCounters().get( 0 ).getValues().get( 0 ).getValue();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/DevicesResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/DevicesResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/DevicesResourceIT.java
deleted file mode 100644
index f63244a..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/DevicesResourceIT.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications;
-
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.rest.AbstractRestIT;
-
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-import org.junit.Ignore;
-
-
-@Concurrent()
-public class DevicesResourceIT extends AbstractRestIT {
-
-    @Test
-    @Ignore("cannot be supported with Core Persistence which requires time based UUIDs")
-    public void putWithUUIDShouldCreateAfterDelete() throws IOException {
-
-        Map<String, String> payload = new HashMap<String, String>();
-        UUID uuid = UUID.randomUUID();
-        payload.put( "name", "foo" );
-
-        String path = "devices/" + uuid;
-
-        refreshIndex("test-organization", "test-app");
-
-        JsonNode response = mapper.readTree( appPath( path ).put( String.class, payload ));
-
-        // create
-        JsonNode entity = getEntity( response, 0 );
-        assertNotNull( entity );
-        String newUuid = entity.get( "uuid" ).textValue();
-        assertEquals( uuid.toString(), newUuid );
-
-        // delete
-        response = mapper.readTree( appPath( path ).delete( String.class ));
-        assertNotNull( getEntity( response, 0 ) );
-
-        refreshIndex("test-organization", "test-app");
-
-        // check deleted
-        try {
-            response = mapper.readTree( appPath( path ).get( String.class ));
-            fail( "should get 404 error" );
-        }
-        catch ( UniformInterfaceException e ) {
-            assertEquals( 404, e.getResponse().getStatus() );
-        }
-
-        // create again
-        response = mapper.readTree( appPath( path ).put( String.class, payload ));
-        entity = getEntity( response, 0 );
-        assertNotNull( entity );
-
-        refreshIndex("test-organization", "test-app");
-
-        // check existence
-        response = mapper.readTree( appPath( path ).get( String.class ));
-        assertNotNull( getEntity( response, 0 ) );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/BadGrammarQueryTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/BadGrammarQueryTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/BadGrammarQueryTest.java
deleted file mode 100644
index bd95fd8..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/BadGrammarQueryTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import java.io.IOException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * @author tnine
- */
-public class BadGrammarQueryTest extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    public void catchBadQueryGrammar() throws IOException {
-
-        CustomCollection things = context.collection( "things" );
-
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-        props.put( "actor", actor );
-        props.put( "content", "bragh" );
-
-        JsonNode activity = things.create( props );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where name != 'go'";
-
-        ClientResponse.Status status = null;
-
-        try {
-
-            JsonNode incorrectNode = things.query( query, "limit", Integer.toString( 10 ) );
-            fail( "This should throw an exception" );
-        }
-        catch ( UniformInterfaceException uie ) {
-             status = uie.getResponse().getClientResponseStatus();
-
-
-        }
-
-        assertEquals( 400, status.getStatusCode() );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/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
new file mode 100644
index 0000000..72639ca
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/CollectionsResourceIT.java
@@ -0,0 +1,205 @@
+/*
+ * 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.collection;
+
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.Assert;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+
+
+/**
+ * @author zznate
+ * @author tnine
+ */
+@Concurrent()
+public class CollectionsResourceIT extends AbstractRestIT {
+
+    private static Logger log = LoggerFactory.getLogger( CollectionsResourceIT.class );
+
+
+    @Test
+    public void postToBadPath() throws IOException {
+        Map<String, String> payload = hashMap( "name", "Austin" ).map( "state", "TX" );
+        JsonNode node = null;
+        try {
+            node = mapper.readTree( resource().path( "/test-organization/test-organization/test-app/cities" )
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
+        }
+        catch ( UniformInterfaceException e ) {
+            assertEquals( "Should receive a 400 Not Found", 400, e.getResponse().getStatus() );
+        }
+    }
+
+
+    @Test
+    public void postToEmptyCollection() throws IOException {
+        Map<String, String> payload = new HashMap<String, String>();
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/cities" ).queryParam( "access_token", access_token )
+                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .post( String.class, payload ));
+        assertNull( getEntity( node, 0 ) );
+        assertNull( node.get( "count" ) );
+    }
+
+
+    /**
+     * emails with "me" in them are causing errors. Test we can post to a colleciton after creating a user with this
+     * email
+     * <p/>
+     * USERGRID-689
+     */
+    @Test
+    public void permissionWithMeInString() throws Exception {
+        // user is created get a token
+        createUser( "sumeet.agarwal@usergrid.com", "sumeet.agarwal@usergrid.com", "secret", "Sumeet Agarwal" );
+        refreshIndex("test-organization", "test-app");
+
+        String token = userToken( "sumeet.agarwal@usergrid.com", "secret" );
+
+
+        //create a permission with the path "me" in it
+        Map<String, String> data = new HashMap<String, String>();
+
+        data.put( "permission", "get,post,put,delete:/users/sumeet.agarwal@usergrid.com/**" );
+
+        String path = "/test-organization/test-app/users/sumeet.agarwal@usergrid.com/permissions";
+        JsonNode posted = mapper.readTree( resource().path( path ).queryParam( "access_token", token ).accept( MediaType.APPLICATION_JSON )
+                        .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, data ));
+
+
+        //now post data
+        data = new HashMap<String, String>();
+
+        data.put( "name", "profile-sumeet" );
+        data.put( "firstname", "sumeet" );
+        data.put( "lastname", "agarwal" );
+        data.put( "mobile", "122" );
+
+
+        posted = mapper.readTree( resource().path( "/test-organization/test-app/nestprofiles" ).queryParam( "access_token", token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, data ));
+
+        refreshIndex("test-organization", "test-app");
+
+        JsonNode response = mapper.readTree( resource().path( "/test-organization/test-app/nestprofiles" ).queryParam( "access_token", token )
+                        .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                        .get( String.class ));
+
+        assertNotNull( getEntity( response, 0 ) );
+        assertNotNull( response.get( "count" ) );
+    }
+
+
+    @Test
+    public void stringWithSpaces() throws IOException {
+        Map<String, String> payload = hashMap( "summaryOverview", "My Summary" ).map( "caltype", "personal" );
+
+        JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" )
+                .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
+
+
+        UUID id = getEntityId( node, 0 );
+
+        //post a second entity
+
+
+        payload = hashMap( "summaryOverview", "Your Summary" ).map( "caltype", "personal" );
+
+        node = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" ).queryParam( "access_token", access_token )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE )
+                .post( String.class, payload ));
+
+
+        refreshIndex("test-organization", "test-app");
+
+        //query for the first entity
+
+        String query = "summaryOverview = 'My Summary'";
+
+
+        JsonNode queryResponse = mapper.readTree( resource().path( "/test-organization/test-app/calendarlists" )
+                .queryParam( "access_token", access_token ).queryParam( "ql", query )
+                .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ).get( String.class ));
+
+
+        UUID returnedId = getEntityId( queryResponse, 0 );
+
+        assertEquals( id, returnedId );
+
+        assertEquals( 1, queryResponse.get( "entities" ).size() );
+    }
+
+
+    /**
+     * Test to verify "name property returns twice in AppServices response" is fixed.
+     * https://apigeesc.atlassian.net/browse/USERGRID-2318
+     */
+    @Test
+    public void testNoDuplicateFields() throws Exception {
+
+        {
+            // create an "app_user" object with name fred
+            Map<String, String> payload = hashMap( "type", "app_user" ).map( "name", "fred" );
+
+            JsonNode node = mapper.readTree( resource().path( "/test-organization/test-app/app_users" )
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).post( String.class, payload ));
+
+            String uuidString = node.get( "entities" ).get( 0 ).get( "uuid" ).asText();
+            UUID entityId = UUIDUtils.tryGetUUID( uuidString );
+            Assert.assertNotNull( entityId );
+        }
+
+        refreshIndex("test-organization", "test-app");
+
+        {
+            // check REST API response for duplicate name property
+            // have to look at raw response data, Jackson will remove dups
+            String s = resource().path( "/test-organization/test-app/app_users/fred" )
+                    .queryParam( "access_token", access_token ).accept( MediaType.APPLICATION_JSON )
+                    .type( MediaType.APPLICATION_JSON_TYPE ).get( String.class );
+
+            int firstFred = s.indexOf( "fred" );
+            int secondFred = s.indexOf( "fred", firstFred + 4 );
+            Assert.assertEquals( "Should not be more than one name property", -1, secondFred );
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/PagingResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/PagingResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/PagingResourceIT.java
deleted file mode 100644
index c7a7a84..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/PagingResourceIT.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection;
-
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import org.apache.usergrid.cassandra.Concurrent;
-import org.apache.usergrid.java.client.entities.Entity;
-import org.apache.usergrid.java.client.response.ApiResponse;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-import org.apache.usergrid.rest.test.resource.EntityResource;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/** Simple tests to test querying at the REST tier */
-@Concurrent()
-public class PagingResourceIT extends AbstractRestIT {
-
-    private static final Logger logger = LoggerFactory.getLogger( PagingResourceIT.class );
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    public void collectionPaging() throws Exception {
-
-        CustomCollection things = context.application().collection( "test1things" );
-
-        int size = 40;
-
-        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
-
-        for ( int i = 0; i < size; i++ ) {
-            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
-            things.create( entity );
-
-            created.add( entity );
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // now page them all
-        ApiResponse response = null;
-        Iterator<Map<String, String>> entityItr = created.iterator();
-
-        do {
-
-            response = parse( things.get() );
-
-            for ( Entity e : response.getEntities() ) {
-                assertTrue( entityItr.hasNext() );
-                assertEquals( entityItr.next().get( "name" ), e.getProperties().get( "name" ).asText() );
-                logger.debug("Got item value {}", e.getProperties().get( "name" ).asText());
-            }
-
-            logger.debug("response cursor: " + response.getCursor() );
-            
-            things = things.withCursor( response.getCursor() );
-        }
-        while ( response != null && response.getCursor() != null );
-
-        assertFalse("Should have paged them all", entityItr.hasNext() );
-    }
-
-
-    @Test
-    @Ignore("ignored because currently startPaging is only be supported for queues and not for  "
-            + "generic collections as this test assumes. "
-            + "see also: https://issues.apache.org/jira/browse/USERGRID-211 ")
-    public void startPaging() throws Exception {
-
-        CustomCollection things = context.application().collection( "test2things" );
-
-        int size = 40;
-
-        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
-
-        for ( int i = 0; i < size; i++ ) {
-            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
-            things.create( entity );
-
-            created.add( entity );
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // now page them all
-        ApiResponse response = null;
-
-        UUID start = null;
-        int index = 0;
-
-        do {
-
-            response = parse( things.get() );
-
-            for ( Entity e : response.getEntities() ) {
-                logger.debug("Getting item {} value {}", index, e.getProperties().get( "name" ).asText());
-                assertEquals( created.get( index ).get( "name" ), e.getProperties().get( "name" ).asText() );
-                index++;
-            }
-
-            // decrement since we'll get this one again
-            index--;
-
-            start = response.getEntities().get( response.getEntities().size() - 1 ).getUuid();
-
-            things = things.withStart( start );
-        }
-        while ( response != null && response.getEntities().size() > 1 );
-
-        // we paged them all
-        assertEquals( created.size() - 1, index );
-    }
-
-
-    @Test
-    public void collectionBatchDeleting() throws Exception {
-
-        CustomCollection things = context.application().collection( "test3things" );
-
-        int size = 40;
-
-        List<Map<String, String>> created = new ArrayList<Map<String, String>>( size );
-
-        for ( int i = 0; i < size; i++ ) {
-            Map<String, String> entity = hashMap( "name", String.valueOf( i ) );
-            things.create( entity );
-
-            created.add( entity );
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        ApiResponse response;
-        int deletePageSize = 10;
-
-        things = things.withLimit( deletePageSize );
-
-        for ( int i = 0; i < size / deletePageSize; i++ ) {
-            response = parse( things.delete() );
-
-            refreshIndex(context.getOrgName(), context.getAppName());
-
-            assertEquals( "Only 10 entities should have been deleted", 10, response.getEntityCount() );
-        }
-
-        response = parse( things.get() );
-
-        assertEquals( "All entities should have been removed", 0, response.getEntityCount() );
-
-        //now do 1 more delete, we should get any results
-
-        response = parse( things.delete() );
-
-        assertEquals( "No more entities deleted", 0, response.getEntityCount() );
-    }
-
-
-    @Test
-    public void emptyQlandLimitIgnored() throws Exception {
-
-        CustomCollection things = context.application().collection( "test4things" );
-
-        Map<String, String> data = hashMap( "name", "thing1" );
-        JsonNode response = things.create( data );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        JsonNode entity = getEntity( response, 0 );
-
-        String uuid = entity.get( "uuid" ).asText();
-
-        EntityResource entityRequest = things.entity( "thing1" ).withParam( "ql", "" ).withParam( "limit", "" );
-
-        JsonNode returnedEntity = getEntity( entityRequest.get(), 0 );
-
-        assertEquals( entity, returnedEntity );
-
-        entityRequest = things.entity( uuid ).withParam( "ql", "" ).withParam( "limit", "" );
-
-        returnedEntity = getEntity( entityRequest.get(), 0 );
-
-        assertEquals( entity, returnedEntity );
-
-        // now do a delete
-        returnedEntity = getEntity( entityRequest.delete(), 0 );
-
-        assertEquals( entity, returnedEntity );
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        // verify it's gone
-        returnedEntity = getEntity( things.entity( uuid ).get(), 0 );
-
-        assertNull( returnedEntity );
-    }
-
-
-    private static ObjectMapper mapper = new ObjectMapper();
-
-
-    private static final ApiResponse parse( JsonNode response ) throws Exception {
-        String jsonResponseString = mapper.writeValueAsString( response );
-        return mapper.readValue( jsonResponseString, ApiResponse.class );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/ActivityResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/ActivityResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/ActivityResourceIT.java
new file mode 100644
index 0000000..49fa7bb
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/ActivityResourceIT.java
@@ -0,0 +1,188 @@
+/*
+ * 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.collection.activities;
+
+
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.java.client.Client.Query;
+import org.apache.usergrid.java.client.entities.Entity;
+import org.apache.usergrid.java.client.entities.User;
+import org.apache.usergrid.java.client.response.ApiResponse;
+import org.apache.usergrid.rest.AbstractRestIT;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+
+/** @author tnine */
+@Concurrent()
+public class ActivityResourceIT extends AbstractRestIT {
+    private static Logger log = LoggerFactory.getLogger( ActivityResourceIT.class );
+
+    private static final String GROUP = "testGroup";
+
+    private static final String USER = "edanuff";
+
+    private static boolean groupCreated = false;
+
+
+    public ActivityResourceIT() throws Exception {
+
+    }
+
+
+    @Before
+    public void setupGroup() {
+        if ( groupCreated ) {
+            return;
+        }
+
+        client.createGroup( GROUP );
+
+        refreshIndex("test-organization", "test-app");
+
+        groupCreated = true;
+    }
+
+
+    @Test
+    public void postNullActivityToGroup() {
+
+        boolean fail = false;
+        try {
+            ApiResponse groupActivity = client.postGroupActivity( GROUP, null );
+            fail = (groupActivity.getError() != null);
+            
+        }
+        catch ( Exception e ) {
+            fail = true;
+        }
+        assertTrue( fail );
+    }
+
+
+    @Test
+    public void postGroupActivity() {
+
+        // don't populate the user, it will use the currently authenticated user.
+
+        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
+        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
+
+        client.postGroupActivity( GROUP, "POST", 
+            activityTitle, activityDesc, "testCategory", null, null, null, null, null );
+
+        refreshIndex("test-organization", "test-app");
+
+        Query results = client.queryActivityFeedForGroup( GROUP );
+
+        ApiResponse response = results.getResponse();
+
+        Entity result = response.getEntities().get( 0 );
+
+        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
+        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
+        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
+
+        // now pull the activity directly, we should find it
+
+        results = client.queryActivity();
+
+        response = results.getResponse();
+
+        result = response.getEntities().get( 0 );
+
+        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
+        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
+        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
+    }
+
+
+    @Test
+    public void postUserActivity() {
+
+        // don't populate the user, it will use the currently authenticated
+        // user.
+
+        User current = client.getLoggedInUser();
+
+        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
+        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
+
+        client.postUserActivity( "POST", activityTitle, activityDesc, "testCategory", current, null, null, null, null );
+
+        refreshIndex("test-organization", "test-app");
+
+        Query results = client.queryActivityFeedForUser( USER );
+
+        ApiResponse response = results.getResponse();
+
+        Entity result = response.getEntities().get( 0 );
+
+        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
+        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
+        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
+        assertEquals( current.getUuid().toString(), result.getProperties().get( "actor" ).get( "uuid" ).asText() );
+
+        // now pull the activity directly, we should find it
+
+        results = client.queryActivity();
+
+        response = results.getResponse();
+
+        result = response.getEntities().get( 0 );
+
+        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
+        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
+        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
+    }
+
+
+    @Test
+    public void postActivity() {
+
+        // don't populate the user, it will use the currently authenticated
+        // user.
+
+        User current = client.getLoggedInUser();
+
+        String activityTitle = "testTitle" + UUIDUtils.newTimeUUID();
+        String activityDesc = "testActivity" + UUIDUtils.newTimeUUID();
+
+        client.postActivity( "POST", activityTitle, activityDesc, "testCategory", current, null, null, null, null );
+
+        refreshIndex("test-organization", "test-app");
+
+        Query results = client.queryActivity();
+
+        ApiResponse response = results.getResponse();
+
+        Entity result = response.getEntities().get( 0 );
+
+        assertEquals( "POST", result.getProperties().get( "verb" ).asText() );
+        assertEquals( activityTitle, result.getProperties().get( "title" ).asText() );
+        assertEquals( activityDesc, result.getProperties().get( "content" ).asText() );
+
+        //ACTOR isn't coming back, why?
+        assertEquals( current.getUuid().toString(), result.getProperties().get( "actor" ).get( "uuid" ).asText() );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/AndOrQueryTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/AndOrQueryTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/AndOrQueryTest.java
deleted file mode 100644
index 5eda243..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/AndOrQueryTest.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection.activities;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.apache.commons.lang.RandomStringUtils;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import static org.junit.Assert.assertEquals;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class AndOrQueryTest extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test //USERGRID-900
-    public void queriesWithAndPastLimit() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        long created = 0;
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-
-        for ( int i = 0; i < 2000; i++ ) {
-            if ( i < 1000 ) {
-                props.put( "madeup", false );
-            }
-            else {
-                props.put( "madeup", true );
-            }
-
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-            if ( i == 0 ) {
-                created = activity.findValue( "created" ).longValue();
-            }
-        }
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String errorQuery = "select * where created >= " + created + "AND madeup = true";
-        JsonNode incorrectNode = activities.withQuery( errorQuery ).get();
-
-        assertEquals( 10, incorrectNode.get( "entities" ).size() );
-    }
-
-
-    @Test //USERGRID-1475
-    public void displayFullQueriesInLimit() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-        props.put( "actor", actor );
-        props.put( "content", "bragh" );
-
-        for ( int i = 0; i < 20; i++ ) {
-
-            if ( i < 10 ) {
-                props.put( "verb", "go" );
-            }
-            else {
-                props.put( "verb", "stop" );
-            }
-
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-        }
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String query = "select * where not verb = 'go'";
-        JsonNode incorrectNode = activities.query( query, "limit", Integer.toString( 10 ) );
-
-        assertEquals( 10, incorrectNode.get( "entities" ).size() );
-
-        for ( int i = 0; i < 10; i++ ) {
-            assertEquals( 19 - i, incorrectNode.get( "entities" ).get( i ).get( "ordinal" ).intValue() );
-            assertEquals( "stop", incorrectNode.get( "entities" ).get( i ).get( "verb" ).textValue() );
-        }
-    }
-
-
-    @Test //USERGRID-1615
-    public void queryReturnCount() throws Exception {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-
-        int numValuesTested = 20;
-
-
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-        JsonNode[] correctValues = activities.createEntitiesWithOrdinal( props, numValuesTested );
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String inCorrectQuery = "select * where verb = 'go' and ordinal >= 10 ";
-
-        activities.verificationOfQueryResults( correctValues, true, inCorrectQuery );
-    }
-
-
-    @Test //Check to make sure that asc works
-    public void queryCheckAsc() throws Exception {
-
-        CustomCollection madeupStuff = context.collection( "imagination" + RandomStringUtils.randomAlphabetic(5));
-        Map character = hashMap( "WhoHelpedYou", "Ruff" );
-
-        JsonNode[] correctValues;
-        correctValues = madeupStuff.createEntitiesWithOrdinal( character, 10 );
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String inquisitiveQuery = "select * where Ordinal gte 0 and Ordinal lte 10 "
-                + "or WhoHelpedYou eq 'Ruff' ORDER BY Ordinal asc";
-
-        int totalEntitiesContained = madeupStuff.verificationOfQueryResults( correctValues, false, inquisitiveQuery );
-
-        assertEquals( 10, totalEntitiesContained );
-    }
-
-
-    @Ignore("Test to make sure all 1000 exist with a regular query")
-    public void queryReturnCheck() throws Exception {
-        CustomCollection madeupStuff = context.collection( "imagination" );
-        Map character = hashMap( "WhoHelpedYou", "Ruff" );
-
-        int numOfEntities = 1000;
-
-        JsonNode[] correctValues = madeupStuff.createEntitiesWithOrdinal( character, numOfEntities );
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String inquisitiveQuery = "select * where Ordinal >= 0 and Ordinal <= 2000 or WhoHelpedYou = 'Ruff'";
-
-        int totalEntitiesContained = madeupStuff.verificationOfQueryResults( correctValues, true, inquisitiveQuery );
-
-        assertEquals( numOfEntities, totalEntitiesContained );
-    }
-
-
-    @Ignore
-    public void queryReturnCheckWithShortHand() throws IOException {
-        CustomCollection madeupStuff = context.collection( "imagination" );
-        Map character = hashMap( "WhoHelpedYou", "Ruff" );
-
-        madeupStuff.createEntitiesWithOrdinal( character, 1000 );
-
-        this.refreshIndex( context.getAppUuid() );
-
-        String inquisitiveQuery = "select * where Ordinal gte 0 and Ordinal lte 2000 or WhoHelpedYou eq 'Ruff'";
-
-        int totalEntitiesContained = madeupStuff.countEntities( inquisitiveQuery );
-
-        assertEquals( 1000, totalEntitiesContained );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/OrderByTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/OrderByTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/OrderByTest.java
deleted file mode 100644
index 7e96818..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/OrderByTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection.activities;
-
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import static org.junit.Assert.assertEquals;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class OrderByTest extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test
-    // USERGRID-1400
-    public void orderByShouldNotAffectResults() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        long created = 0;
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-        for ( int i = 0; i < 20; i++ ) {
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-            if ( i == 5 ) {
-                created = activity.findValue( "created" ).longValue();
-            }
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where created > " + created;
-        JsonNode node = activities.withQuery( query ).get();
-        assertEquals( 10, node.get( "entities" ).size() );
-
-        query = query + " order by created desc";
-        node = activities.withQuery( query ).get();
-        assertEquals( 10, node.get( "entities" ).size() );
-    }
-
-
-    @Test
-    // USERGRID-1520
-    public void orderByComesBeforeLimitResult() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-        int checkResultsNum = 0;
-
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-        for ( int i = 0; i < 20; i++ ) {
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where created > " + 1 + " order by created desc";
-
-        JsonNode incorrectNode = activities.withQuery( query ).withLimit( 5 ).get();
-
-        assertEquals( 5, incorrectNode.get( "entities" ).size() );
-
-        while ( checkResultsNum < 5 ) {
-            assertEquals( activities.entityIndex( query, checkResultsNum ),
-                    activities.entityIndexLimit( query, 5, checkResultsNum ) );
-            checkResultsNum++;
-        }
-    }
-
-  /*
-   * public JsonNode entityIndex(JsonNode container, int index) { return
-   * container.get("entities").get(index); }
-   */
-
-
-    @Test
-    // USERGRID-1521
-    public void orderByReturnCorrectResults() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        int size = 200;
-
-        Map<String, String> actor = hashMap( "displayName", "Erin" );
-        Map<String, Object> props = new HashMap<String, Object>();
-
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-        List<JsonNode> activites = new ArrayList<JsonNode>( size );
-
-        for ( int i = 0; i < size; i++ ) {
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props ).get( "entities" ).get( 0 );
-            activites.add( activity );
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        long lastCreated = activites.get( activites.size() - 1 ).get( "created" ).asLong();
-
-        String errorQuery = String.format( "select * where created <= %d order by created desc", lastCreated );
-        String cursor = null;
-        int index = size - 1;
-
-        do {
-            JsonNode response = activities.withQuery( errorQuery ).get();
-            JsonNode cursorNode = response.get( "cursor" );
-
-            cursor = cursorNode != null ? cursorNode.asText() : null;
-
-            JsonNode entities = response.get( "entities" );
-
-            int returnSize = entities.size();
-
-            for ( int i = 0; i < returnSize; i++, index-- ) {
-                assertEquals( activites.get( index ), entities.get( i ) );
-            }
-
-            activities = activities.withCursor( cursor );
-        }
-        while ( cursor != null && cursor.length() > 0 );
-
-        assertEquals( "Paged to last result", -1, index );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/PagingEntitiesTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/PagingEntitiesTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/PagingEntitiesTest.java
deleted file mode 100644
index ab9f0f0..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/activities/PagingEntitiesTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection.activities;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import org.apache.commons.lang.ArrayUtils;
-
-import static org.junit.Assert.assertEquals;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class PagingEntitiesTest extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test //USERGRID-266
-    public void pageThroughConnectedEntities() throws IOException {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        long created = 0;
-        int maxSize = 100;
-        long[] verifyCreated = new long[maxSize];
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-
-
-        props.put( "actor", actor );
-        props.put( "verb", "go" );
-
-        for ( int i = 0; i < maxSize; i++ ) {
-
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-            verifyCreated[i] = activity.findValue( "created" ).longValue();
-            if ( i == 0 ) {
-                created = activity.findValue( "created" ).longValue();
-            }
-        }
-        ArrayUtils.reverse( verifyCreated );
-        
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where created >= " + created;
-
-
-        JsonNode node = activities.query( query, "limit", "2" ); //activities.query(query,"");
-        int index = 0;
-        while ( node.get( "entities" ).get( "created" ) != null ) {
-            assertEquals( 2, node.get( "entities" ).size() );
-
-            if ( node.get( "cursor" ) != null ) {
-                node = activities.query( query, "cursor", node.get( "cursor" ).toString() );
-            }
-
-            else {
-                break;
-            }
-        }
-    }
-
-
-    @Test //USERGRID-1253
-    public void pagingQueryReturnCorrectResults() throws Exception {
-
-        CustomCollection activities = context.collection( "activities" );
-
-        long created = 0;
-        int maxSize = 23;
-        long[] verifyCreated = new long[maxSize];
-        Map actor = hashMap( "displayName", "Erin" );
-        Map props = new HashMap();
-
-        props.put( "actor", actor );
-        props.put( "content", "bragh" );
-
-        for ( int i = 0; i < maxSize; i++ ) {
-
-            if ( i > 17 && i < 23 ) {
-                props.put( "verb", "stop" );
-            }
-            else {
-                props.put( "verb", "go" );
-            }
-            props.put( "ordinal", i );
-            JsonNode activity = activities.create( props );
-            verifyCreated[i] = activity.findValue( "created" ).longValue();
-            if ( i == 18 ) {
-                created = activity.findValue( "created" ).longValue();
-            }
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where created >= " + created + " or verb = 'stop'";
-
-        JsonNode node = activities.withQuery( query ).get();
-
-        for ( int index = 0; index < 5; index++ ) {
-            assertEquals( verifyCreated[maxSize - 1 - index],
-                    node.get( "entities" ).get( index ).get( "created" ).longValue() );
-        }
-
-        int totalEntitiesContained = activities.countEntities( query );
-
-        assertEquals( 5, totalEntitiesContained );
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
new file mode 100644
index 0000000..4010a05
--- /dev/null
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
@@ -0,0 +1,87 @@
+/*
+ * 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.collection.devices;
+
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.junit.Test;
+import org.apache.usergrid.cassandra.Concurrent;
+import org.apache.usergrid.rest.AbstractRestIT;
+
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import org.junit.Ignore;
+
+
+@Concurrent()
+public class DevicesResourceIT extends AbstractRestIT {
+
+    @Test
+    @Ignore("cannot be supported with Core Persistence which requires time based UUIDs")
+    public void putWithUUIDShouldCreateAfterDelete() throws IOException {
+
+        Map<String, String> payload = new HashMap<String, String>();
+        UUID uuid = UUID.randomUUID();
+        payload.put( "name", "foo" );
+
+        String path = "devices/" + uuid;
+
+        refreshIndex("test-organization", "test-app");
+
+        JsonNode response = mapper.readTree( appPath( path ).put( String.class, payload ));
+
+        // create
+        JsonNode entity = getEntity( response, 0 );
+        assertNotNull( entity );
+        String newUuid = entity.get( "uuid" ).textValue();
+        assertEquals( uuid.toString(), newUuid );
+
+        // delete
+        response = mapper.readTree( appPath( path ).delete( String.class ));
+        assertNotNull( getEntity( response, 0 ) );
+
+        refreshIndex("test-organization", "test-app");
+
+        // check deleted
+        try {
+            response = mapper.readTree( appPath( path ).get( String.class ));
+            fail( "should get 404 error" );
+        }
+        catch ( UniformInterfaceException e ) {
+            assertEquals( 404, e.getResponse().getStatus() );
+        }
+
+        // create again
+        response = mapper.readTree( appPath( path ).put( String.class, payload ));
+        entity = getEntity( response, 0 );
+        assertNotNull( entity );
+
+        refreshIndex("test-organization", "test-app");
+
+        // check existence
+        response = mapper.readTree( appPath( path ).get( String.class ));
+        assertNotNull( getEntity( response, 0 ) );
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/3993f081/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GeoPagingTest.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GeoPagingTest.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GeoPagingTest.java
deleted file mode 100644
index db99c9f..0000000
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/groups/GeoPagingTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.usergrid.rest.applications.collection.groups;
-
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import java.io.IOException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.apache.usergrid.rest.AbstractRestIT;
-import org.apache.usergrid.rest.TestContextSetup;
-import org.apache.usergrid.rest.test.resource.CustomCollection;
-
-import static org.junit.Assert.assertEquals;
-import static org.apache.usergrid.utils.MapUtils.hashMap;
-
-
-/**
- * // TODO: Document this
- *
- * @author ApigeeCorporation
- * @since 4.0
- */
-public class GeoPagingTest extends AbstractRestIT {
-
-    @Rule
-    public TestContextSetup context = new TestContextSetup( this );
-
-
-    @Test //("Test uses up to many resources to run reliably") // USERGRID-1403
-    public void groupQueriesWithGeoPaging() throws IOException {
-
-        CustomCollection groups = context.application().collection( "test1groups" );
-
-        int maxRangeLimit = 2000;
-        long[] index = new long[maxRangeLimit];
-        Map actor = hashMap( "displayName", "Erin" );
-
-        Map props = new HashMap();
-
-        props.put( "actor", actor );
-        Map location = hashMap( "latitude", 37 );
-        location.put( "longitude", -75 );
-        props.put( "location", location );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-        for ( int i = 0; i < 5; i++ ) {
-            String newPath = String.format( "/kero" + i );
-            props.put( "path", newPath );
-            props.put( "ordinal", i );
-            JsonNode activity = groups.create( props );
-            index[i] = activity.findValue( "created" ).longValue();
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        String query = "select * where location within 20000 of 37,-75 "
-                + " and created > " + index[2] 
-                + " and created < " + index[4] + "";
-
-        JsonNode node = groups.withQuery( query ).get();
-        assertEquals( 1, node.get( "entities" ).size() );
-
-        assertEquals( index[3], node.get( "entities" ).get( 0 ).get( "created" ).longValue() );
-    }
-
-
-    @Test // USERGRID-1401
-    public void groupQueriesWithConsistentResults() throws IOException {
-
-        CustomCollection groups = context.application().collection( "test2groups" );
-
-        int maxRangeLimit = 20;
-        JsonNode[] saved = new JsonNode[maxRangeLimit];
-
-        Map<String, String> actor = hashMap( "displayName", "Erin" );
-        Map<String, Object> props = new HashMap<String, Object>();
-
-        props.put( "actor", actor );
-        Map<String, Integer> location = hashMap( "latitude", 37 );
-        location.put( "longitude", -75 );
-        props.put( "location", location );
-        props.put( "verb", "go" );
-        props.put( "content", "bragh" );
-
-        for ( int i = 0; i < 20; i++ ) {
-            String newPath = String.format( "/kero" + i );
-            props.put( "path", newPath );
-            props.put( "ordinal", i );
-            JsonNode activity = groups.create( props ).get( "entities" ).get( 0 );
-            saved[i] = activity;
-        }
-
-        refreshIndex(context.getOrgName(), context.getAppName());
-
-        JsonNode node = null;
-        for ( int consistent = 0; consistent < 20; consistent++ ) {
-
-            String query = String.format( 
-                "select * where location within 100 of 37, -75 and ordinal >= %d and ordinal < %d", 
-                saved[7].get( "ordinal" ).asLong(), saved[10].get( "ordinal" ).asLong() );
-
-            node = groups.withQuery( query ).get(); //groups.query(query);
-
-            JsonNode entities = node.get( "entities" );
-
-            assertEquals( 3, entities.size() );
-
-            for ( int i = 0; i < 3; i++ ) {
-                // shouldn't start at 10 since you're excluding it above in the query, it should return 9,8,7
-                assertEquals( saved[7 + i], entities.get( i ) );
-            }
-        }
-    }
-}


[8/8] incubator-usergrid git commit: Merge branch 'two-dot-o-rest-refactor' of github.com:apache/incubator-usergrid into two-dot-o-rest-refactor

Posted by ro...@apache.org.
Merge branch 'two-dot-o-rest-refactor' of github.com:apache/incubator-usergrid into two-dot-o-rest-refactor


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

Branch: refs/heads/two-dot-o-rest-refactor
Commit: c41e920bbd317ffb1b183c7d2927ee7f07160c76
Parents: cc08a04 66b8ecb
Author: amuramoto <am...@apigee.com>
Authored: Wed Sep 17 14:52:59 2014 -0700
Committer: amuramoto <am...@apigee.com>
Committed: Wed Sep 17 14:52:59 2014 -0700

----------------------------------------------------------------------
 .../usergrid/rest/ConcurrentRestITSuite.java    |  12 +-
 .../org/apache/usergrid/rest/RestITSuite.java   |   9 +-
 .../usergrid/rest/management/AccessTokenIT.java |  81 ++++
 .../rest/management/ApplicationsIT.java         | 251 +++++++++++++
 .../rest/management/ManagementResourceIT.java   | 284 --------------
 .../rest/management/OrganizationsIT.java        | 191 ++++++++++
 .../rest/management/RegistrationIT.java         | 369 -------------------
 .../organizations/AdminEmailEncodingIT.java     | 119 ------
 .../applications/ApplicationsIT.java            |  91 -----
 9 files changed, 529 insertions(+), 878 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/c41e920b/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
----------------------------------------------------------------------
diff --cc stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
index c6d2705,9a404bf..39a1eed
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/ConcurrentRestITSuite.java
@@@ -23,23 -23,19 +23,19 @@@ import org.junit.runners.Suite
  import org.apache.usergrid.cassandra.CassandraResource;
  import org.apache.usergrid.cassandra.Concurrent;
  import org.apache.usergrid.cassandra.ConcurrentSuite;
 -import org.apache.usergrid.rest.applications.ApplicationRequestCounterIT;
 +import org.apache.usergrid.rest.applications.events.ApplicationRequestCounterIT;
  import org.apache.usergrid.rest.applications.ApplicationResourceIT;
 -import org.apache.usergrid.rest.applications.DevicesResourceIT;
 +import org.apache.usergrid.rest.applications.collection.devices.DevicesResourceIT;
  import org.apache.usergrid.rest.applications.assets.AssetResourceIT;
 -import org.apache.usergrid.rest.applications.collection.PagingResourceIT;
 +import org.apache.usergrid.rest.applications.collection.paging.PagingResourceIT;
  import org.apache.usergrid.rest.applications.events.EventsResourceIT;
 -import org.apache.usergrid.rest.applications.users.ActivityResourceIT;
 -import org.apache.usergrid.rest.applications.users.CollectionsResourceIT;
 -import org.apache.usergrid.rest.applications.users.GroupResourceIT;
 -import org.apache.usergrid.rest.applications.users.OwnershipResourceIT;
 -import org.apache.usergrid.rest.applications.users.PermissionsResourceIT;
 -import org.apache.usergrid.rest.applications.users.UserResourceIT;
 +import org.apache.usergrid.rest.applications.collection.activities.ActivityResourceIT;
 +import org.apache.usergrid.rest.applications.collection.CollectionsResourceIT;
 +import org.apache.usergrid.rest.applications.collection.groups.GroupResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.OwnershipResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.PermissionsResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.UserResourceIT;
  import org.apache.usergrid.rest.filters.ContentTypeResourceIT;
- import org.apache.usergrid.rest.management.ManagementResourceIT;
- import org.apache.usergrid.rest.management.RegistrationIT;
- import org.apache.usergrid.rest.management.organizations.AdminEmailEncodingIT;
- import org.apache.usergrid.rest.management.users.organizations.UsersOrganizationsResourceIT;
  
  
  @RunWith(ConcurrentSuite.class)

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/c41e920b/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
----------------------------------------------------------------------
diff --cc stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
index a28fa89,7630bb1..d4b15c4
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/RestITSuite.java
@@@ -22,20 -22,18 +22,18 @@@ import org.junit.runner.RunWith
  import org.junit.runners.Suite;
  import org.apache.usergrid.cassandra.CassandraResource;
  import org.apache.usergrid.cassandra.Concurrent;
 -import org.apache.usergrid.rest.applications.ApplicationRequestCounterIT;
 -import org.apache.usergrid.rest.applications.DevicesResourceIT;
 +import org.apache.usergrid.rest.applications.events.ApplicationRequestCounterIT;
 +import org.apache.usergrid.rest.applications.collection.devices.DevicesResourceIT;
  import org.apache.usergrid.rest.applications.assets.AssetResourceIT;
 -import org.apache.usergrid.rest.applications.collection.PagingResourceIT;
 +import org.apache.usergrid.rest.applications.collection.paging.PagingResourceIT;
  import org.apache.usergrid.rest.applications.events.EventsResourceIT;
 -import org.apache.usergrid.rest.applications.users.ActivityResourceIT;
 -import org.apache.usergrid.rest.applications.users.CollectionsResourceIT;
 -import org.apache.usergrid.rest.applications.users.GroupResourceIT;
 -import org.apache.usergrid.rest.applications.users.OwnershipResourceIT;
 -import org.apache.usergrid.rest.applications.users.PermissionsResourceIT;
 -import org.apache.usergrid.rest.applications.users.UserResourceIT;
 +import org.apache.usergrid.rest.applications.collection.activities.ActivityResourceIT;
 +import org.apache.usergrid.rest.applications.collection.CollectionsResourceIT;
 +import org.apache.usergrid.rest.applications.collection.groups.GroupResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.OwnershipResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.PermissionsResourceIT;
 +import org.apache.usergrid.rest.applications.collection.users.UserResourceIT;
  import org.apache.usergrid.rest.filters.ContentTypeResourceIT;
- import org.apache.usergrid.rest.management.organizations.AdminEmailEncodingIT;
- import org.apache.usergrid.rest.management.users.organizations.UsersOrganizationsResourceIT;
  
  @RunWith(Suite.class)
  @Suite.SuiteClasses(