usergrid-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From snoopd...@apache.org
Subject [80/81] [abbrv] Merge branch 'master' into two-dot-o
Date Thu, 13 Feb 2014 13:22:12 GMT
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/.gitignore
----------------------------------------------------------------------
diff --cc .gitignore
index 5427973,3684d76..b14275b
--- a/.gitignore
+++ b/.gitignore
@@@ -18,5 -18,4 +18,3 @@@ Ico
  /portal/dist
  /portal/bower_components
  /portal/.idea
- .Trashes
--/stack/corepersistence/priamcluster/aws.properties

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
----------------------------------------------------------------------
diff --cc stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
index bc456dc,0000000..2586285
mode 100644,000000..100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
@@@ -1,254 -1,0 +1,253 @@@
 +/*
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *    http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing,
 + * software distributed under the License is distributed on an
 + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 + * KIND, either express or implied.  See the License for the
 + * specific language governing permissions and limitations
 + * under the License.
 + */
 +package org.apache.usergrid.persistence.collection.impl;
 +
 +
 +import java.util.UUID;
 +
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import org.apache.usergrid.persistence.collection.CollectionScope;
 +import org.apache.usergrid.persistence.collection.EntityCollectionManager;
 +import org.apache.usergrid.persistence.collection.mvcc.entity.MvccEntity;
 +import org.apache.usergrid.persistence.collection.mvcc.entity.ValidationUtils;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.CollectionIoEvent;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.delete.DeleteCommit;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.delete.DeleteStart;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.load.Load;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteCommit;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteOptimisticVerify;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteStart;
 +import org.apache.usergrid.persistence.collection.mvcc.stage.write.WriteUniqueVerify;
