@Test(
     groups = {"wso2.am"},
     description = "Test changing of the API Tier from Gold to Silver",
     dependsOnMethods = "testInvokingAfterExpireThrottleExpireTime")
 public void testEditAPITierToSilver()
     throws APIManagerIntegrationTestException, MalformedURLException {
   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_SILVER);
   apiCreationRequestBean.setTiersCollection(TIER_SILVER);
   // Update API with Edited information with Tier Silver
   HttpResponse updateAPIHTTPResponse = apiPublisherClientUser1.updateAPI(apiCreationRequestBean);
   assertEquals(
       updateAPIHTTPResponse.getResponseCode(),
       HTTP_RESPONSE_CODE_OK,
       "Update API Response Code is"
           + " invalid. Updating of API information fail"
           + getAPIIdentifierString(apiIdentifier));
   assertEquals(
       getValueFromJSON(updateAPIHTTPResponse, "error"),
       "false",
       "Error in API Update in "
           + getAPIIdentifierString(apiIdentifier)
           + "Response Data:"
           + updateAPIHTTPResponse.getData());
 }
  @Test(
      groups = {"wso2.am"},
      description = "Test changing of the API end point URL",
      dependsOnMethods = "testAPIInvocationBeforeChangeTheEndPointURL")
  public void testEditEndPointURL()
      throws APIManagerIntegrationTestException, MalformedURLException {
    // Create the API Request with new context
    APICreationRequestBean apiCreationRequestBeanUpdate =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(API2_END_POINT_URL));
    apiCreationRequestBeanUpdate.setTags(API_TAGS);
    apiCreationRequestBeanUpdate.setDescription(API_DESCRIPTION);
    // Update API with Edited information
    HttpResponse updateAPIHTTPResponse =
        apiPublisherClientUser1.updateAPI(apiCreationRequestBeanUpdate);

    assertEquals(
        updateAPIHTTPResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Update API end point URL Response Code is invalid."
            + getAPIIdentifierString(apiIdentifier));
    assertEquals(
        getValueFromJSON(updateAPIHTTPResponse, "error"),
        "false",
        "Error in API end point URL Update in "
            + getAPIIdentifierString(apiIdentifier)
            + "Response Data:"
            + updateAPIHTTPResponse.getData());
  }
  @BeforeClass(alwaysRun = true)
  public void initialize()
      throws APIManagerIntegrationTestException, XPathExpressionException, RemoteException,
          ResourceAdminServiceExceptionException, MalformedURLException {
    super.init();
    apiEndPointUrl = getGatewayURLHttp() + API_END_POINT_POSTFIX_URL;
    providerName = user.getUserName();
    apiCreationRequestBean =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
    apiCreationRequestBean.setTags(API_TAGS);
    apiCreationRequestBean.setDescription(API_DESCRIPTION);
    String publisherURLHttp = getPublisherURLHttp();
    String storeURLHttp = getStoreURLHttp();
    apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp);
    APIStoreRestClient apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp);

    // Login to API Publisher with  admin
    apiPublisherClientUser1.login(user.getUserName(), user.getPassword());

    // Login to API Store with  admin
    apiStoreClientUser1.login(user.getUserName(), user.getPassword());

    apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
    String artifactsLocation =
        TestConfigurationProvider.getResourceLocation()
            + File.separator
            + "artifacts"
            + File.separator
            + "AM"
            + File.separator
            + "lifecycletest"
            + File.separator
            + "tiers.xml";
    resourceAdminServiceClient =
        new ResourceAdminServiceClient(
            publisherContext.getContextUrls().getBackEndUrl(), createSession(publisherContext));
    originalTiersXML = resourceAdminServiceClient.getTextContent(TIER_XML_REG_CONFIG_LOCATION);
    newTiersXML = readFile(artifactsLocation);
  }
 @BeforeClass(alwaysRun = true)
 public void initialize()
     throws APIManagerIntegrationTestException, XPathExpressionException, MalformedURLException {
   super.init();
   api1EndPointUrl = getGatewayURLHttp() + API_END_POINT_POSTFIX_URL;
   providerName = user.getUserName();
   apiCreationRequestBean =
       new APICreationRequestBean(
           API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(api1EndPointUrl));
   apiCreationRequestBean.setTags(API_TAGS);
   apiCreationRequestBean.setDescription(API_DESCRIPTION);
   String publisherURLHttp = getPublisherURLHttp();
   String storeURLHttp = getStoreURLHttp();
   apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp);
   apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp);
   // Login to API Publisher with  admin
   apiPublisherClientUser1.login(user.getUserName(), user.getPassword());
   // Login to API Store with  admin
   apiStoreClientUser1.login(user.getUserName(), user.getPassword());
   apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
   apiStoreClientUser1.addApplication(APPLICATION_NAME, TIER_UNLIMITED, "", "");
 }
  @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");
  }
  @BeforeClass(alwaysRun = true)
  public void setEnvironment() throws Exception {
    super.init(userMode);
    // Load the back-end dummy API
    if (TestUserMode.SUPER_TENANT_ADMIN == userMode) {
      String gatewaySessionCookie = createSession(gatewayContextMgt);
      loadSynapseConfigurationFromClasspath(
          "artifacts"
              + File.separator
              + "AM"
              + File.separator
              + "synapseconfigs"
              + File.separator
              + "rest"
              + File.separator
              + "dummy_api.xml",
          gatewayContextMgt,
          gatewaySessionCookie);
    }
    publisherURLHttp = getPublisherURLHttp();
    apiPublisher = new APIPublisherRestClient(publisherURLHttp);
    apiPublisher.login(user.getUserName(), user.getPassword());

    String providerName = user.getUserName();
    URL endpointUrl = new URL(getSuperTenantAPIInvocationURLHttp("response", "1.0.0"));
    ArrayList<APIResourceBean> resourceBeanList = new ArrayList<APIResourceBean>();
    resourceBeanList.add(
        new APIResourceBean(
            APIMIntegrationConstants.HTTP_VERB_GET,
            APIMIntegrationConstants.RESOURCE_AUTH_TYPE_APPLICATION_AND_APPLICATION_USER,
            APIMIntegrationConstants.RESOURCE_TIER.UNLIMITED,
            "/*"));
    apiCreationRequestBean =
        new APICreationRequestBean(
            API_NAME, API_CONTEXT, API_VERSION, providerName, endpointUrl, resourceBeanList);
    apiCreationRequestBean.setTags(TAGS);
    apiCreationRequestBean.setDescription(DESCRIPTION);
    String publisherURLHttp = getPublisherURLHttp();
    String storeURLHttp = getStoreURLHttp();
    apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp);
    apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp);
    // Login to API Publisher with admin
    apiPublisherClientUser1.login(user.getUserName(), user.getPassword());
    // Login to API Store with  admin
    apiStoreClientUser1.login(user.getUserName(), user.getPassword());
    apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION);
    apiIdentifier.setTier(APIMIntegrationConstants.API_TIER.GOLD);
    // Create application
    apiStoreClientUser1.addApplication(
        APPLICATION_NAME, APIMIntegrationConstants.APPLICATION_TIER.LARGE, "", "");
    accessToken = generateApplicationKeys(apiStoreClientUser1, APPLICATION_NAME).getAccessToken();

    createPublishAndSubscribeToAPI(
        apiIdentifier,
        apiCreationRequestBean,
        apiPublisherClientUser1,
        apiStoreClientUser1,
        APPLICATION_NAME);
    waitForAPIDeploymentSync(
        user.getUserName(), API_NAME, API_VERSION, APIMIntegrationConstants.IS_API_EXISTS);
  }