From commits-return-2148-apmail-usergrid-commits-archive=usergrid.apache.org@usergrid.incubator.apache.org Tue Feb 25 06:22:06 2014 Return-Path: X-Original-To: apmail-usergrid-commits-archive@minotaur.apache.org Delivered-To: apmail-usergrid-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 066A410A44 for ; Tue, 25 Feb 2014 06:22:06 +0000 (UTC) Received: (qmail 20845 invoked by uid 500); 25 Feb 2014 06:22:05 -0000 Delivered-To: apmail-usergrid-commits-archive@usergrid.apache.org Received: (qmail 20802 invoked by uid 500); 25 Feb 2014 06:22:05 -0000 Mailing-List: contact commits-help@usergrid.incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@usergrid.incubator.apache.org Delivered-To: mailing list commits@usergrid.incubator.apache.org Received: (qmail 17618 invoked by uid 99); 25 Feb 2014 06:21:22 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 25 Feb 2014 06:21:22 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id E72A09258F1; Tue, 25 Feb 2014 06:21:21 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: snoopdave@apache.org To: commits@usergrid.apache.org Date: Tue, 25 Feb 2014 06:22:00 -0000 Message-Id: In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: =?utf-8?q?=5B46/50=5D_=5Babbrv=5D_Resolved_conflicts_as_well=2C_th?= =?utf-8?q?is_caused_creation_of_files_else_where=2C_so_they_now_appear_as_i?= =?utf-8?q?f_they=E2=80=99ve_been_created_as_new=2E_Removed_extraneous_files?= =?utf-8?q?_related_to_export=2E_Merge_remote-tracking_branch_=27origin/mast?= =?utf-8?q?er=27_into_Export=5FPersistance=5FI?= http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/22a17dc8/stack/rest/src/main/java/org/usergrid/rest/management/organizations/applications/ApplicationResource.java ---------------------------------------------------------------------- diff --cc stack/rest/src/main/java/org/usergrid/rest/management/organizations/applications/ApplicationResource.java index 9f6a6c8,0000000..5a29500 mode 100644,000000..100644 --- a/stack/rest/src/main/java/org/usergrid/rest/management/organizations/applications/ApplicationResource.java +++ b/stack/rest/src/main/java/org/usergrid/rest/management/organizations/applications/ApplicationResource.java @@@ -1,275 -1,0 +1,277 @@@ +/******************************************************************************* + * 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.usergrid.rest.management.organizations.applications; + + +import java.util.HashMap; +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.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.usergrid.management.ApplicationInfo; +import org.usergrid.management.ExportInfo; +import org.usergrid.management.OrganizationInfo; +import org.usergrid.management.export.ExportService; +import org.usergrid.persistence.entities.Export; +import org.usergrid.rest.AbstractContextResource; +import org.usergrid.rest.ApiResponse; +import org.usergrid.rest.applications.ServiceResource; +import org.usergrid.rest.security.annotations.RequireOrganizationAccess; +import org.usergrid.rest.utils.JSONPUtils; +import org.usergrid.security.oauth.ClientCredentialsInfo; +import org.usergrid.security.providers.SignInAsProvider; +import org.usergrid.security.providers.SignInProviderFactory; +import org.usergrid.services.ServiceManager; + +import org.apache.amber.oauth2.common.exception.OAuthSystemException; +import org.apache.amber.oauth2.common.message.OAuthResponse; +import org.apache.commons.lang.StringUtils; + ++import org.apache.usergrid.rest.security.annotations.RequireOrganizationAccess; ++ +import com.google.common.base.Preconditions; +import com.sun.jersey.api.json.JSONWithPadding; + +import static javax.servlet.http.HttpServletResponse.SC_ACCEPTED; +import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static javax.servlet.http.HttpServletResponse.SC_OK; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + + +@Component("org.usergrid.rest.management.organizations.applications.ApplicationResource") +@Scope("prototype") +@Produces({ + MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript", + "application/ecmascript", "text/jscript" +}) +public class ApplicationResource extends AbstractContextResource { + + @Autowired + protected ExportService exportService; + OrganizationInfo organization; + UUID applicationId; + ApplicationInfo application; + + @Autowired + private SignInProviderFactory signInProviderFactory; + + + public ApplicationResource() { + } + + + public ApplicationResource init( OrganizationInfo organization, UUID applicationId ) { + this.organization = organization; + this.applicationId = applicationId; + return this; + } + + + public ApplicationResource init( OrganizationInfo organization, ApplicationInfo application ) { + this.organization = organization; + applicationId = application.getId(); + this.application = application; + return this; + } + + + @RequireOrganizationAccess + @DELETE + public JSONWithPadding deleteApplicationFromOrganizationByApplicationId( @Context UriInfo ui, + @QueryParam("callback") + @DefaultValue("callback") String callback ) + throws Exception { + + ApiResponse response = createApiResponse(); + response.setAction( "delete application from organization" ); + + management.deleteOrganizationApplication( organization.getUuid(), applicationId ); + + return new JSONWithPadding( response, callback ); + } + + + @RequireOrganizationAccess + @GET + public JSONWithPadding getApplication( @Context UriInfo ui, + @QueryParam("callback") @DefaultValue("callback") String callback ) + throws Exception { + + ApiResponse response = createApiResponse(); + ServiceManager sm = smf.getServiceManager( applicationId ); + response.setAction( "get" ); + response.setApplication( sm.getApplication() ); + response.setParams( ui.getQueryParameters() ); + response.setResults( management.getApplicationMetadata( applicationId ) ); + return new JSONWithPadding( response, callback ); + } + + + @RequireOrganizationAccess + @GET + @Path("credentials") + public JSONWithPadding getCredentials( @Context UriInfo ui, + @QueryParam("callback") @DefaultValue("callback") String callback ) + throws Exception { + + ApiResponse response = createApiResponse(); + response.setAction( "get application client credentials" ); + + ClientCredentialsInfo credentials = + new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), + management.getClientSecretForApplication( applicationId ) ); + + response.setCredentials( credentials ); + return new JSONWithPadding( response, callback ); + } + + + @RequireOrganizationAccess + @POST + @Path("credentials") + public JSONWithPadding generateCredentials( @Context UriInfo ui, + @QueryParam("callback") @DefaultValue("callback") String callback ) + throws Exception { + + ApiResponse response = createApiResponse(); + response.setAction( "generate application client credentials" ); + + ClientCredentialsInfo credentials = + new ClientCredentialsInfo( management.getClientIdForApplication( applicationId ), + management.newClientSecretForApplication( applicationId ) ); + + response.setCredentials( credentials ); + return new JSONWithPadding( response, callback ); + } + + + @POST + @Path("sia-provider") + @Consumes(APPLICATION_JSON) + @RequireOrganizationAccess + public JSONWithPadding configureProvider( @Context UriInfo ui, @QueryParam("provider_key") String siaProvider, + Map json, + @QueryParam("callback") @DefaultValue("") String callback ) + throws Exception { + + ApiResponse response = createApiResponse(); + response.setAction( "post signin provider configuration" ); + + Preconditions.checkArgument( siaProvider != null, "Sign in provider required" ); + + SignInAsProvider signInAsProvider = null; + if ( StringUtils.equalsIgnoreCase( siaProvider, "facebook" ) ) { + signInAsProvider = + signInProviderFactory.facebook( smf.getServiceManager( applicationId ).getApplication() ); + } + else if ( StringUtils.equalsIgnoreCase( siaProvider, "pingident" ) ) { + signInAsProvider = + signInProviderFactory.pingident( smf.getServiceManager( applicationId ).getApplication() ); + } + else if ( StringUtils.equalsIgnoreCase( siaProvider, "foursquare" ) ) { + signInAsProvider = + signInProviderFactory.foursquare( smf.getServiceManager( applicationId ).getApplication() ); + } + + Preconditions + .checkArgument( signInAsProvider != null, "No signin provider found by that name: " + siaProvider ); + + signInAsProvider.saveToConfiguration( json ); + + return new JSONWithPadding( response, callback ); + } + //add export here + @POST + @Path("export") + @Consumes(APPLICATION_JSON) + @RequireOrganizationAccess + public Response exportPostJson (@Context UriInfo ui, + Map json, + @QueryParam( "callback" ) @DefaultValue( "" ) String callback) + throws OAuthSystemException { + + + OAuthResponse response = null; + UUID jobUUID = null; + Map uuidRet = new HashMap( ); + + try { + //parse the json into some useful object (the config params) + ExportInfo objEx = new ExportInfo(json); + objEx.setApplicationId( applicationId ); + jobUUID = exportService.schedule(objEx); + uuidRet.put( "jobUUID", jobUUID.toString() ); + + } + catch (NullPointerException e) { + OAuthResponse errorMsg = OAuthResponse.errorResponse( SC_BAD_REQUEST ) + .setErrorDescription( "Job Not Created" ) + .buildJSONMessage(); + + return Response.status( errorMsg.getResponseStatus() ).type( JSONPUtils.jsonMediaType( callback ) ) + .entity( ServiceResource.wrapWithCallback( errorMsg.getBody(), callback ) ).build(); + } + catch (Exception e) { + //TODO:throw descriptive error message and or include on in the response + //TODO:fix below, it doesn't work if there is an exception. Make it look like the OauthResponse. + return Response.status( SC_INTERNAL_SERVER_ERROR ).build(); + } + + return Response.status(SC_ACCEPTED).entity(uuidRet).build(); + + //Response.status( response.getResponseStatus() ).type( jsonMediaType( callback ) ) + // .entity( wrapWithCallback( "", callback ) ).build(); + } + + @GET + @Path( "export/{jobUUID: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}" ) + public Response exportGetJson(@Context UriInfo ui,@PathParam( "jobUUID" ) UUID jobUUIDStr, + @QueryParam( "callback" ) @DefaultValue( "" ) String callback ) throws Exception { + + Export entity; + try { + entity = smf.getServiceManager( applicationId ).getEntityManager().get(jobUUIDStr, Export.class ); + }catch(Exception e) { + return Response.status( SC_BAD_REQUEST ).build(); + } + //validate this user owns it + + if (entity == null) { + return Response.status(SC_BAD_REQUEST).build(); + } + + return Response.status(SC_OK).entity(entity.getState()).build(); + //return Response.status(SC_OK).entity(state).build(); + } + +} http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/22a17dc8/stack/services/src/main/resources/usergrid-services-context.xml ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/22a17dc8/stack/services/src/test/java/org/usergrid/management/cassandra/ManagementServiceIT.java ---------------------------------------------------------------------- diff --cc stack/services/src/test/java/org/usergrid/management/cassandra/ManagementServiceIT.java index a89aae6,0000000..41f6259 mode 100644,000000..100644 --- a/stack/services/src/test/java/org/usergrid/management/cassandra/ManagementServiceIT.java +++ b/stack/services/src/test/java/org/usergrid/management/cassandra/ManagementServiceIT.java @@@ -1,1150 -1,0 +1,1152 @@@ +package org.usergrid.management.cassandra; + + +import java.io.File; +import java.io.FileReader; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.usergrid.ServiceITSetup; +import org.usergrid.ServiceITSetupImpl; +import org.usergrid.ServiceITSuite; +import org.usergrid.batch.JobExecution; +import org.usergrid.cassandra.CassandraResource; +import org.usergrid.cassandra.ClearShiroSubject; +import org.usergrid.cassandra.Concurrent; +import org.usergrid.count.SimpleBatcher; +import org.usergrid.management.ExportInfo; +import org.usergrid.management.OrganizationInfo; +import org.usergrid.management.UserInfo; +import org.usergrid.management.export.ExportJob; +import org.usergrid.management.export.ExportService; +import org.usergrid.management.export.S3Export; +import org.usergrid.management.export.S3ExportImpl; +import org.usergrid.persistence.CredentialsInfo; +import org.usergrid.persistence.Entity; +import org.usergrid.persistence.EntityManager; +import org.usergrid.persistence.EntityManagerFactory; +import org.usergrid.persistence.entities.Export; +import org.usergrid.persistence.entities.JobData; +import org.usergrid.persistence.entities.User; +import org.usergrid.security.AuthPrincipalType; +import org.usergrid.security.crypto.command.Md5HashCommand; +import org.usergrid.security.crypto.command.Sha1HashCommand; +import org.usergrid.security.tokens.TokenCategory; +import org.usergrid.security.tokens.exceptions.InvalidTokenException; +import org.usergrid.utils.JsonUtils; +import org.usergrid.utils.UUIDUtils; + ++import org.apache.usergrid.management.cassandra.MockS3ExportImpl; ++ +import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString; +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.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.usergrid.persistence.Schema.DICTIONARY_CREDENTIALS; +import static org.usergrid.persistence.cassandra.CassandraService.MANAGEMENT_APPLICATION_ID; + +/** @author zznate */ +@Concurrent() +public class ManagementServiceIT { + private static final Logger LOG = LoggerFactory.getLogger( ManagementServiceIT.class ); + + private static CassandraResource cassandraResource = ServiceITSuite.cassandraResource; + + // app-level data generated only once + private static UserInfo adminUser; + private static OrganizationInfo organization; + private static UUID applicationId; + + @Rule + public ClearShiroSubject clearShiroSubject = new ClearShiroSubject(); + + @ClassRule + public static final ServiceITSetup setup = new ServiceITSetupImpl( cassandraResource ); + + + @BeforeClass + public static void setup() throws Exception { + LOG.info( "in setup" ); + adminUser = setup.getMgmtSvc().createAdminUser( "edanuff", "Ed Anuff", "ed@anuff.com", "test", false, false ); + organization = setup.getMgmtSvc().createOrganization( "ed-organization", adminUser, true ); + applicationId = setup.getMgmtSvc().createApplication( organization.getUuid(), "ed-application" ).getId(); + } + + + @Test + public void testGetTokenForPrincipalAdmin() throws Exception { + String token = ( ( ManagementServiceImpl ) setup.getMgmtSvc() ) + .getTokenForPrincipal( TokenCategory.ACCESS, null, MANAGEMENT_APPLICATION_ID, + AuthPrincipalType.ADMIN_USER, adminUser.getUuid(), 0 ); + // ^ same as: + // managementService.getAccessTokenForAdminUser(user.getUuid()); + assertNotNull( token ); + token = ( ( ManagementServiceImpl ) setup.getMgmtSvc() ) + .getTokenForPrincipal( TokenCategory.ACCESS, null, MANAGEMENT_APPLICATION_ID, + AuthPrincipalType.APPLICATION_USER, adminUser.getUuid(), 0 ); + // This works because ManagementService#getSecret takes the same code + // path + // on an OR for APP._USER as for ADMIN_USER + // is ok technically as ADMIN_USER is a APP_USER to the admin app, but + // should still + // be stricter checking + assertNotNull( token ); + // managementService.getTokenForPrincipal(appUuid, authPrincipal, pUuid, + // salt, true); + } + + + @Test + public void testGetTokenForPrincipalUser() throws Exception { + // create a user + Map properties = new LinkedHashMap(); + properties.put( "username", "edanuff" ); + properties.put( "email", "ed@anuff.com" ); + + Entity user = setup.getEmf().getEntityManager( applicationId ).create( "user", properties ); + + assertNotNull( user ); + String token = ( ( ManagementServiceImpl ) setup.getMgmtSvc() ) + .getTokenForPrincipal( TokenCategory.ACCESS, null, MANAGEMENT_APPLICATION_ID, + AuthPrincipalType.APPLICATION_USER, user.getUuid(), 0 ); + assertNotNull( token ); + } + + + @Test + public void testCountAdminUserAction() throws Exception { + SimpleBatcher batcher = cassandraResource.getBean( SimpleBatcher.class ); + + batcher.setBlockingSubmit( true ); + batcher.setBatchSize( 1 ); + + setup.getMgmtSvc().countAdminUserAction( adminUser, "login" ); + + EntityManager em = setup.getEmf().getEntityManager( MANAGEMENT_APPLICATION_ID ); + + Map counts = em.getApplicationCounters(); + LOG.info( JsonUtils.mapToJsonString( counts ) ); + LOG.info( JsonUtils.mapToJsonString( em.getCounterNames() ) ); + assertNotNull( counts.get( "admin_logins" ) ); + assertEquals( 1, counts.get( "admin_logins" ).intValue() ); + } + + + @Test + public void deactivateUser() throws Exception { + + UUID uuid = UUIDUtils.newTimeUUID(); + Map properties = new LinkedHashMap(); + properties.put( "username", "test" + uuid ); + properties.put( "email", String.format( "test%s@anuff.com", uuid ) ); + + EntityManager em = setup.getEmf().getEntityManager( applicationId ); + + Entity entity = em.create( "user", properties ); + + assertNotNull( entity ); + + User user = em.get( entity.getUuid(), User.class ); + + assertFalse( user.activated() ); + assertNull( user.getDeactivated() ); + + setup.getMgmtSvc().activateAppUser( applicationId, user.getUuid() ); + + user = em.get( entity.getUuid(), User.class ); + + assertTrue( user.activated() ); + assertNull( user.getDeactivated() ); + + // get a couple of tokens. These shouldn't work after we deactive the user + String token1 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, user.getUuid(), 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, user.getUuid(), 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + long startTime = System.currentTimeMillis(); + + setup.getMgmtSvc().deactivateUser( applicationId, user.getUuid() ); + + long endTime = System.currentTimeMillis(); + + user = em.get( entity.getUuid(), User.class ); + + assertFalse( user.activated() ); + assertNotNull( user.getDeactivated() ); + + assertTrue( startTime <= user.getDeactivated() && user.getDeactivated() <= endTime ); + + boolean invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + + invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + } + + + @Test + public void disableAdminUser() throws Exception { + + UUID uuid = UUIDUtils.newTimeUUID(); + Map properties = new LinkedHashMap(); + properties.put( "username", "test" + uuid ); + properties.put( "email", String.format( "test%s@anuff.com", uuid ) ); + + EntityManager em = setup.getEmf().getEntityManager( MANAGEMENT_APPLICATION_ID ); + + Entity entity = em.create( "user", properties ); + + assertNotNull( entity ); + + User user = em.get( entity.getUuid(), User.class ); + + assertFalse( user.activated() ); + assertNull( user.getDeactivated() ); + + setup.getMgmtSvc().activateAdminUser( user.getUuid() ); + + user = em.get( entity.getUuid(), User.class ); + + assertTrue( user.activated() ); + assertNull( user.getDeactivated() ); + + // get a couple of tokens. These shouldn't work after we deactive the user + String token1 = setup.getMgmtSvc().getAccessTokenForAdminUser( user.getUuid(), 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAdminUser( user.getUuid(), 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + setup.getMgmtSvc().disableAdminUser( user.getUuid() ); + + user = em.get( entity.getUuid(), User.class ); + + assertTrue( user.disabled() ); + + boolean invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + + invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + } + + + @Test + public void userTokensRevoke() throws Exception { + UUID userId = UUIDUtils.newTimeUUID(); + + String token1 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, userId, 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, userId, 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + setup.getMgmtSvc().revokeAccessTokensForAppUser( applicationId, userId ); + + boolean invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + + invalidTokenExcpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenExcpetion = true; + } + + assertTrue( invalidTokenExcpetion ); + } + + + @Test + public void userTokenRevoke() throws Exception { + EntityManager em = setup.getEmf().getEntityManager( applicationId ); + + Map properties = new LinkedHashMap(); + properties.put( "username", "realbeast" ); + properties.put( "email", "sungju@softwaregeeks.org" ); + + Entity user = em.create( "user", properties ); + assertNotNull( user ); + + UUID userId = user.getUuid(); + + String token1 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, userId, 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAppUser( applicationId, userId, 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + setup.getMgmtSvc().revokeAccessTokenForAppUser( token1 ); + + boolean invalidToken1Excpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidToken1Excpetion = true; + } + + assertTrue( invalidToken1Excpetion ); + + boolean invalidToken2Excpetion = true; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidToken2Excpetion = false; + } + + assertTrue( invalidToken2Excpetion ); + } + + + @Test + public void adminTokensRevoke() throws Exception { + UUID userId = UUIDUtils.newTimeUUID(); + + String token1 = setup.getMgmtSvc().getAccessTokenForAdminUser( userId, 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAdminUser( userId, 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + setup.getMgmtSvc().revokeAccessTokensForAdminUser( userId ); + + boolean invalidTokenException = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenException = true; + } + + assertTrue( invalidTokenException ); + + invalidTokenException = false; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidTokenException = true; + } + + assertTrue( invalidTokenException ); + } + + + @Test + public void adminTokenRevoke() throws Exception { + UUID userId = adminUser.getUuid(); + + String token1 = setup.getMgmtSvc().getAccessTokenForAdminUser( userId, 0 ); + String token2 = setup.getMgmtSvc().getAccessTokenForAdminUser( userId, 0 ); + + assertNotNull( setup.getTokenSvc().getTokenInfo( token1 ) ); + assertNotNull( setup.getTokenSvc().getTokenInfo( token2 ) ); + + setup.getMgmtSvc().revokeAccessTokenForAdminUser( userId, token1 ); + + boolean invalidToken1Excpetion = false; + + try { + setup.getTokenSvc().getTokenInfo( token1 ); + } + catch ( InvalidTokenException ite ) { + invalidToken1Excpetion = true; + } + + assertTrue( invalidToken1Excpetion ); + + boolean invalidToken2Excpetion = true; + + try { + setup.getTokenSvc().getTokenInfo( token2 ); + } + catch ( InvalidTokenException ite ) { + invalidToken2Excpetion = false; + } + + assertTrue( invalidToken2Excpetion ); + } + + + @Test + public void superUserGetOrganizationsPage() throws Exception { + int beforeSize = setup.getMgmtSvc().getOrganizations().size() - 1; + // create 15 orgs + for ( int x = 0; x < 15; x++ ) { + setup.getMgmtSvc().createOrganization( "super-user-org-" + x, adminUser, true ); + } + // should be 17 total + assertEquals( 16 + beforeSize, setup.getMgmtSvc().getOrganizations().size() ); + List orgs = setup.getMgmtSvc().getOrganizations( null, 10 ); + assertEquals( 10, orgs.size() ); + UUID val = orgs.get( 9 ).getUuid(); + orgs = setup.getMgmtSvc().getOrganizations( val, 10 ); + assertEquals( 7 + beforeSize, orgs.size() ); + assertEquals( val, orgs.get( 0 ).getUuid() ); + } + + + @Test + public void authenticateAdmin() throws Exception { + + String username = "tnine"; + String password = "test"; + + UserInfo adminUser = setup.getMgmtSvc() + .createAdminUser( username, "Todd Nine", UUID.randomUUID() + "@apigee.com", password, + false, false ); + + UserInfo authedUser = setup.getMgmtSvc().verifyAdminUserPasswordCredentials( username, password ); + + assertEquals( adminUser.getUuid(), authedUser.getUuid() ); + + authedUser = setup.getMgmtSvc().verifyAdminUserPasswordCredentials( adminUser.getEmail(), password ); + + assertEquals( adminUser.getUuid(), authedUser.getUuid() ); + + authedUser = setup.getMgmtSvc().verifyAdminUserPasswordCredentials( adminUser.getUuid().toString(), password ); + + assertEquals( adminUser.getUuid(), authedUser.getUuid() ); + } + + + /** Test we can change the password if it's hashed with sha1 */ + @Test + public void testAdminPasswordChangeShaType() throws Exception { + String username = "testAdminPasswordChangeShaType"; + String password = "test"; + + + User user = new User(); + user.setActivated( true ); + user.setUsername( username ); + + EntityManager em = setup.getEmf().getEntityManager( MANAGEMENT_APPLICATION_ID ); + + User storedUser = em.create( user ); + + + UUID userId = storedUser.getUuid(); + + //set the password in the sha1 format + CredentialsInfo info = new CredentialsInfo(); + info.setRecoverable( false ); + info.setEncrypted( true ); + + + Sha1HashCommand command = new Sha1HashCommand(); + byte[] hashed = command.hash( password.getBytes( "UTF-8" ), info, userId, MANAGEMENT_APPLICATION_ID ); + + info.setSecret( encodeBase64URLSafeString( hashed ) ); + info.setCipher( command.getName() ); + + + em.addToDictionary( storedUser, DICTIONARY_CREDENTIALS, "password", info ); + + + //verify authorization works + User authedUser = + setup.getMgmtSvc().verifyAppUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, username, password ); + + assertEquals( userId, authedUser.getUuid() ); + + //test we can change the password + String newPassword = "test2"; + + setup.getMgmtSvc().setAppUserPassword( MANAGEMENT_APPLICATION_ID, userId, password, newPassword ); + + //verify authorization works + authedUser = + setup.getMgmtSvc().verifyAppUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, username, newPassword ); + + assertEquals( userId, authedUser.getUuid() ); + } + + + /** Test we can change the password if it's hashed with md5 then sha1 */ + @Test + public void testAdminPasswordChangeMd5ShaType() throws Exception { + String username = "testAdminPasswordChangeMd5ShaType"; + String password = "test"; + + + User user = new User(); + user.setActivated( true ); + user.setUsername( username ); + + EntityManager em = setup.getEmf().getEntityManager( MANAGEMENT_APPLICATION_ID ); + + User storedUser = em.create( user ); + + + UUID userId = storedUser.getUuid(); + + //set the password in the sha1 format + + //set the password in the sha1 format + CredentialsInfo info = new CredentialsInfo(); + info.setRecoverable( false ); + info.setEncrypted( true ); + + + Md5HashCommand md5 = new Md5HashCommand(); + + Sha1HashCommand sha1 = new Sha1HashCommand(); + + byte[] hashed = md5.hash( password.getBytes( "UTF-8" ), info, userId, MANAGEMENT_APPLICATION_ID ); + hashed = sha1.hash( hashed, info, userId, MANAGEMENT_APPLICATION_ID ); + + info.setSecret( encodeBase64URLSafeString( hashed ) ); + //set the final cipher to sha1 + info.setCipher( sha1.getName() ); + //set the next hash type to md5 + info.setHashType( md5.getName() ); + + + em.addToDictionary( storedUser, DICTIONARY_CREDENTIALS, "password", info ); + + + //verify authorization works + User authedUser = + setup.getMgmtSvc().verifyAppUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, username, password ); + + assertEquals( userId, authedUser.getUuid() ); + + //test we can change the password + String newPassword = "test2"; + + setup.getMgmtSvc().setAppUserPassword( MANAGEMENT_APPLICATION_ID, userId, password, newPassword ); + + //verify authorization works + authedUser = + setup.getMgmtSvc().verifyAppUserPasswordCredentials( MANAGEMENT_APPLICATION_ID, username, newPassword ); + + assertEquals( userId, authedUser.getUuid() ); + } + + + @Test + public void authenticateUser() throws Exception { + + String username = "tnine"; + String password = "test"; + String orgName = "autneticateUser"; + String appName = "authenticateUser"; + + UUID appId = setup.getEmf().createApplication( orgName, appName ); + + User user = new User(); + user.setActivated( true ); + user.setUsername( username ); + + EntityManager em = setup.getEmf().getEntityManager( appId ); + + User storedUser = em.create( user ); + + + UUID userId = storedUser.getUuid(); + + //set the password + setup.getMgmtSvc().setAppUserPassword( appId, userId, password ); + + //verify authorization works + User authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, password ); + + assertEquals( userId, authedUser.getUuid() ); + + //test we can change the password + String newPassword = "test2"; + + setup.getMgmtSvc().setAppUserPassword( appId, userId, password, newPassword ); + + //verify authorization works + authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, newPassword ); + } + + + /** Test we can change the password if it's hashed with sha1 */ + @Test + public void testAppUserPasswordChangeShaType() throws Exception { + String username = "tnine"; + String password = "test"; + String orgName = "testAppUserPasswordChangeShaType"; + String appName = "testAppUserPasswordChangeShaType"; + + UUID appId = setup.getEmf().createApplication( orgName, appName ); + + User user = new User(); + user.setActivated( true ); + user.setUsername( username ); + + EntityManager em = setup.getEmf().getEntityManager( appId ); + + User storedUser = em.create( user ); + + + UUID userId = storedUser.getUuid(); + + //set the password in the sha1 format + CredentialsInfo info = new CredentialsInfo(); + info.setRecoverable( false ); + info.setEncrypted( true ); + + + Sha1HashCommand command = new Sha1HashCommand(); + byte[] hashed = command.hash( password.getBytes( "UTF-8" ), info, userId, appId ); + + info.setSecret( encodeBase64URLSafeString( hashed ) ); + info.setCipher( command.getName() ); + + + em.addToDictionary( storedUser, DICTIONARY_CREDENTIALS, "password", info ); + + + //verify authorization works + User authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, password ); + + assertEquals( userId, authedUser.getUuid() ); + + //test we can change the password + String newPassword = "test2"; + + setup.getMgmtSvc().setAppUserPassword( appId, userId, password, newPassword ); + + //verify authorization works + authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, newPassword ); + + assertEquals( userId, authedUser.getUuid() ); + } + + + /** Test we can change the password if it's hashed with md5 then sha1 */ + @Test + public void testAppUserPasswordChangeMd5ShaType() throws Exception { + String username = "tnine"; + String password = "test"; + String orgName = "testAppUserPasswordChangeMd5ShaType"; + String appName = "testAppUserPasswordChangeMd5ShaType"; + + UUID appId = setup.getEmf().createApplication( orgName, appName ); + + User user = new User(); + user.setActivated( true ); + user.setUsername( username ); + + EntityManager em = setup.getEmf().getEntityManager( appId ); + + User storedUser = em.create( user ); + + + UUID userId = storedUser.getUuid(); + + //set the password in the sha1 format + CredentialsInfo info = new CredentialsInfo(); + info.setRecoverable( false ); + info.setEncrypted( true ); + + + Md5HashCommand md5 = new Md5HashCommand(); + + Sha1HashCommand sha1 = new Sha1HashCommand(); + + byte[] hashed = md5.hash( password.getBytes( "UTF-8" ), info, userId, appId ); + hashed = sha1.hash( hashed, info, userId, appId ); + + info.setSecret( encodeBase64URLSafeString( hashed ) ); + //set the final cipher to sha1 + info.setCipher( sha1.getName() ); + //set the next hash type to md5 + info.setHashType( md5.getName() ); + + + em.addToDictionary( storedUser, DICTIONARY_CREDENTIALS, "password", info ); + + + //verify authorization works + User authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, password ); + + assertEquals( userId, authedUser.getUuid() ); + + //test we can change the password + String newPassword = "test2"; + + setup.getMgmtSvc().setAppUserPassword( appId, userId, password, newPassword ); + + //verify authorization works + authedUser = setup.getMgmtSvc().verifyAppUserPasswordCredentials( appId, username, newPassword ); + + assertEquals( userId, authedUser.getUuid() ); + } + + //Tests to make sure we can call the job with mock data and it runs. + @Ignore + public void testFileConnections() throws Exception { + + File f = null; + + + try { + f = new File ("test.json"); + f.delete(); + } catch (Exception e) { + //consumed because this checks to see if the file exists. If it doesn't then don't do anything and carry on. + } + + S3Export s3Export = new MockS3ExportImpl(); + ExportService exportService = setup.getExportService(); + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + EntityManager em = setup.getEmf().getEntityManager( applicationId ); + //intialize user object to be posted + Map userProperties = null; + Entity[] entity; + entity = new Entity[10]; + //creates entities + for (int i = 0; i< 10;i++) { + userProperties = new LinkedHashMap(); + userProperties.put( "username", "billybob" + i ); + userProperties.put( "email", "test"+i+"@anuff.com");//String.format( "test%i@anuff.com", i ) ); + + entity[i] = em.create( "user", userProperties ); + + } + //creates connections + em.createConnection( em.getRef( entity[0].getUuid() ),"Vibrations",em.getRef( entity[1].getUuid() ) ); + em.createConnection( em.getRef( entity[1].getUuid() ),"Vibrations",em.getRef( entity[0].getUuid() ) ); + + UUID exportUUID = exportService.schedule( exportInfo ); + exportService.setS3Export( s3Export ); + + //create and initialize jobData returned in JobExecution. + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", exportUUID ); + + JobExecution jobExecution = mock ( JobExecution.class); + when(jobExecution.getJobData()).thenReturn( jobData ); + + exportService.doExport( exportInfo, jobExecution ); + + JSONParser parser = new JSONParser(); + + org.json.simple.JSONArray a = ( org.json.simple.JSONArray ) parser.parse(new FileReader(f)); + //assertEquals(13, a.size() ); + + org.json.simple.JSONObject objEnt = ( org.json.simple.JSONObject) a.get( 0 ); + org.json.simple.JSONObject objConnections = ( org.json.simple.JSONObject) objEnt.get( "connections" ); + + assertNotNull( objConnections ); + + org.json.simple.JSONArray objVibrations = ( org.json.simple.JSONArray ) objConnections.get("Vibrations"); + + assertNotNull( objVibrations ); + + f.delete(); + } + + + @Test + public void testFileValidity() throws Exception { + + File f = null; + + try { + f = new File ("test.json"); + f.delete(); + } catch (Exception e) { + //consumed because this checks to see if the file exists. If it doesn't then don't do anything and carry on. + } + + S3Export s3Export = new MockS3ExportImpl(); + ExportService exportService = setup.getExportService(); + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + UUID exportUUID = exportService.schedule( exportInfo ); + exportService.setS3Export( s3Export ); + + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", exportUUID ); + + JobExecution jobExecution = mock ( JobExecution.class); + when(jobExecution.getJobData()).thenReturn( jobData ); + + exportService.doExport( exportInfo, jobExecution ); + + JSONParser parser = new JSONParser(); + + org.json.simple.JSONArray a = ( org.json.simple.JSONArray ) parser.parse(new FileReader(f)); + + for (int i = 0; i < a.size();i++ ) + { + org.json.simple.JSONObject entity = ( org.json.simple.JSONObject) a.get( i ); + org.json.simple.JSONObject entityData = ( JSONObject ) entity.get( "Metadata" ); + assertNotNull( entityData ); + + } + f.delete(); + } + + @Test + public void testFileExportOneOrg() throws Exception { + + File f = null; + + + try { + f = new File ("test.json"); + f.delete(); + } catch (Exception e) { + //consumed because this checks to see if the file exists. If it doesn't then don't do anything and carry on. + } + setup.getMgmtSvc().createOwnerAndOrganization( "noExport","junkUserName","junkRealName","ugExport@usergrid.com","123456789" ); + + S3Export s3Export = new MockS3ExportImpl(); + ExportService exportService = setup.getExportService(); + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + UUID exportUUID = exportService.schedule( exportInfo ); + exportService.setS3Export( s3Export ); + + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", exportUUID ); + + JobExecution jobExecution = mock ( JobExecution.class); + when(jobExecution.getJobData()).thenReturn( jobData ); + + exportService.doExport( exportInfo, jobExecution ); + + JSONParser parser = new JSONParser(); + + org.json.simple.JSONArray a = ( org.json.simple.JSONArray ) parser.parse(new FileReader(f)); + + //assertEquals( 3 , a.size() ); + for (int i = 0; i < a.size();i++ ) + { + org.json.simple.JSONObject entity = ( org.json.simple.JSONObject) a.get( i ); + org.json.simple.JSONObject entityData = ( JSONObject ) entity.get( "Metadata" ); + String entityName = ( String) entityData.get( "name" ); + // assertNotEquals( "NotEqual","junkRealName",entityName ); + assertFalse( "junkRealName".equals( entityName ) ); + + } + f.delete(); + } + @Test + public void testFileExportOneApp() throws Exception { + + File f = null; + String orgName = "ed-organization"; + String appName = "testAppNotExported"; + + try { + f = new File ("test.json"); + f.delete(); + } catch (Exception e) { + //consumed because this checks to see if the file exists. If it doesn't, don't do anything and carry on. + } + + UUID appId = setup.getEmf().createApplication( orgName, appName ); + + + EntityManager em = setup.getEmf().getEntityManager( appId ); + //intialize user object to be posted + Map userProperties = null; + Entity[] entity; + entity = new Entity[10]; + //creates entities + for (int i = 0; i< 10;i++) { + userProperties = new LinkedHashMap(); + userProperties.put( "username", "billybob" + i ); + userProperties.put( "email", "test"+i+"@anuff.com");//String.format( "test%i@anuff.com", i ) ); + entity[i] = em.create( "user", userProperties ); + } + + S3Export s3Export = new MockS3ExportImpl(); + ExportService exportService = setup.getExportService(); + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + UUID exportUUID = exportService.schedule( exportInfo ); + exportService.setS3Export( s3Export ); + + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", exportUUID ); + + JobExecution jobExecution = mock ( JobExecution.class); + when(jobExecution.getJobData()).thenReturn( jobData ); + + exportService.doExport( exportInfo, jobExecution ); + + JSONParser parser = new JSONParser(); + + org.json.simple.JSONArray a = ( org.json.simple.JSONArray ) parser.parse(new FileReader(f)); + + //assertEquals( 3 , a.size() ); + for (int i = 0; i < a.size();i++ ) + { + org.json.simple.JSONObject data = ( org.json.simple.JSONObject) a.get( i ); + org.json.simple.JSONObject entityData = ( JSONObject ) data.get( "Metadata" ); + String entityName = ( String) entityData.get( "name" ); + assertFalse( "junkRealName".equals( entityName ) ); + //assertNotEquals( "NotEquals","junkRealName",entityName ); + } + f.delete(); + } + + //only handles the DoJob Code , different tests for DoExport + @Test + public void testExportDoJob() throws Exception { + + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); //this needs to be populated with properties of export info + + JobExecution jobExecution = mock ( JobExecution.class); + + when( jobExecution.getJobData() ).thenReturn( jobData ); + + ExportJob job = new ExportJob(); + ExportService eS = mock (ExportService.class); + job.setExportService( eS ); + try { + job.doJob( jobExecution ); + }catch ( Exception e) { + assert( false ); + } + assert(true); + + } + + @Test + public void testExportDoExport() throws Exception { + + EntityManagerFactory emf = setup.getEmf(); + EntityManager em = emf.getEntityManager( applicationId ); + HashMap payload = payloadBuilder(); + ExportService eS = setup.getExportService(); + + JobExecution jobExecution = mock( JobExecution.class); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + UUID entityExportUUID = eS.schedule( exportInfo ); + + + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", entityExportUUID); + + when( jobExecution.getJobData() ).thenReturn( jobData ); + + //Exportem.get(entityExport); + Export exportEntity = ( Export ) em.get(entityExportUUID); + assertNotNull( exportEntity ); + String derp = exportEntity.getState().name(); + assertEquals( "PENDING",exportEntity.getState().name()); + try { + eS.doExport( exportInfo,jobExecution ); + }catch(Exception e) { + throw e; + //assert(false); + } + exportEntity = ( Export ) em.get(entityExportUUID); + assertNotNull( exportEntity ); + assertEquals( "COMPLETED",exportEntity.getState().name() ); + } + + //tests that with empty job data, the export still runs. + @Test + public void testExportEmptyJobData() throws Exception { + + JobData jobData = new JobData(); + + JobExecution jobExecution = mock ( JobExecution.class); + + when( jobExecution.getJobData() ).thenReturn( jobData ); + + ExportJob job = new ExportJob(); + S3Export s3Export = mock( S3Export.class ); + setup.getExportService().setS3Export( s3Export ); + job.setExportService( setup.getExportService() ); + try { + job.doJob( jobExecution ); + }catch ( Exception e) { + assert( false ); + } + assert(true); + } + + @Test + public void testNullJobExecution () { + + JobData jobData = new JobData(); + + JobExecution jobExecution = mock ( JobExecution.class); + + when( jobExecution.getJobData() ).thenReturn( jobData ); + + ExportJob job = new ExportJob(); + S3Export s3Export = mock( S3Export.class ); + setup.getExportService().setS3Export( s3Export ); + job.setExportService( setup.getExportService() ); + try { + job.doJob( jobExecution ); + }catch ( Exception e) { + assert( false ); + } + assert(true); + } + + @Ignore //For this test please input your s3 credentials into payload builder. + public void testIntegration100Entities() throws Exception { + + S3Export s3Export = new S3ExportImpl(); + ExportService exportService = setup.getExportService(); + HashMap payload = payloadBuilder(); + + ExportInfo exportInfo = new ExportInfo(payload); + exportInfo.setApplicationId( applicationId ); + + EntityManager em = setup.getEmf().getEntityManager( applicationId ); + //intialize user object to be posted + Map userProperties = null; + Entity[] entity; + entity = new Entity[100]; + //creates entities + for (int i = 0; i< 100;i++) { + userProperties = new LinkedHashMap(); + userProperties.put( "username", "billybob" + i ); + userProperties.put( "email", "test"+i+"@anuff.com");//String.format( "test%i@anuff.com", i ) ); + + entity[i] = em.create( "user", userProperties ); + + } + + UUID exportUUID = exportService.schedule( exportInfo ); + exportService.setS3Export( s3Export ); + + //create and initialize jobData returned in JobExecution. + JobData jobData = new JobData(); + jobData.setProperty( "jobName", "exportJob" ); + jobData.setProperty( "exportInfo", exportInfo ); + jobData.setProperty( "exportId", exportUUID ); + + JobExecution jobExecution = mock ( JobExecution.class); + when(jobExecution.getJobData()).thenReturn( jobData ); + + exportService.doExport( exportInfo, jobExecution ); + + } + + + /*Creates fake payload for testing purposes.*/ + public HashMap payloadBuilder() { + HashMap payload = new HashMap(); + Map properties = new HashMap(); + Map storage_info = new HashMap(); +// TODO: always put dummy values here and ignore this test. + storage_info.put( "s3_key","insert key here" ); + storage_info.put( "s3_accessId","insert access id here"); + storage_info.put( "bucket_location","insert bucket name here"); + + properties.put( "storage_provider","s3"); + properties.put( "storage_info",storage_info); + + payload.put( "path", "test-organization/test-app"); + payload.put( "properties", properties); + return payload; + } + +}