- import org.apache.usergrid.persistence.collection.rx.Concurrent;
 +import org.apache.usergrid.persistence.collection.service.UUIDService;
 +import org.apache.usergrid.persistence.collection.util.EntityUtils;
 +import org.apache.usergrid.persistence.model.entity.Entity;
 +import org.apache.usergrid.persistence.model.entity.Id;
 +
 +import com.google.common.base.Preconditions;
 +import com.google.inject.Inject;
 +import com.google.inject.assistedinject.Assisted;
 +
 +import rx.Observable;
 +import rx.Scheduler;
 +import rx.util.functions.Func1;
 +import rx.util.functions.Func2;
 +import rx.util.functions.FuncN;
 +
 +
 +/**
 + * Simple implementation.  Should perform  writes, delete and load.
 + *
 + * TODO T.N. maybe refactor the stage operations into their own classes for clarity and organization?
 + *
 + * @author tnine
 + */
 +public class EntityCollectionManagerImpl implements EntityCollectionManager {
 +
 +    private static final Logger logger = LoggerFactory.getLogger( EntityCollectionManagerImpl.class );
 +
 +    private final CollectionScope collectionScope;
 +    private final UUIDService uuidService;
 +    private final Scheduler scheduler;
 +
 +
 +    //start stages
 +    private final WriteStart writeStart;
 +    private final WriteUniqueVerify writeVerifyUnique;
 +    private final WriteOptimisticVerify writeOptimisticVerify;
 +    private final WriteCommit writeCommit;
 +
 +    //load stages
 +    private final Load load;
 +
 +
 +    //delete stages
 +    private final DeleteStart deleteStart;
 +    private final DeleteCommit deleteCommit;
 +
 +
 +    @Inject
 +    public EntityCollectionManagerImpl( final UUIDService uuidService, final WriteStart writeStart,
 +                                        final Scheduler scheduler, final WriteUniqueVerify writeVerifyUnique,
 +                                        final WriteOptimisticVerify writeOptimisticVerify,
 +                                        final WriteCommit writeCommit, final Load load, final DeleteStart deleteStart,
 +                                        final DeleteCommit deleteCommit,
 +                                        @Assisted final CollectionScope collectionScope ) {
 +
 +
 +        Preconditions.checkNotNull( uuidService, "uuidService must be defined" );
 +        ValidationUtils.validateCollectionScope( collectionScope );
 +
 +
 +        this.writeStart = writeStart;
 +        this.writeVerifyUnique = writeVerifyUnique;
 +        this.writeOptimisticVerify = writeOptimisticVerify;
 +        this.writeCommit = writeCommit;
 +        this.load = load;
 +        this.deleteStart = deleteStart;
 +        this.deleteCommit = deleteCommit;
 +
 +
 +        this.uuidService = uuidService;
 +        this.scheduler = scheduler;
 +        this.collectionScope = collectionScope;
 +    }
 +
 +
 +    @Override
 +    public Observable<Entity> write( final Entity entity ) {
 +        //do our input validation
 +
 +        Preconditions.checkNotNull( entity, "Entity is required in the new stage of the mvcc write" );
 +
 +        final Id entityId = entity.getId();
 +
 +        Preconditions.checkNotNull( entityId, "The entity id is required to be set for an update operation" );
 +
 +        Preconditions
 +                .checkNotNull( entityId.getUuid(), "The entity id uuid is required to be set for an update operation" );
 +
 +        Preconditions
 +                .checkNotNull( entityId.getType(), "The entity id type required to be set for an update operation" );
 +
 +
 +        final UUID version = uuidService.newTimeUUID();
 +
 +        EntityUtils.setVersion( entity, version );
 +
 +
 +        /**
 +         *fire the stages
 +         * TODO use our own scheduler to help with multitenancy here.
 +         * TODO writeOptimisticVerify and writeVerifyUnique should happen concurrently to reduce user wait time
 +         */
 +
 +        //these 3 lines could be done in a single line, but they are on multiple lines for clarity
 +
 +        //create our observable and start the write
 +        CollectionIoEvent<Entity> writeData = new CollectionIoEvent<Entity>( collectionScope, entity );
 +
 +        Observable<CollectionIoEvent<MvccEntity>> observable =
 +                Observable.from( writeData ).subscribeOn( scheduler ).map( writeStart ).flatMap(
 +                        new Func1<CollectionIoEvent<MvccEntity>, Observable<CollectionIoEvent<MvccEntity>>>() {
 +
 +
 +                            @Override
 +                            public Observable<CollectionIoEvent<MvccEntity>> call(
 +                                    final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent ) {
 +
 +                                //do the unique and optimistic steps in parallel
 +
 +                                /**
 +                                 *unique function.  Since there can be more than 1 unique value in this entity
 +                                 * the unique verification step itself is multiple parallel executions.
 +                                 * This is why we use "flatMap" instead of "map", which allows the
 +                                 * WriteVerifyUnique stage to execute multiple verification steps in parallel and
 +                                 * zip the results
 +                                 */
 +
 +
 +                                Observable<CollectionIoEvent<MvccEntity>> unique =
 +                                        Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
 +                                                  .flatMap( writeVerifyUnique);
 +
 +
 +                                //optimistic verification
 +                                Observable<CollectionIoEvent<MvccEntity>> optimistic =
 +                                        Observable.from( mvccEntityCollectionIoEvent ).subscribeOn( scheduler )
 +                                                  .map( writeOptimisticVerify );
 +
 +
 +                                //zip the results
 +                                /**
 +                                 * TODO: Should the zip only return errors here, and if errors are present, we throw during the zip phase?  I couldn't find "
 +                                 */
 +
 +                               return Observable.zip( unique, optimistic, new Func2<CollectionIoEvent<MvccEntity>,
 +                                       CollectionIoEvent<MvccEntity>, CollectionIoEvent<MvccEntity>>() {
 +                                   @Override
 +                                   public CollectionIoEvent<MvccEntity> call(
 +                                           final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent,
 +                                           final CollectionIoEvent<MvccEntity> mvccEntityCollectionIoEvent2 ) {
 +
 +                                       return mvccEntityCollectionIoEvent;
 +                                   }
 +                               } );
 +                            }
 +                        } );
 +
 +
 +//        //execute all validation stages concurrently.  Needs refactored when this is done.  https://github
 +//        // .com/Netflix/RxJava/issues/627
 +//        observable =
 +//                Concurrent.concurrent( observable, scheduler, new WaitZip(), writeVerifyUnique, writeOptimisticVerify );
 +
 +        //return the commit result.
 +        return observable.map( writeCommit );
 +    }
 +
 +
 +    @Override
 +    public Observable<Void> delete( final Id entityId ) {
 +
 +
 +        Preconditions.checkNotNull( entityId, "Entity id is required in this stage" );
 +        Preconditions.checkNotNull( entityId.getUuid(), "Entity id is required in this stage" );
 +        Preconditions.checkNotNull( entityId.getType(), "Entity type is required in this stage" );
 +
 +
 +        return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
 +                         .map( deleteStart ).map( deleteCommit );
 +    }
 +
 +
 +    @Override
 +    public Observable<Entity> load( final Id entityId ) {
 +
 +        Preconditions.checkNotNull( entityId, "Entity id required in the load stage" );
 +        Preconditions.checkNotNull( entityId.getUuid(), "Entity id uuid required in the load stage" );
 +        Preconditions.checkNotNull( entityId.getType(), "Entity id type required in the load stage" );
 +
 +        return Observable.from( new CollectionIoEvent<Id>( collectionScope, entityId ) ).subscribeOn( scheduler )
 +                         .map( load );
 +    }
 +
 +
 +    /**
 +     * Class that validates all results are equal then proceeds
 +     */
 +    private static class WaitZip<R> implements FuncN<R> {
 +
 +
 +        private WaitZip() {
 +        }
 +
 +
 +        @Override
 +        public R call( final Object... args ) {
 +
 +            for ( int i = 0; i < args.length - 1; i++ ) {
 +                assert args[i] == args[i + 1];
 +            }
 +
 +            return ( R ) args[0];
 +        }
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/pom.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/pom.xml
index 30bb3dd,4f523a6..22158b5
--- a/stack/query-validator/pom.xml
+++ b/stack/query-validator/pom.xml
@@@ -3,9 -3,9 +3,9 @@@
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
-         <groupId>org.usergrid</groupId>
+         <groupId>org.apache.usergrid</groupId>
          <artifactId>usergrid</artifactId>
 -        <version>0.0.16-SNAPSHOT</version>
 +        <version>0.0.28-SNAPSHOT</version>
      </parent>
      <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@@ -81,8 -77,9 +81,8 @@@
                              <goal>test-jar</goal>
                          </goals>
                          <configuration>
 -                            <classifier>tests</classifier>
                              <includes>
-                                 <include>**/org/usergrid/**</include>
+                                 <include>**/org/apache/usergrid/**</include>
                              </includes>
                          </configuration>
                      </execution>
@@@ -92,94 -89,47 +92,94 @@@
      </build>
      <dependencies>
          <dependency>
-             <groupId>org.usergrid</groupId>
+             <groupId>org.apache.usergrid</groupId>
              <artifactId>usergrid-config</artifactId>
              <version>${project.version}</version>
 -            <scope>test</scope>
 -            <classifier>tests</classifier>
          </dependency>
 +
          <dependency>
-             <groupId>org.usergrid</groupId>
-             <artifactId>usergrid-core</artifactId>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-count-batcher</artifactId>
              <version>${project.version}</version>
 +            <exclusions>
 +                <exclusion>
 +                    <artifactId>commons-logging</artifactId>
 +                    <groupId>commons-logging</groupId>
 +                </exclusion>
 +            </exclusions>
          </dependency>
 +
          <dependency>
-             <groupId>org.usergrid</groupId>
-             <artifactId>usergrid-rest</artifactId>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-count-common</artifactId>
              <version>${project.version}</version>
 +            <classifier>classes</classifier>
 +            <exclusions>
 +                <exclusion>
 +                    <artifactId>servlet-api</artifactId>
 +                    <groupId>javax.servlet</groupId>
 +                </exclusion>
 +            </exclusions>
          </dependency>
 +
          <dependency>
-             <groupId>org.usergrid</groupId>
-             <artifactId>usergrid-rest</artifactId>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-test-utils</artifactId>
              <version>${project.version}</version>
 -            <scope>test</scope>
 +            <classifier>compiled-jsp</classifier>
          </dependency>
 +
          <dependency>
-             <groupId>org.usergrid</groupId>
-             <artifactId>usergrid-rest</artifactId>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-core</artifactId>
              <version>${project.version}</version>
 -            <exclusions>
 -                <exclusion>
 -                    <artifactId>commons-logging</artifactId>
 -                    <groupId>commons-logging</groupId>
 -                </exclusion>
 -            </exclusions>
 +            <classifier>tests</classifier>
 +            <scope>test</scope>
          </dependency>
 +
 +        <!-- Apache Dependencies -->
 +
          <dependency>
 -            <groupId>org.apache.usergrid</groupId>
 -            <artifactId>usergrid-scheduler</artifactId>
 -            <version>${project.version}</version>
 +            <groupId>commons-collections</groupId>
 +            <artifactId>commons-collections</artifactId>
 +        </dependency>
 +
 +        <!-- SUN, Javax Package, and Other Com Dependencies -->
 +
 +
 +        <dependency>
 +            <groupId>javax.servlet</groupId>
 +            <artifactId>javax.servlet-api</artifactId>
 +            <scope>provided</scope>
 +        </dependency>
 +
 +        <dependency>
 +            <groupId>javax.servlet</groupId>
 +            <artifactId>jstl</artifactId>
          </dependency>
 +
 +        <dependency>
 +            <groupId>org.springframework</groupId>
 +            <artifactId>spring-webmvc</artifactId>
 +        </dependency>
 +
 +        <!--<dependency>-->
 +        <!--&lt;!&ndash; TODO - should not scope be 'test' ? &ndash;&gt;-->
 +        <!--<groupId>org.slf4j</groupId>-->
 +        <!--<artifactId>jcl-over-slf4j</artifactId>-->
 +        <!--</dependency>-->
 +
 +        <!--<dependency>-->
 +        <!--&lt;!&ndash; TODO - should not scope be 'test' ? &ndash;&gt;-->
 +        <!--<groupId>org.slf4j</groupId>-->
 +        <!--<artifactId>jul-to-slf4j</artifactId>-->
 +        <!--</dependency>-->
 +
 +        <!-- Testing and Logging Dependencies -->
 +
          <dependency>
-             <groupId>org.usergrid</groupId>
-             <artifactId>usergrid-config</artifactId>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-core</artifactId>
              <version>${project.version}</version>
              <scope>test</scope>
              <classifier>tests</classifier>
@@@ -285,12 -212,22 +285,29 @@@
              <artifactId>sqlite-jdbc</artifactId>
              <version>3.7.2</version>
          </dependency>
 -            <dependency>
 +
 +        <dependency>
 +            <groupId>org.springframework</groupId>
 +            <artifactId>spring-jdbc</artifactId>
 +            <version>${org.springframework.version}</version>
 +        </dependency>
++        <dependency>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-java-client</artifactId>
+             <version>0.0.3</version>
+             <scope>compile</scope>
+         </dependency>
+         <dependency>
+             <groupId>org.apache.usergrid</groupId>
+             <artifactId>usergrid-standalone</artifactId>
+             <version>${project.version}</version>
+             <exclusions>
+                 <exclusion>
+                     <artifactId>commons-logging</artifactId>
+                     <groupId>commons-logging</groupId>
+                 </exclusion>
+             </exclusions>
+         </dependency>
 +
      </dependencies>
- </project>
+ </project>

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
index 7a7015e,c53d08b..796b1bf
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java
@@@ -14,29 -12,30 +14,29 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
- 
- import org.apache.commons.lang.StringUtils;
- import org.codehaus.jackson.JsonNode;
- import org.springframework.http.HttpMethod;
- import org.springframework.stereotype.Component;
- import org.usergrid.java.client.Client;
- import org.usergrid.java.client.response.ApiResponse;
- import org.usergrid.persistence.Entity;
- import org.usergrid.persistence.Schema;
+ package org.apache.usergrid.query.validator;
  
 -import org.apache.commons.lang.StringUtils;
 -import org.codehaus.jackson.JsonNode;
 -import org.springframework.http.HttpMethod;
 -import org.springframework.stereotype.Component;
 -import org.apache.usergrid.java.client.response.ApiResponse;
 -import org.apache.usergrid.persistence.Entity;
 -
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.logging.Level;
  import java.util.logging.Logger;
--
- import static org.usergrid.java.client.utils.ObjectUtils.isEmpty;
 -import static org.apache.usergrid.java.client.utils.ObjectUtils.isEmpty;
++import org.apache.commons.lang.StringUtils;
++import static org.apache.commons.lang.StringUtils.isEmpty;
++import org.apache.usergrid.persistence.Entity;
++import org.apache.usergrid.persistence.Schema;
++import org.codehaus.jackson.JsonNode;
++import org.springframework.http.HttpMethod;
++import org.springframework.stereotype.Component;
++import org.usergrid.java.client.Client;
++import org.usergrid.java.client.response.ApiResponse;
++import org.usergrid.query.validator.QueryEntity;
++import org.usergrid.query.validator.QueryRunner;
  
  /**
 - * @author Sung-ju Jin(realbeast)
 + * @author Sungju Jin
   */
  @Component
  public class ApiServerRunner implements QueryRunner {
@@@ -79,23 -78,23 +79,24 @@@
      }
  
      public boolean insertDatas() {
-         List<org.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
-         for(org.usergrid.java.client.entities.Entity entity : clientEntities) {
-             ApiResponse response = client.createEntity(entity);
-             if( response == null || !StringUtils.isEmpty(response.getError()) ) {
-                 logger.log(Level.SEVERE, response.getErrorDescription());
-                 //throw new RuntimeException(response.getErrorDescription());
-             } else {
-                 logger.log(Level.INFO, response.toString());
-             }
-         }
-         return true;
-     }
 +
-     private List<org.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
-         List<org.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.usergrid.java.client.entities.Entity>();
+        List<org.apache.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities());
+        for(org.apache.usergrid.java.client.entities.Entity entity : clientEntities) {
+            ApiResponse response = client.createEntity(entity);
+            if( response == null || !StringUtils.isEmpty(response.getError()) ) {
+                logger.log(Level.SEVERE, response.getErrorDescription());
+                //throw new RuntimeException(response.getErrorDescription());
+            } else {
+                logger.log(Level.INFO, response.toString());
+            }
+        }
+        return true;
+     }
+ 
+     private List<org.apache.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) {
+         List<org.apache.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.apache.usergrid.java.client.entities.Entity>();
          for(Entity entity : entities) {
-             org.usergrid.java.client.entities.Entity clientEntity = new org.usergrid.java.client.entities.Entity();
+             org.apache.usergrid.java.client.entities.Entity clientEntity = new org.apache.usergrid.java.client.entities.Entity();
              clientEntity.setType(entity.getType());
              Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity);
              for(String key : properties.keySet()) {

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
index c43afe7,77893bd..5790204
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryEntity.java
@@@ -1,23 -1,6 +1,23 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 + * See the License for the specific language governing permissions and
 + * limitations under the License.
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
- import org.usergrid.persistence.DynamicEntity;
+ import org.apache.usergrid.persistence.DynamicEntity;
  
  import java.util.Map;
  

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
index 59032ba,d2989c7..eecc0d2
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRequest.java
@@@ -14,11 -12,11 +14,11 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
  /**
 - * @author Sung-ju Jin(realbeast)
 + * @author Sungju Jin
   */
  public class QueryRequest {
      private String dbQuery;
@@@ -64,4 -63,12 +64,4 @@@
              this.limit = limit;
          }
      }
- }
 -
 -    public boolean isIgnoreOrdering() {
 -        return ignoreOrdering;
 -    }
 -
 -    public void setIgnoreOrdering(boolean ignoreOrdering) {
 -        this.ignoreOrdering = ignoreOrdering;
 -    }
