@Test(
      groups = "wso2.esb",
      description =
          "Test to check whether the Content-Type header is preserved when sending "
              + "requests to back end")
  public void testPreserveContentTypeHeader() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("PreserveContentTypeHeaderTest");

    String requestPayload =
        "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' >"
            + "<soapenv:Body>"
            + "</soapenv:Body></soapenv:Envelope> ";

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Soapaction", "urn:mediate");
    headers.put("Content-type", "application/xml");

    HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);

    String wireResponse = wireMonitorServer.getCapturedMessage();
    String[] wireResponseList = wireResponse.split(System.lineSeparator());

    Assert.assertTrue(wireResponse.contains("Content-Type"));
    for (String line : wireResponseList) {
      if (line.contains("Content-Type")) {
        if (line.contains(";")) {
          Assert.fail("Content-Type header was modified - " + line);
        }
      }
    }
    // coming to this line means content type header is in expected state, hence passing the test
    Assert.assertTrue(true);
  }
 @Test(
     groups = {"wso2.am"},
     description = "test  invocation of APi after expire the throttling block time.",
     dependsOnMethods = "testInvokingWithGoldTier")
 public void testInvokingAfterExpireThrottleExpireTime() throws InterruptedException, IOException {
   // wait millisecond to expire the throttling block
   Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME);
   HttpResponse invokeResponse =
       HttpRequestUtil.doGet(
           gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
           requestHeadersGoldTier);
   assertEquals(
       invokeResponse.getResponseCode(),
       HTTP_RESPONSE_CODE_OK,
       "Response code mismatched, "
           + "Invocation fails after wait "
           + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME)
           + "millisecond to expire the throttling block");
   assertTrue(
       invokeResponse.getData().contains(API_RESPONSE_DATA),
       "Response data mismatched. "
           + "Invocation fails after wait "
           + (THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME)
           + "millisecond to expire the throttling block");
 }
 @Test(
     groups = {"wso2.am"},
     description = "Test  invocation of API before change the  api end point URL.")
 public void testAPIInvocationBeforeChangeTheEndPointURL() throws Exception {
   // Create and publish  and subscribe API version 1.0.0
   createPublishAndSubscribeToAPI(
       apiIdentifier,
       apiCreationRequestBean,
       apiPublisherClientUser1,
       apiStoreClientUser1,
       APPLICATION_NAME);
   // get access token
   String accessToken =
       generateApplicationKeys(apiStoreClientUser1, APPLICATION_NAME).getAccessToken();
   // Create requestHeaders
   requestHeaders = new HashMap<String, String>();
   requestHeaders.put("accept", "text/xml");
   requestHeaders.put("Authorization", "Bearer " + accessToken);
   // Invoke  old version
   HttpResponse oldVersionInvokeResponse =
       HttpRequestUtil.doGet(
           getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/" + API1_END_POINT_METHOD,
           requestHeaders);
   assertEquals(
       oldVersionInvokeResponse.getResponseCode(),
       HTTP_RESPONSE_CODE_OK,
       "Response code mismatched when invoke api before change the end point URL");
   assertTrue(
       oldVersionInvokeResponse.getData().contains(API1_RESPONSE_DATA),
       "Response data mismatched when invoke  API  before change the end point URL"
           + " Response Data:"
           + oldVersionInvokeResponse.getData()
           + ". Expected Response Data: "
           + API1_RESPONSE_DATA);
 }
 @Test(
     groups = {"wso2.am"},
     description =
         "Test the invocation of API using new end point URL" + "  after end point URL  change",
     dependsOnMethods = "testEditEndPointURL")
 public void testInvokeAPIAfterChangeAPIEndPointURLWithNewEndPointURL() throws Exception {
   // Invoke  new context
   HttpResponse oldVersionInvokeResponse =
       HttpRequestUtil.doGet(
           getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0), requestHeaders);
   assertEquals(
       oldVersionInvokeResponse.getResponseCode(),
       HTTP_RESPONSE_CODE_OK,
       "Response code mismatched when invoke  API  after change the end point URL");
   assertTrue(
       oldVersionInvokeResponse.getData().contains(API2_RESPONSE_DATA),
       "Response data mismatched when invoke  API  after change the end point URL"
           + " Response Data:"
           + oldVersionInvokeResponse.getData()
           + ". Expected Response Data: "
           + API2_RESPONSE_DATA);
   assertFalse(
       oldVersionInvokeResponse.getData().contains(API1_RESPONSE_DATA),
       "Response data mismatched when invoke  API  after change the end point URL. It contains the"
           + " Old end point URL response data. Response Data:"
           + oldVersionInvokeResponse.getData()
           + ". Expected Response Data: "
           + API2_RESPONSE_DATA);
 }
  @Test(
      groups = {"wso2.am"},
      description = "Sending a Message Via REST to test uri template fix")
  public void testRESTURITemplate() throws Exception {
    // Before apply this patch uri template not recognize localhost:8280/stockquote/test/
    // and localhost:8280/stockquote/test
    // maps to same resource. It will return correct response only if request hits
    // localhost:8280/stockquote/test
    // after fixing issue both will work.

    HttpResponse response = HttpRequestUtil.sendGetRequest(gatewayUrl + "stockquote/test/", null);
    assertEquals(
        response.getResponseCode(), Response.Status.OK.getStatusCode(), "Response code mismatch");
  }
 @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
 @AfterClass(alwaysRun = true)
 public void testDeleteWebApplication() throws Exception {
   webAppAdminClient.deleteWebAppFile(webAppFileName);
   assertTrue(
       WebAppDeploymentUtil.isWebApplicationUnDeployed(backendURL, sessionCookie, webAppName),
       "Web Application unDeployment failed");
   String webAppURLLocal = getWebAppURL(WebAppTypes.WEBAPPS) + "/" + webAppName;
   HttpResponse response = HttpRequestUtil.sendGetRequest(webAppURLLocal, null);
   Assert.assertEquals(
       response.getResponseCode(),
       404,
       "Response code mismatch. Client request "
           + "got a response even after web app is undeployed");
 }
  @Test(
      groups = "wso2.as",
      description = "UnDeploying web application",
      dependsOnMethods = "testInvokeWebApp")
  public void testDeleteWebApplication() throws Exception {
    webAppAdminClient.deleteWebAppFile(webAppFileName, hostName);
    assertTrue(
        WebAppDeploymentUtil.isWebApplicationUnDeployed(backendURL, sessionCookie, webAppName),
        "Web Application unDeployment failed");

    String webAppURLLocal = webAppURL + "/appServer-valied-deploymant-1.0.0";
    HttpResponse response = HttpRequestUtil.sendGetRequest(webAppURLLocal, null);
    Assert.assertEquals(
        response.getResponseCode(),
        302,
        "Response code mismatch. Client request "
            + "got a response even after web app is undeployed");
  }
 @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
 @Test(groups = "wso2.as", description = "deploy webApp as tenant")
 public void testDeployWebAppAsTenant() throws Exception {
   super.init(TestUserMode.TENANT_USER);
   webAppAdminClient = new WebAppAdminClient(backendURL, sessionCookie);
   webAppAdminClient.warFileUplaoder(
       FrameworkPathUtil.getSystemResourceLocation()
           + "artifacts"
           + File.separator
           + "AS"
           + File.separator
           + "war"
           + File.separator
           + webAppFileName);
   assertTrue(
       WebAppDeploymentUtil.isWebApplicationDeployed(backendURL, sessionCookie, webAppName),
       "Web Application Deployment failed");
   String webAppURLLocal =
       getWebAppURL(WebAppTypes.WEBAPPS) + "/" + webAppName + "/" + "Calendar.html";
   HttpResponse response1 = HttpRequestUtil.sendGetRequest(webAppURLLocal, null);
   assertTrue(response1.getData().contains("<h1>GWT Calendar</h1>"), "Webapp invocation fail");
 }
  @Test(
      groups = {"wso2.am"},
      description =
          "Test the API with endpoint security enabled with simple password"
              + " that only has characters and numbers")
  public void testInvokeGETResourceWithSecuredEndPointPasswordOnlyNumbersAndLetters()
      throws Exception {
    String endpointUsername = "******";
    char[] endpointPassword = {'a', 'd', 'm', 'i', 'n', '1', '2', '3'};
    byte[] userNamePasswordByteArray =
        (endpointUsername + ":" + String.valueOf(endpointPassword)).getBytes();
    String encodedUserNamePassword = DatatypeConverter.printBase64Binary(userNamePasswordByteArray);

    APICreationRequestBean apiCreationRequestBean =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
    apiCreationRequestBean.setTags(API_TAGS);
    apiCreationRequestBean.setDescription(API_DESCRIPTION);
    apiCreationRequestBean.setEndpointType("secured");
    apiCreationRequestBean.setEpUsername(endpointUsername);
    apiCreationRequestBean.setEpPassword(String.valueOf(endpointPassword));
    apiCreationRequestBean.setTier(TIER_UNLIMITED);
    apiCreationRequestBean.setTiersCollection(TIER_UNLIMITED);
    APIIdentifier apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
    apiIdentifier.setTier(TIER_UNLIMITED);
    createPublishAndSubscribeToAPI(
        apiIdentifier,
        apiCreationRequestBean,
        apiPublisherClientUser1,
        apiStoreClientUser1,
        APPLICATION_NAME);
    waitForAPIDeploymentSync(
        user.getUserName(), API_NAME, API_VERSION_1_0_0, APIMIntegrationConstants.IS_API_EXISTS);

    String accessToken =
        generateApplicationKeys(apiStoreClientUser1, APPLICATION_NAME).getAccessToken();
    requestHeadersGet.put("Authorization", "Bearer " + accessToken);
    HttpResponse httpResponseGet =
        HttpRequestUtil.doGet(
            getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/sec", requestHeadersGet);
    assertEquals(
        httpResponseGet.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Invocation fails for GET request for "
            + "endpoint type secured. username:"******" password:"******"Response Data not match for GET"
            + " request for endpoint type secured. Expected value :"
            + encodedUserNamePassword
            + " not contains in "
            + "response data:"
            + httpResponseGet.getData()
            + "username:"******" password:"
            + String.valueOf(endpointPassword));
  }
  @Test(
      groups = {"wso2.am"},
      dataProvider = "SymbolCharacters",
      description = "Test the API with endpoint security" + " enabled with complex password",
      dependsOnMethods = "testInvokeGETResourceWithSecuredEndPointPasswordOnlyNumbersAndLetters")
  public void testInvokeGETResourceWithSecuredEndPointComplexPassword(String symbolicCharacter)
      throws Exception {

    String endpointUsername = "******";
    char[] endpointPassword = {
      'a', 'b', 'c', 'd', symbolicCharacter.charAt(0), 'e', 'f', 'g', 'h', 'i', 'j', 'k'
    };
    byte[] userNamePasswordByteArray =
        (endpointUsername + ":" + String.valueOf(endpointPassword)).getBytes();
    String encodedUserNamePassword = DatatypeConverter.printBase64Binary(userNamePasswordByteArray);
    APICreationRequestBean apiCreationRequestBean =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
    apiCreationRequestBean.setTags(API_TAGS);
    apiCreationRequestBean.setDescription(API_DESCRIPTION);
    apiCreationRequestBean.setVisibility("public");
    apiCreationRequestBean.setEndpointType("secured");
    apiCreationRequestBean.setEpUsername(endpointUsername);
    apiCreationRequestBean.setEpPassword(
        URLEncoder.encode(String.valueOf(endpointPassword), "UTF-8"));
    // Update API with Edited information
    HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean);
    assertEquals(
        updateAPIHTTPResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Update APi with new Resource " + "information fail");
    assertEquals(
        updateAPIHTTPResponse.getData(),
        "{\"error\" : false}",
        "Update APi with new Resource information fail");
    // Send GET request

    waitForAPIDeploymentSync(
        user.getUserName(), API_NAME, API_VERSION_1_0_0, encodedUserNamePassword);

    HttpResponse httpResponseGet =
        HttpRequestUtil.doGet(
            getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + "/sec", requestHeadersGet);
    assertEquals(
        httpResponseGet.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Invocation fails for GET request for "
            + "endpoint type secured. username:"******" password:"******"Response Data not match for GET"
            + " request for endpoint type secured. Expected value : "
            + encodedUserNamePassword
            + " not contains in "
            + "response data: "
            + httpResponseGet.getData()
            + " username:"******" password:"
            + String.valueOf(endpointPassword));
  }
  @Test(
      groups = {"wso2.am"},
      description = "Pizzashack Test")
  public void testPizzashackApiSample() throws Exception {

    List<APIResourceBean> resourceBeanList = new ArrayList<APIResourceBean>();

    APICreationRequestBean apiCreationRequestBean =
        new APICreationRequestBean(
            "PizzaAPI",
            "pizzashack",
            "1.0.0",
            "admin",
            new URL("http://localhost:9766/pizzashack-api-1.0.0/api/"));

    apiCreationRequestBean.setThumbUrl("/home/bhagya/WS/Pizza_Shack_Logo.jpeg");
    apiCreationRequestBean.setDescription(
        "Pizza API:Allows to manage pizza orders (create, update, retrieve orders)");
    apiCreationRequestBean.setTags("pizza, order, pizza-menu");
    apiCreationRequestBean.setResourceCount("4");

    resourceBeanList.add(
        new APIResourceBean("GET", "Application & Application User", "Unlimited", "/menu"));
    resourceBeanList.add(
        new APIResourceBean("POST", "Application & Application User", "Unlimited", "/order"));
    resourceBeanList.add(
        new APIResourceBean(
            "GET", "Application & Application User", "Unlimited", "/order/{orderid}"));
    resourceBeanList.add(
        new APIResourceBean("GET", "Application & Application User", "Unlimited", "/delivery"));
    apiCreationRequestBean.setResourceBeanList(resourceBeanList);

    apiCreationRequestBean.setTier("Unlimited");
    apiCreationRequestBean.setTiersCollection("Unlimited");

    apiPublisher.addAPI(apiCreationRequestBean);
    APILifeCycleStateRequest updateRequest =
        new APILifeCycleStateRequest(
            "PizzaAPI",
            publisherContext.getContextTenant().getContextUser().getUserName(),
            APILifeCycleState.PUBLISHED);
    apiPublisher.changeAPILifeCycleStatus(updateRequest);
    apiStore.addApplication("PizzaShack", "Unlimited", "", "");
    SubscriptionRequest subscriptionRequest =
        new SubscriptionRequest(
            "PizzaAPI", storeContext.getContextTenant().getContextUser().getUserName());
    subscriptionRequest.setApplicationName("PizzaShack");
    apiStore.subscribe(subscriptionRequest);

    APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("PizzaShack");
    String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
    JSONObject response = new JSONObject(responseString);
    String accessToken =
        response.getJSONObject("data").getJSONObject("key").get("accessToken").toString();
    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put("Authorization", "Bearer " + accessToken);

    Thread.sleep(2000);

    HttpResponse pizzaShackResponse =
        HttpRequestUtil.doGet(
            gatewayUrlsMgt.getWebAppURLNhttp() + "pizzashack/1.0.0/menu", requestHeaders);
    assertEquals(
        pizzaShackResponse.getResponseCode(),
        Response.Status.OK.getStatusCode(),
        "Response code mismatched when api invocation");
    System.out.println("My Response Code is " + pizzaShackResponse.getResponseCode());

    assertTrue(
        pizzaShackResponse.getData().contains("BBQ Chicken Bacon"),
        "Response data mismatched when api invocation");
    assertTrue(
        pizzaShackResponse.getData().contains("Grilled white chicken"),
        "Response data mismatched when api invocation");
    assertTrue(
        pizzaShackResponse.getData().contains("Chicken Parmesan"),
        "Response data mismatched when api invocation");
    assertTrue(
        pizzaShackResponse.getData().contains("Tuscan Six Cheese"),
        "Response data mismatched when api invocation");
    assertTrue(
        pizzaShackResponse.getData().contains("Asiago and Fontina"),
        "Response data mismatched when api invocation");
  }
  @Test(
      groups = {"wso2.am"},
      description = "test  invocation of  api under tier Gold.")
  public void testInvokingWithGoldTier() throws APIManagerIntegrationTestException, IOException {

    applicationNameGold = APPLICATION_NAME + TIER_GOLD;
    apiStoreClientUser1.addApplication(applicationNameGold, TIER_GOLD, "", "");
    apiCreationRequestBean =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
    apiCreationRequestBean.setTags(API_TAGS);
    apiCreationRequestBean.setDescription(API_DESCRIPTION);
    apiCreationRequestBean.setTier(TIER_GOLD);
    createPublishAndSubscribeToAPI(
        apiIdentifier,
        apiCreationRequestBean,
        apiPublisherClientUser1,
        apiStoreClientUser1,
        applicationNameGold);

    // get access token
    String accessToken =
        generateApplicationKeys(apiStoreClientUser1, applicationNameGold).getAccessToken();

    // Create requestHeaders
    requestHeadersGoldTier = new HashMap<String, String>();
    requestHeadersGoldTier.put("Authorization", "Bearer " + accessToken);
    requestHeadersGoldTier.put("accept", "text/xml");
    long startTime = System.currentTimeMillis();
    long currentTime;
    for (int invocationCount = 1;
        invocationCount <= GOLD_INVOCATION_LIMIT_PER_MIN;
        invocationCount++) {
      currentTime = System.currentTimeMillis();
      // Invoke  API
      HttpResponse invokeResponse =
          HttpRequestUtil.doGet(
              gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
              requestHeadersGoldTier);
      assertEquals(
          invokeResponse.getResponseCode(),
          HTTP_RESPONSE_CODE_OK,
          "Response code mismatched. Invocation attempt:"
              + invocationCount
              + " failed  during :"
              + (currentTime - startTime)
              + " milliseconds under Gold API level tier");
      assertTrue(
          invokeResponse.getData().contains(API_RESPONSE_DATA),
          "Response data mismatched. Invocation attempt:"
              + invocationCount
              + " failed  during :"
              + (currentTime - startTime)
              + " milliseconds under Gold API level tier");
    }
    currentTime = System.currentTimeMillis();
    HttpResponse invokeResponse =
        HttpRequestUtil.doGet(
            gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
            requestHeadersGoldTier);
    assertEquals(
        invokeResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_SERVICE_UNAVAILABLE,
        "Response code mismatched. Invocation attempt:"
            + (GOLD_INVOCATION_LIMIT_PER_MIN + 1)
            + " passed  during :"
            + (currentTime - startTime)
            + " milliseconds under Gold API level tier");
    assertTrue(
        invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT),
        "Response data mismatched. Invocation attempt:"
            + (GOLD_INVOCATION_LIMIT_PER_MIN + 1)
            + " passed  during :"
            + (currentTime - startTime)
            + " milliseconds under Gold API level tier");
  }
 @Test(
     groups = {"wso2.am"},
     description = "test  invocation of  api under tier Silver.",
     dependsOnMethods = "testEditAPITierToSilver")
 public void testInvokingWithSilverTier()
     throws APIManagerIntegrationTestException, InterruptedException, IOException {
   applicationNameSilver = APPLICATION_NAME + TIER_SILVER;
   // create new application
   apiStoreClientUser1.addApplication(applicationNameSilver, TIER_GOLD, "", "");
   apiIdentifier.setTier(TIER_SILVER);
   // Do a API Silver subscription.
   subscribeToAPI(apiIdentifier, applicationNameSilver, apiStoreClientUser1);
   // get access token
   String accessToken =
       generateApplicationKeys(apiStoreClientUser1, applicationNameSilver).getAccessToken();
   // Create requestHeaders
   Map<String, String> requestHeadersSilverTier = new HashMap<String, String>();
   requestHeadersSilverTier.put("accept", "text/xml");
   requestHeadersSilverTier.put("Authorization", "Bearer " + accessToken);
   // millisecond to expire the throttling block
   Thread.sleep(THROTTLING_UNIT_TIME + THROTTLING_ADDITIONAL_WAIT_TIME);
   long startTime = System.currentTimeMillis();
   long currentTime;
   for (int invocationCount = 1;
       invocationCount <= SILVER_INVOCATION_LIMIT_PER_MIN;
       invocationCount++) {
     currentTime = System.currentTimeMillis();
     // Invoke  API
     HttpResponse invokeResponse =
         HttpRequestUtil.doGet(
             gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
             requestHeadersSilverTier);
     assertEquals(
         invokeResponse.getResponseCode(),
         HTTP_RESPONSE_CODE_OK,
         "Response code mismatched. "
             + "Invocation attempt:"
             + invocationCount
             + " failed  during :"
             + (currentTime - startTime)
             + " milliseconds under Silver API level tier");
     assertTrue(
         invokeResponse.getData().contains(API_RESPONSE_DATA),
         "Response data mismatched."
             + " Invocation attempt:"
             + invocationCount
             + " failed  during :"
             + (currentTime - startTime)
             + " milliseconds under Silver API level tier");
   }
   currentTime = System.currentTimeMillis();
   HttpResponse invokeResponse =
       HttpRequestUtil.doGet(
           gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
           requestHeadersSilverTier);
   assertEquals(
       invokeResponse.getResponseCode(),
       HTTP_RESPONSE_CODE_SERVICE_UNAVAILABLE,
       "Response code mismatched. Invocation attempt:"
           + (SILVER_INVOCATION_LIMIT_PER_MIN + 1)
           + " passed  during :"
           + (currentTime - startTime)
           + " milliseconds under Silver API level tier");
   assertTrue(
       invokeResponse.getData().contains(MESSAGE_THROTTLED_OUT),
       "Response data mismatched. Invocation attempt:"
           + (SILVER_INVOCATION_LIMIT_PER_MIN + 1)
           + " passed  during :"
           + (currentTime - startTime)
           + " milliseconds under Silver API level tier");
 }
  @Test(groups = "wso2.am", description = "Check functionality of the default version API")
  public void testDefaultVersionAPI() throws Exception {

    // Login to the API Publisher
    apiPublisher.login(user.getUserName(), user.getPassword());

    String apiName = "DefaultVersionAPI";
    String apiVersion = "1.0.0";
    String apiContext = "defaultversion";
    String endpointUrl = getGatewayURLNhttp() + "response";

    // Create the api creation request object
    APIRequest apiRequest = new APIRequest(apiName, apiContext, new URL(endpointUrl));
    apiRequest.setDefault_version("default_version");
    apiRequest.setDefault_version_checked("default_version");
    apiRequest.setVersion(apiVersion);
    apiRequest.setTiersCollection("Unlimited");
    apiRequest.setTier("Unlimited");
    apiRequest.setProvider(provider);

    // Add the API using the API publisher.
    HttpResponse response = apiPublisher.addAPI(apiRequest);

    APILifeCycleStateRequest updateRequest =
        new APILifeCycleStateRequest(apiName, user.getUserName(), APILifeCycleState.PUBLISHED);
    // Publish the API
    response = apiPublisher.changeAPILifeCycleStatus(updateRequest);

    // Login to the API Store
    apiStore.login(user.getUserName(), user.getPassword());

    // Add an Application in the Store.
    response = apiStore.addApplication("DefaultVersionAPP", "Unlimited", "", "");
    verifyResponse(response);

    // Subscribe the API to the DefaultApplication
    SubscriptionRequest subscriptionRequest =
        new SubscriptionRequest(apiName, apiVersion, provider, "DefaultVersionAPP", "Unlimited");
    response = apiStore.subscribe(subscriptionRequest);

    // Generate production token and invoke with that
    APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("DefaultVersionAPP");
    String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
    JSONObject jsonResponse = new JSONObject(responseString);

    // Get the accessToken which was generated.
    String accessToken =
        jsonResponse.getJSONObject("data").getJSONObject("key").getString("accessToken");

    String apiInvocationUrl = getAPIInvocationURLHttp(apiContext);

    // Going to access the API without the version in the request url.
    HttpResponse directResponse = HttpRequestUtil.doGet(endpointUrl, new HashMap<String, String>());

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer " + accessToken);
    // Invoke the API
    HttpResponse httpResponse = HttpRequestUtil.doGet(apiInvocationUrl, headers);

    // Check if accessing the back-end directly and accessing it via the API yield the same
    // responses.
    assertEquals(
        httpResponse.getData(),
        directResponse.getData(),
        "Default version API test failed while " + "invoking the API.");
  }