@Test
  public void mgmtCreateAndGetApplication() throws Exception {

    OrganizationInfo orgInfo = setup.getMgmtSvc().getOrganizationByName("test-organization");
    Map<String, String> data = new HashMap<String, String>();
    data.put("name", "mgmt-org-app");

    // POST /applications
    JsonNode appdata =
        resource()
            .path("/management/orgs/" + orgInfo.getUuid() + "/applications")
            .queryParam("access_token", adminToken())
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .post(JsonNode.class, data);
    logNode(appdata);
    appdata = getEntity(appdata, 0);

    assertEquals("test-organization/mgmt-org-app", appdata.get("name").asText());
    assertEquals(
        "Roles", appdata.get("metadata").get("collections").get("roles").get("title").asText());
    assertEquals(3, appdata.get("metadata").get("collections").get("roles").get("count").asInt());

    // GET /applications/mgmt-org-app
    appdata =
        resource()
            .path("/management/orgs/" + orgInfo.getUuid() + "/applications/mgmt-org-app")
            .queryParam("access_token", adminToken())
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .get(JsonNode.class);
    logNode(appdata);

    assertEquals("test-organization", appdata.get("organization").asText());
    assertEquals("mgmt-org-app", appdata.get("applicationName").asText());
    assertEquals(
        "http://sometestvalue/test-organization/mgmt-org-app", appdata.get("uri").getTextValue());
    appdata = getEntity(appdata, 0);

    assertEquals("test-organization/mgmt-org-app", appdata.get("name").asText());
    assertEquals(
        "Roles", appdata.get("metadata").get("collections").get("roles").get("title").asText());
    assertEquals(3, appdata.get("metadata").get("collections").get("roles").get("count").asInt());
  }
  /** @return Map of Organization UUID -> Name */
  private Map<UUID, String> getOrganizations() throws Exception {

    Map<UUID, String> organizationNames;

    if (orgId == null) {
      organizationNames = managementService.getOrganizations();
    } else {

      OrganizationInfo info = managementService.getOrganizationByUuid(orgId);

      if (info == null) {
        LOG.error("Organization info is null!");
        System.exit(1);
      }

      organizationNames = new HashMap<UUID, String>();
      organizationNames.put(orgId, info.getName());
    }

    return organizationNames;
  }
  @Override
  public ApplicationInfo createSampleFor(OrganizationInfo organizationInfo)
      throws ApplicationCreationException {

    Preconditions.checkArgument(organizationInfo != null, "OrganizationInfo was null");
    Preconditions.checkArgument(organizationInfo.getUuid() != null, "OrganizationInfo had no UUID");
    logger.info("create sample app {} in: {}", sampleAppName, organizationInfo.getName());
    UUID appId = null;
    try {
      appId =
          managementService.createApplication(organizationInfo.getUuid(), sampleAppName).getId();
    } catch (Exception ex) {
      throw new ApplicationCreationException(
          "'"
              + sampleAppName
              + "' could not be created for organization: "
              + organizationInfo.getUuid(),
          ex);
    }
    logger.info("granting permissions for: {} in: {}", sampleAppName, organizationInfo.getName());
    // grant access to all default collections with groups
    EntityManager em = entityManagerFactory.getEntityManager(appId);
    try {
      em.grantRolePermissions("guest", Arrays.asList("get,post,put,delete:/**"));
      em.grantRolePermissions("default", Arrays.asList("get,put,post,delete:/**"));
    } catch (Exception ex) {
      throw new ApplicationCreationException(
          "Could not grant permissions to guest for default collections in '" + sampleAppName + "'",
          ex);
    }
    // re-load the applicationinfo so the correct name is set
    try {
      return managementService.getApplicationInfo(appId);
    } catch (Exception ex) {
      throw new ApplicationCreationException("Could not load new Application.", ex);
    }
  }
  @POST
  @Path("collection/{collection_name}/export")
  @Consumes(APPLICATION_JSON)
  @RequireOrganizationAccess
  public Response exportPostJson(
      @Context UriInfo ui,
      @PathParam("collection_name") String collection_name,
      Map<String, Object> json,
      @QueryParam("callback") @DefaultValue("") String callback)
      throws OAuthSystemException {

    UsergridAwsCredentials uac = new UsergridAwsCredentials();
    UUID jobUUID = null;
    String colExport = collection_name;
    Map<String, String> uuidRet = new HashMap<String, String>();

    Map<String, Object> properties;
    Map<String, Object> storage_info;

    try {
      // checkJsonExportProperties(json);
      if ((properties = (Map<String, Object>) json.get("properties")) == null) {
        throw new NullArgumentException("Could not find 'properties'");
      }
      storage_info = (Map<String, Object>) properties.get("storage_info");
      String storage_provider = (String) properties.get("storage_provider");
      if (storage_provider == null) {
        throw new NullArgumentException("Could not find field 'storage_provider'");
      }
      if (storage_info == null) {
        throw new NullArgumentException("Could not find field 'storage_info'");
      }

      String bucketName = (String) storage_info.get("bucket_location");
      String accessId = (String) storage_info.get("s3_access_id");
      String secretKey = (String) storage_info.get("s3_key");

      if (accessId == null) {
        throw new NullArgumentException("Could not find field 's3_access_id'");
      }
      if (secretKey == null) {
        throw new NullArgumentException("Could not find field 's3_key'");
      }

      if (bucketName == null) {
        throw new NullArgumentException("Could not find field 'bucketName'");
      }

      json.put("organizationId", organization.getUuid());
      json.put("applicationId", applicationId);
      json.put("collectionName", colExport);

      jobUUID = exportService.schedule(json);
      uuidRet.put("Export Entity", jobUUID.toString());
    } catch (NullArgumentException e) {
      return Response.status(SC_BAD_REQUEST)
          .type(JSONPUtils.jsonMediaType(callback))
          .entity(ServiceResource.wrapWithCallback(e.getMessage(), 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.

      OAuthResponse errorMsg =
          OAuthResponse.errorResponse(SC_INTERNAL_SERVER_ERROR)
              .setErrorDescription(e.getMessage())
              .buildJSONMessage();

      return Response.status(errorMsg.getResponseStatus())
          .type(JSONPUtils.jsonMediaType(callback))
          .entity(ServiceResource.wrapWithCallback(errorMsg.getBody(), callback))
          .build();
    }

    return Response.status(SC_ACCEPTED).entity(uuidRet).build();
  }
  /** Test that admins can't view organizations they're not authorized to view. */
  @Test
  public void crossOrgsNotViewable() throws Exception {

    OrganizationOwnerInfo orgInfo =
        setup
            .getMgmtSvc()
            .createOwnerAndOrganization(
                "crossOrgsNotViewable",
                "crossOrgsNotViewable",
                "TestName",
                "*****@*****.**",
                "password");

    // check that the test admin cannot access the new org info

    Status status = null;

    try {
      resource()
          .path(String.format("/management/orgs/%s", orgInfo.getOrganization().getName()))
          .queryParam("access_token", adminAccessToken)
          .accept(MediaType.APPLICATION_JSON)
          .type(MediaType.APPLICATION_JSON_TYPE)
          .get(JsonNode.class);
    } catch (UniformInterfaceException uie) {
      status = uie.getResponse().getClientResponseStatus();
    }

    assertNotNull(status);
    assertEquals(Status.UNAUTHORIZED, status);

    status = null;

    try {
      resource()
          .path(String.format("/management/orgs/%s", orgInfo.getOrganization().getUuid()))
          .queryParam("access_token", adminAccessToken)
          .accept(MediaType.APPLICATION_JSON)
          .type(MediaType.APPLICATION_JSON_TYPE)
          .get(JsonNode.class);
    } catch (UniformInterfaceException uie) {
      status = uie.getResponse().getClientResponseStatus();
    }

    assertNotNull(status);
    assertEquals(Status.UNAUTHORIZED, status);

    // this admin should have access to test org
    status = null;
    try {
      resource()
          .path("/management/orgs/test-organization")
          .queryParam("access_token", adminAccessToken)
          .accept(MediaType.APPLICATION_JSON)
          .type(MediaType.APPLICATION_JSON_TYPE)
          .get(JsonNode.class);
    } catch (UniformInterfaceException uie) {
      status = uie.getResponse().getClientResponseStatus();
    }

    assertNull(status);

    OrganizationInfo org = setup.getMgmtSvc().getOrganizationByName("test-organization");

    status = null;
    try {
      resource()
          .path(String.format("/management/orgs/%s", org.getUuid()))
          .queryParam("access_token", adminAccessToken)
          .accept(MediaType.APPLICATION_JSON)
          .type(MediaType.APPLICATION_JSON_TYPE)
          .get(JsonNode.class);
    } catch (UniformInterfaceException uie) {
      status = uie.getResponse().getClientResponseStatus();
    }

    assertNull(status);
  }