+ }

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
index 6a05c13,aa152d5..b3669ff
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryResponse.java
@@@ -14,11 -12,11 +14,11 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
  import org.apache.commons.lang.StringUtils;
- import org.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.Entity;
  
  import java.util.List;
  

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
index fbc6220,06341d6..b99038d
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryRunner.java
@@@ -14,15 -12,14 +14,15 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
- import org.usergrid.persistence.Entity;
 -import java.util.List;
+ import org.apache.usergrid.persistence.Entity;
  
 +import java.util.List;
 +
  /**
 - * @author Sung-ju Jin(realbeast)
 + * @author Sungju Jin
   */
  public interface QueryRunner {
      public boolean setup();

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
index 35f3994,8b14737..6f7b9e6
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidationConfiguration.java
@@@ -1,24 -1,7 +1,24 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 + * See the License for the specific language governing permissions and
 + * limitations under the License.
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
- import org.usergrid.persistence.Entity;
- import org.usergrid.utils.InflectionUtils;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.utils.InflectionUtils;
  
  import java.util.List;
  

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
index 0e7f89a,180a8e5..4d46950
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/QueryValidator.java
@@@ -14,8 -12,8 +14,8 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Component;

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
index dd728c8,a1932a0..7c7aa55
--- a/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
+++ b/stack/query-validator/src/main/java/org/usergrid/query/validator/SqliteRunner.java
@@@ -14,16 -12,16 +14,14 @@@
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
 - ******************************************************************************/
 + */
- package org.usergrid.query.validator;
+ package org.apache.usergrid.query.validator;
  
  import org.apache.commons.lang.StringUtils;
  import org.springframework.beans.factory.annotation.Autowired;
--import org.springframework.jdbc.core.JdbcTemplate;
--import org.springframework.jdbc.core.RowMapper;
  import org.springframework.stereotype.Component;
- import org.usergrid.persistence.Entity;
- import org.usergrid.persistence.Schema;
+ import org.apache.usergrid.persistence.Entity;
+ import org.apache.usergrid.persistence.Schema;
  
  import java.sql.ResultSet;
  import java.sql.ResultSetMetaData;
@@@ -31,9 -29,9 +29,12 @@@ import java.sql.SQLException
  import java.util.List;
  import java.util.Map;
  import java.util.logging.Logger;
++import javax.swing.tree.RowMapper;
++import org.usergrid.query.validator.QueryEntity;
++import org.usergrid.query.validator.QueryRunner;
  
  /**
 - * @author Sung-ju Jin(realbeast)
 + * @author Sungju Jin
   */
  @Component
  public class SqliteRunner implements QueryRunner {

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
index 89679d7,36355a8..3a8c577
--- a/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
+++ b/stack/query-validator/src/main/resources/usergrid-query-validator-context.xml
@@@ -1,14 -1,16 +1,14 @@@
  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
 -	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 -	xmlns:context="http://www.springframework.org/schema/context"
 -	xsi:schemaLocation="
 -	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 -	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
 +       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 +       xmlns:context="http://www.springframework.org/schema/context"
 +       xsi:schemaLocation="
 +        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 +        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
  
-     <context:annotation-config />
-     <context:component-scan base-package="org.usergrid.query.validator" />
+ 	<context:annotation-config />
+     <context:component-scan base-package="org.apache.usergrid.query.validator" />
  
 -    <import resource="classpath:/usergrid-core-context.xml" />
 -
      <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="org.sqlite.JDBC" />

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/query-validator/src/test/resources/usergrid-test-context.xml
----------------------------------------------------------------------
diff --cc stack/query-validator/src/test/resources/usergrid-test-context.xml
index bec5638,5df1815..b07cc2d
--- a/stack/query-validator/src/test/resources/usergrid-test-context.xml
+++ b/stack/query-validator/src/test/resources/usergrid-test-context.xml
@@@ -20,17 -17,9 +20,17 @@@
          </property>
      </bean>
  
 -	<import resource="classpath:/usergrid-query-validator-context.xml" />
 +    <import resource="usergrid-rest-context.xml"/>
 +
 +    <bean id="traceTagManager" class="org.usergrid.persistence.cassandra.util.TraceTagManager">
 +        <property name="reportUnattached" value="false"/>
 +        <property name="traceEnabled" value="false"/>
 +    </bean>
 +
 +
 +    <bean id="binaryStore" class="org.usergrid.services.assets.data.LocalFileBinaryStore"/>
  
-     <bean id="setup" class="org.usergrid.persistence.cassandra.Setup">
+     <bean id="setup" class="org.apache.usergrid.persistence.cassandra.Setup">
          <constructor-arg ref="entityManagerFactory"/>
          <constructor-arg ref="cassandraService"/>
      </bean>
@@@ -41,6 -30,5 +41,6 @@@
          <constructor-arg ref="cassandraCluster"/>
      </bean>
  
 +    <import resource="usergrid-query-validator-context.xml"/>
  
- </beans>
+ </beans>

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
----------------------------------------------------------------------
diff --cc stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
index 0000000,552d501..3583b88
mode 000000,100644..100644
--- a/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
+++ b/stack/rest/src/main/java/org/apache/usergrid/rest/applications/ApplicationResource.java
@@@ -1,0 -1,610 +1,610 @@@
+ /*******************************************************************************
+  * Copyright 2012 Apigee Corporation
+  *
+  * Licensed under the Apache License, Version 2.0 (the "License");
+  * you may not use this file except in compliance with the License.
+  * You may obtain a copy of the License at
+  *
+  *   http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  ******************************************************************************/
+ package org.apache.usergrid.rest.applications;
+ 
+ 
+ import java.io.UnsupportedEncodingException;
+ import java.net.URLEncoder;
+ import java.util.Map;
+ import java.util.UUID;
+ 
+ import javax.ws.rs.Consumes;
+ import javax.ws.rs.DELETE;
+ import javax.ws.rs.DefaultValue;
+ import javax.ws.rs.FormParam;
+ import javax.ws.rs.GET;
+ import javax.ws.rs.HeaderParam;
+ import javax.ws.rs.POST;
+ import javax.ws.rs.Path;
+ import javax.ws.rs.Produces;
+ import javax.ws.rs.QueryParam;
+ import javax.ws.rs.core.Context;
+ import javax.ws.rs.core.MediaType;
+ import javax.ws.rs.core.PathSegment;
+ import javax.ws.rs.core.Response;
+ import javax.ws.rs.core.UriInfo;
+ 
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+ import org.springframework.context.annotation.Scope;
+ import org.springframework.stereotype.Component;
+ import org.apache.usergrid.exception.NotImplementedException;
+ import org.apache.usergrid.management.ApplicationInfo;
+ import org.apache.usergrid.management.exceptions.DisabledAdminUserException;
+ import org.apache.usergrid.management.exceptions.DisabledAppUserException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAdminUserException;
+ import org.apache.usergrid.management.exceptions.UnactivatedAppUserException;
+ import org.apache.usergrid.mq.QueueManager;
+ import org.apache.usergrid.persistence.EntityManager;
+ import org.apache.usergrid.persistence.Identifier;
+ import org.apache.usergrid.persistence.SimpleEntityRef;
+ import org.apache.usergrid.persistence.entities.Application;
+ import org.apache.usergrid.persistence.entities.User;
+ import org.apache.usergrid.rest.AbstractContextResource;
+ import org.apache.usergrid.rest.applications.assets.AssetsResource;
+ import org.apache.usergrid.rest.applications.events.EventsResource;
+ import org.apache.usergrid.rest.applications.queues.QueueResource;
+ import org.apache.usergrid.rest.applications.users.UsersResource;
+ import org.apache.usergrid.rest.exceptions.AuthErrorInfo;
+ import org.apache.usergrid.rest.exceptions.RedirectionException;
+ import org.apache.usergrid.rest.security.annotations.RequireApplicationAccess;
+ import org.apache.usergrid.security.oauth.AccessInfo;
+ import org.apache.usergrid.security.oauth.ClientCredentialsInfo;
+ 
+ import org.apache.amber.oauth2.common.error.OAuthError;
+ import org.apache.amber.oauth2.common.exception.OAuthProblemException;
+ import org.apache.amber.oauth2.common.message.OAuthResponse;
+ import org.apache.amber.oauth2.common.message.types.GrantType;
+ import org.apache.shiro.authz.UnauthorizedException;
+ import org.apache.shiro.codec.Base64;
+ 
+ import com.sun.jersey.api.json.JSONWithPadding;
+ import com.sun.jersey.api.view.Viewable;
+ 
+ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
+ import static javax.servlet.http.HttpServletResponse.SC_OK;
+ import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
+ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+ 
+ import static org.apache.commons.lang.StringUtils.isNotBlank;
+ import static org.apache.usergrid.rest.exceptions.SecurityException.mappableSecurityException;
+ import static org.apache.usergrid.security.oauth.ClientCredentialsInfo.getUUIDFromClientId;
+ import static org.apache.usergrid.security.shiro.utils.SubjectUtils.isApplicationAdmin;
+ import static org.apache.usergrid.services.ServiceParameter.addParameter;
+ import static org.apache.usergrid.utils.StringUtils.stringOrSubstringAfterFirst;
+ import static org.apache.usergrid.utils.StringUtils.stringOrSubstringBeforeFirst;
+ 
+ 
+ @Component("org.apache.usergrid.rest.applications.ApplicationResource")
+ @Scope("prototype")
+ @Produces({
+         MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript",
+         "application/ecmascript", "text/jscript"
+ })
+ public class ApplicationResource extends ServiceResource {
+ 
+     public static final Logger logger = LoggerFactory.getLogger( ApplicationResource.class );
+ 
+     UUID applicationId;
+     QueueManager queues;
+ 
+ 
+     public ApplicationResource() {
+     }
+ 
+ 
+     public ApplicationResource init( UUID applicationId ) throws Exception {
+         this.applicationId = applicationId;
+         services = smf.getServiceManager( applicationId );
+         queues = qmf.getQueueManager( applicationId );
+         return this;
+     }
+ 
+ 
+     public QueueManager getQueues() {
+         return queues;
+     }
+ 
+ 
+     @Override
+     public UUID getApplicationId() {
+         return applicationId;
+     }
+ 
+ 
+     @Path("auth")
+     public AuthResource getAuthResource() throws Exception {
+         return getSubResource( AuthResource.class );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("queues")
+     public QueueResource getQueueResource() throws Exception {
+         return getSubResource( QueueResource.class ).init( queues, "" );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("events")
+     public EventsResource getEventsResource( @Context UriInfo ui ) throws Exception {
+         addParameter( getServiceParameters(), "events" );
+ 
+         PathSegment ps = getFirstPathSegment( "events" );
+         if ( ps != null ) {
+             addMatrixParams( getServiceParameters(), ui, ps );
+         }
+ 
+         return getSubResource( EventsResource.class );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("event")
+     public EventsResource getEventResource( @Context UriInfo ui ) throws Exception {
+         return getEventsResource( ui );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("assets")
+     public AssetsResource getAssetsResource( @Context UriInfo ui ) throws Exception {
+         logger.debug( "in assets n applicationResource" );
+         addParameter( getServiceParameters(), "assets" );
+ 
+         PathSegment ps = getFirstPathSegment( "assets" );
+         if ( ps != null ) {
+             addMatrixParams( getServiceParameters(), ui, ps );
+         }
+ 
+         return getSubResource( AssetsResource.class );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("asset")
+     public AssetsResource getAssetResource( @Context UriInfo ui ) throws Exception {
+         // TODO change to singular
+         logger.debug( "in asset in applicationResource" );
+         return getAssetsResource( ui );
+     }
+ 
+ 
+     @Path("users")
+     public UsersResource getUsers( @Context UriInfo ui ) throws Exception {
+         logger.debug( "ApplicationResource.getUsers" );
+         addParameter( getServiceParameters(), "users" );
+ 
+         PathSegment ps = getFirstPathSegment( "users" );
+         if ( ps != null ) {
+             addMatrixParams( getServiceParameters(), ui, ps );
+         }
+ 
+         return getSubResource( UsersResource.class );
+     }
+ 
+ 
+     @Path("user")
+     public UsersResource getUsers2( @Context UriInfo ui ) throws Exception {
+         return getUsers( ui );
+     }
+ 
+ 
+     @GET
+     @Path("token")
+     public Response getAccessToken( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+                                     @QueryParam("grant_type") String grant_type,
+                                     @QueryParam("username") String username, @QueryParam("password") String password,
+                                     @QueryParam("pin") String pin, @QueryParam("client_id") String client_id,
+                                     @QueryParam("client_secret") String client_secret, @QueryParam("code") String code,
+                                     @QueryParam("ttl") long ttl, @QueryParam("redirect_uri") String redirect_uri,
+                                     @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {
+ 
+         logger.debug( "ApplicationResource.getAccessToken" );
+ 
+         User user = null;
+ 
+         try {
+ 
+             if ( authorization != null ) {
+                 String type = stringOrSubstringBeforeFirst( authorization, ' ' ).toUpperCase();
+                 if ( "BASIC".equals( type ) ) {
+                     String token = stringOrSubstringAfterFirst( authorization, ' ' );
+                     String[] values = Base64.decodeToString( token ).split( ":" );
+                     if ( values.length >= 2 ) {
+                         client_id = values[0];
+                         client_secret = values[1];
+                     }
+                 }
+             }
+ 
+             // do checking for different grant types
+             String errorDescription = "invalid username or password";
+             if ( GrantType.PASSWORD.toString().equals( grant_type ) ) {
+                 try {
+                     user = management
+                             .verifyAppUserPasswordCredentials( services.getApplicationId(), username, password );
+                 }
+                 catch ( UnactivatedAppUserException uaue ) {
+                     errorDescription = "user not activated";
+                 }
+                 catch ( DisabledAppUserException daue ) {
+                     errorDescription = "user disabled";
+                 }
+                 catch ( Exception e1 ) {
++                    logger.warn( "Unexpected exception during token username/password verification", e1 );
++
+                 }
+             }
+             else if ( "pin".equals( grant_type ) ) {
+                 try {
+                     user = management.verifyAppUserPinCredentials( services.getApplicationId(), username, pin );
+                 }
+                 catch ( Exception e1 ) {
++                    logger.warn( "Unexpected exception during token pin verification", e1 );
++
+                 }
+             }
+             else if ( "client_credentials".equals( grant_type ) ) {
+                 try {
+                     AccessInfo access_info = management.authorizeClient( client_id, client_secret, ttl );
+                     if ( access_info != null ) {
+                         return Response.status( SC_OK ).type( jsonMediaType( callback ) )
+                                        .entity( wrapWithCallback( access_info, callback ) ).build();
+                     }
+                 }
+                 catch ( Exception e1 ) {
++                    logger.warn( "Unexpected exception during token client authentication", e1 );
+                 }
+             }
 -            else if ( "authorization_code".equals( grant_type ) ) {
 -                AccessInfo access_info = new AccessInfo();
 -                access_info.setAccessToken( code );
 -                return Response.status( SC_OK ).type( jsonMediaType( callback ) )
 -                               .entity( wrapWithCallback( access_info, callback ) ).build();
 -            }
+ 
+             if ( user == null ) {
+                 OAuthResponse response =
+                         OAuthResponse.errorResponse( SC_BAD_REQUEST ).setError( OAuthError.TokenResponse.INVALID_GRANT )
+                                      .setErrorDescription( errorDescription ).buildJSONMessage();
+                 return Response.status( response.getResponseStatus() ).type( jsonMediaType( callback ) )
+                                .entity( wrapWithCallback( response.getBody(), callback ) ).build();
+             }
+ 
+             String token = management.getAccessTokenForAppUser( services.getApplicationId(), user.getUuid(), ttl );
+ 
+             AccessInfo access_info =
+                     new AccessInfo().withExpiresIn( tokens.getMaxTokenAgeInSeconds( token ) ).withAccessToken( token )
+                                     .withProperty( "user", user );
+ 
+             return Response.status( SC_OK ).type( jsonMediaType( callback ) )
+                            .entity( wrapWithCallback( access_info, callback ) ).build();
+         }
+         catch ( OAuthProblemException e ) {
+             logger.error( "OAuth Error", e );
+             OAuthResponse res = OAuthResponse.errorResponse( SC_BAD_REQUEST ).error( e ).buildJSONMessage();
+             return Response.status( res.getResponseStatus() ).type( jsonMediaType( callback ) )
+                            .entity( wrapWithCallback( res.getBody(), callback ) ).build();
+         }
+     }
+ 
+ 
+     @POST
+     @Path("token")
+     @Consumes(APPLICATION_FORM_URLENCODED)
+     public Response getAccessTokenPost( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+                                         @FormParam("grant_type") String grant_type,
+                                         @FormParam("username") String username, @FormParam("password") String password,
+                                         @FormParam("pin") String pin, @FormParam("client_id") String client_id,
+                                         @FormParam("client_secret") String client_secret,
+                                         @FormParam("code") String code, @FormParam("ttl") long ttl,
+                                         @FormParam("redirect_uri") String redirect_uri,
+                                         @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {
+ 
+         logger.debug( "ApplicationResource.getAccessTokenPost" );
+ 
+         return getAccessToken( ui, authorization, grant_type, username, password, pin, client_id, client_secret, code,
+                 ttl, redirect_uri, callback );
+     }
+ 
+ 
+     @POST
+     @Path("token")
+     @Consumes(APPLICATION_JSON)
+     public Response getAccessTokenPostJson( @Context UriInfo ui, @HeaderParam("Authorization") String authorization,
+                                             Map<String, Object> json,
+                                             @QueryParam("callback") @DefaultValue("") String callback )
+             throws Exception {
+ 
+         String grant_type = ( String ) json.get( "grant_type" );
+         String username = ( String ) json.get( "username" );
+         String password = ( String ) json.get( "password" );
+         String client_id = ( String ) json.get( "client_id" );
+         String client_secret = ( String ) json.get( "client_secret" );
+         String pin = ( String ) json.get( "pin" );
+         String code = ( String ) json.get( "code" );
+         String redirect_uri = ( String ) json.get( "redirect_uri" );
+         long ttl = 0;
+ 
+         if ( json.get( "ttl" ) != null ) {
+             try {
+                 ttl = Long.parseLong( json.get( "ttl" ).toString() );
+             }
+             catch ( NumberFormatException nfe ) {
+                 throw new IllegalArgumentException( "ttl must be a number >= 0" );
+             }
+         }
+ 
+         return getAccessToken( ui, authorization, grant_type, username, password, pin, client_id, client_secret, code,
+                 ttl, redirect_uri, callback );
+     }
+ 
+ 
+     @GET
+     @Path("credentials")
+     @RequireApplicationAccess
+     public JSONWithPadding getKeys( @Context UriInfo ui,
+                                     @QueryParam("callback") @DefaultValue("callback") String callback )
+             throws Exception {
+ 
+         logger.debug( "AuthResource.keys" );
+ 
+         if ( !isApplicationAdmin( Identifier.fromUUID( applicationId ) ) ) {
+             throw new UnauthorizedException();
+         }
+ 
+         ClientCredentialsInfo kp =
+                 new ClientCredentialsInfo( management.getClientIdForApplication( services.getApplicationId() ),
+                         management.getClientSecretForApplication( services.getApplicationId() ) );
+ 
+         return new JSONWithPadding(
+                 createApiResponse().withCredentials( kp ).withAction( "get application keys" ).withSuccess(),
+                 callback );
+     }
+ 
+ 
+     @POST
+     @Path("credentials")
+     @RequireApplicationAccess
+     @Produces(MediaType.APPLICATION_JSON)
+     public JSONWithPadding generateKeys( @Context UriInfo ui,
+                                          @QueryParam("callback") @DefaultValue("callback") String callback )
+             throws Exception {
+ 
+         logger.debug( "AuthResource.keys" );
+ 
+         if ( !isApplicationAdmin( Identifier.fromUUID( applicationId ) ) ) {
+             throw new UnauthorizedException();
+         }
+ 
+         ClientCredentialsInfo kp =
+                 new ClientCredentialsInfo( management.getClientIdForApplication( services.getApplicationId() ),
+                         management.newClientSecretForApplication( services.getApplicationId() ) );
+ 
+         return new JSONWithPadding(
+                 createApiResponse().withCredentials( kp ).withAction( "generate application keys" ).withSuccess(),
+                 callback );
+     }
+ 
+ 
+     @GET
+     @Path("authorize")
+     public Viewable showAuthorizeForm( @Context UriInfo ui, @QueryParam("response_type") String response_type,
+                                        @QueryParam("client_id") String client_id,
+                                        @QueryParam("redirect_uri") String redirect_uri,
+                                        @QueryParam("scope") String scope, @QueryParam("state") String state ) {
+ 
+         try {
+             UUID uuid = getUUIDFromClientId( client_id );
+             if ( uuid == null ) {
+                 throw mappableSecurityException( AuthErrorInfo.OAUTH2_INVALID_CLIENT,
+                         "Unable to authenticate (OAuth). Invalid client_id" );
+             }
+ 
+             responseType = response_type;
+             clientId = client_id;
+             redirectUri = redirect_uri;
+             this.scope = scope;
+             this.state = state;
+ 
+             ApplicationInfo app = management.getApplicationInfo( applicationId );
+             applicationName = app.getName();
+ 
+             return handleViewable( "authorize_form", this );
+         }
+         catch ( RedirectionException e ) {
+             throw e;
+         }
+         catch ( Exception e ) {
+             return handleViewable( "error", e );
+         }
+     }
+ 
+ 
+     @POST
+     @Path("authorize")
+     @Produces(MediaType.TEXT_HTML)
+     public Viewable handleAuthorizeForm( @Context UriInfo ui, @FormParam("response_type") String response_type,
+                                          @FormParam("client_id") String client_id,
+                                          @FormParam("redirect_uri") String redirect_uri,
+                                          @FormParam("scope") String scope, @FormParam("state") String state,
+                                          @FormParam("username") String username,
+                                          @FormParam("password") String password ) {
+ 
+         try {
+             responseType = response_type;
+             clientId = client_id;
+             redirectUri = redirect_uri;
+             this.scope = scope;
+             this.state = state;
+ 
+             User user = null;
+             String errorDescription = "Username or password do not match";
+             try {
+                 user = management.verifyAppUserPasswordCredentials( services.getApplicationId(), username, password );
+             }
+             catch ( UnactivatedAdminUserException uaue ) {
+                 errorDescription = "user not activated";
+             }
+             catch ( DisabledAdminUserException daue ) {
+                 errorDescription = "user disabled";
+             }
+             catch ( Exception e1 ) {
++                logger.warn("Unexpected exception in authorize username/password verification", e1);
+             }
+ 
+             if ( ( user != null ) && isNotBlank( redirect_uri ) ) {
+                 String authorizationCode =
+                         management.getAccessTokenForAppUser( services.getApplicationId(), user.getUuid(), 0 );
+                 redirect_uri = buildRedirectUriWithAuthCode( redirect_uri, state, authorizationCode );
+ 
+                 throw new RedirectionException( redirect_uri );
+             }
+             else {
+                 errorMsg = errorDescription;
+             }
+ 
+             ApplicationInfo app = management.getApplicationInfo( applicationId );
+             applicationName = app.getName();
+ 
+             return handleViewable( "authorize_form", this );
+         }
+         catch ( RedirectionException e ) {
+             throw e;
+         }
+         catch ( Exception e ) {
+             return handleViewable( "error", e );
+         }
+     }
+ 
+ 
+     @DELETE
+     @RequireApplicationAccess
+     @Override
+     public JSONWithPadding executeDelete( @Context UriInfo ui,
+                                           @QueryParam("callback") @DefaultValue("callback") String callback )
+             throws Exception {
+ 
+         logger.debug( "ApplicationResource.executeDelete" );
+ 
+         throw new NotImplementedException( "Application delete is not allowed yet" );
+     }
+ 
+ 
+     String errorMsg = "";
+     String applicationName;
+     String responseType;
+     String clientId;
+     String redirectUri;
+     String scope;
+     String state;
+ 
+ 
+     public String getErrorMsg() {
+         return errorMsg;
+     }
+ 
+ 
+     public String getApplicationName() {
+         return applicationName;
+     }
+ 
+ 
+     public String getResponseType() {
+         return responseType;
+     }
+ 
+ 
+     public String getClientId() {
+         return clientId;
+     }
+ 
+ 
+     public String getRedirectUri() {
+         return redirectUri;
+     }
+ 
+ 
+     public String getScope() {
+         return scope;
+     }
+ 
+ 
+     public String getState() {
+         return state;
+     }
+ 
+ 
+     // todo: find a mechanism to move these methods into the push notifications
+     // project
+     @RequireApplicationAccess
+     @Path("notifiers")
+     public AbstractContextResource getNotifiersResource( @Context UriInfo ui ) throws Exception {
+ 
+         Class cls = Class.forName( "org.apache.usergrid.rest.applications.notifiers.NotifiersResource" );
+ 
+         logger.debug( "NotifiersResource.getNotifiersResource" );
+         addParameter( getServiceParameters(), "notifiers" );
+ 
+         PathSegment ps = getFirstPathSegment( "notifiers" );
+         if ( ps != null ) {
+             addMatrixParams( getServiceParameters(), ui, ps );
+         }
+ 
+         return getSubResource( cls );
+     }
+ 
+ 
+     @RequireApplicationAccess
+     @Path("notifier")
+     public AbstractContextResource getNotifierResource( @Context UriInfo ui ) throws Exception {
+         return getNotifiersResource( ui );
+     }
+ 
+ 
+     private String buildRedirectUriWithAuthCode( String redirect_uri, String state, String authorizationCode )
+             throws UnsupportedEncodingException {
+         if ( !redirect_uri.contains( "?" ) ) {
+             redirect_uri += "?";
+         }
+         else {
+             redirect_uri += "&";
+         }
+         redirect_uri += "code=" + authorizationCode;
+ 
+         if ( isNotBlank( state ) ) {
+             redirect_uri += "&state=" + URLEncoder.encode( state, "UTF-8" );
+         }
+ 
+         return redirect_uri;
+     }
+ 
+ 
+     //mAX /APM integration
+     public static final String APIGEE_MOBILE_APM_CONFIG_JSON_KEY = "apigeeMobileConfig";
+ 
+ 
+     @GET
+     @Path("apm/apigeeMobileConfig")
+     public JSONWithPadding getAPMConfig( @Context UriInfo ui,
+                                          @QueryParam("callback") @DefaultValue("callback") String callback )
+             throws Exception {
+         EntityManager em = ( EntityManager ) emf.getEntityManager( applicationId );
+         Object value = em.getProperty( new SimpleEntityRef( Application.ENTITY_TYPE, applicationId ),
+                 APIGEE_MOBILE_APM_CONFIG_JSON_KEY );
+         //If there is no apm configuration then try to create apm config on the fly
+         if ( value == null ) {
+             value = management.registerAppWithAPM( management.getOrganizationForApplication( applicationId ),
+                     management.getApplicationInfo( applicationId ) );
+         }
+         return new JSONWithPadding( value, callback );
+     }
+ }

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
----------------------------------------------------------------------
diff --cc stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
index 0000000,677b384..0dae405
mode 000000,100644..100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/TomcatResource.java
@@@ -1,0 -1,74 +1,69 @@@
+ package org.apache.usergrid.rest;
+ 
+ 
+ import java.io.File;
+ 
+ import org.junit.rules.ExternalResource;
+ import org.apache.usergrid.cassandra.AvailablePortFinder;
+ 
+ import org.apache.catalina.startup.Tomcat;
+ import org.apache.commons.lang.math.RandomUtils;
+ 
+ import com.google.common.io.Files;
+ 
+ 
+ /** @author tnine */
+ public class TomcatResource extends ExternalResource {
+ 
++    public static final TomcatResource instance = new TomcatResource();
+     private static Object mutex = new Object();
 -
+     private static final String CONTEXT = "/";
 -
++    private String webAppsPath;
+     private int port;
 -
 -
 -
 -
+     private Tomcat tomcat;
+ 
+     protected TomcatResource(){
 -
 -
+     }
+ 
+     @Override
+     protected void before() throws Throwable {
+         if ( tomcat != null ) {
+             return;
+         }
+ 
+         synchronized ( mutex ) {
+             //second into mutex
+             if ( tomcat != null ) {
+                 return;
+             }
+ 
+             File dataDir = Files.createTempDir();
+             dataDir.deleteOnExit();
+ 
+             port = AvailablePortFinder.getNextAvailable( 9998 + RandomUtils.nextInt(10)  );
+ 
+             tomcat = new Tomcat();
+             tomcat.setBaseDir( dataDir.getAbsolutePath() );
+             tomcat.setPort( port );
 -            tomcat.addWebapp( CONTEXT, new File( "src/main/webapp" ).getAbsolutePath() );
 -
 -
++            tomcat.addWebapp( CONTEXT, new File( getWebAppsPath() ).getAbsolutePath() );
+             tomcat.start();
+         }
+     }
+ 
+ 
+     /**
+      * Get the port tomcat runs on
+      * @return
+      */
+     public int getPort(){
+         return port;
+     }
+ 
++    public String getWebAppsPath() {
++        return webAppsPath;
++    }
+ 
 -    public static final TomcatResource instance = new TomcatResource();
 -
 -
++    public void setWebAppsPath(String webAppsPath) {
++        this.webAppsPath = webAppsPath;
++    }
+ }

http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/fb5f8d6c/stack/rest/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --cc stack/rest/src/test/resources/log4j.properties
index 34e591b,3a9f9bb..27a8de9
--- a/stack/rest/src/test/resources/log4j.properties
+++ b/stack/rest/src/test/resources/log4j.properties
@@@ -39,4 -39,4 +39,4 @@@ log4j.logger.org.apache.usergrid.rest.s
  log4j.logger.me.prettyprint.hector.api.beans.AbstractComposite=ERROR, stdout
  
  
- log4j.logger.org.usergrid.rest.management=DEBUG
 -#log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG, stdout
++log4j.logger.org.usergrid.rest.management=DEBUG


Mime
View raw message