Ejemplo n.º 1
0
 @Test(description = "Test get license.")
 public void testGetLicense() throws Exception {
   HttpResponse response = client.get(Constants.LicenseManagement.GET_LICENSE_ENDPOINT);
   Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode());
   Assert.assertTrue(
       response.getData().contains(Constants.LicenseManagement.LICENSE_RESPONSE_PAYLOAD));
 }
 @Test(dataProvider = "validUserModeDataProvider", description = TEST_DESCRIPTION)
 public void testChangeStateFromCreateToInReviewWithValidUsers(
     String userName, String password, String uuid) throws Exception {
   APPMPublisherRestClient publisherRestClient = new APPMPublisherRestClient(backEndUrl);
   // Login to publisher by a valid user.
   publisherRestClient.login(userName, password);
   HttpResponse httpResponse =
       publisherRestClient.changeState(uuid, AppmTestConstants.LifeCycleStatus.SUBMIT_FOR_REVIEW);
   JSONObject responseData = new JSONObject(httpResponse.getData());
   // Logout from publisher by valid user.
   publisherRestClient.logout();
   int responseCode = httpResponse.getResponseCode();
   assertTrue(
       responseCode == 200,
       "Excepted status code is 200 for user :"******". But received status "
           + "code is "
           + responseCode);
   assertEquals(
       responseData.getString(AppmTestConstants.STATUS),
       "Success",
       "Changing web app life cycle state "
           + "from create to review failed for user : "******" who has sufficient privileges to change "
           + "life cycle status.");
 }
 @Test(dataProvider = "inValidUserModeDataProvider", description = TEST_DESCRIPTION)
 public void testChangeStateFromInReviewToRejectWithInValidUsers(
     String userName, String password, String uuid) throws Exception {
   APPMPublisherRestClient publisherRestClient = new APPMPublisherRestClient(backEndUrl);
   // Login to publisher by an invalid user.
   publisherRestClient.login(userName, password);
   HttpResponse httpResponse =
       publisherRestClient.changeState(uuid, AppmTestConstants.LifeCycleStatus.REJECT);
   JSONObject responseData = new JSONObject(httpResponse.getData());
   // Logout from publisher by invalid user.
   publisherRestClient.logout();
   int responseCode = httpResponse.getResponseCode();
   assertTrue(
       responseCode == 401,
       "Excepted status code is 401 for user :"******". But received "
           + "status code is "
           + responseCode);
   assertEquals(
       responseData.getString(AppmTestConstants.STATUS),
       "Access Denied",
       "Changing WebApp life cycle "
           + "state from in review to reject allowed for user : "******" who has insufficient privileges "
           + "to change life cycle status.");
 }
 @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  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 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());
  }
  @Test(description = TEST_DESCRIPTION)
  public void testAppPropertyRetrieval() throws Exception {
    HttpResponse response =
        appmPublisherRestClient.webAppCreate(appName, context, appVersion, trackingCode);
    JSONObject responseData = new JSONObject(response.getData());
    String uuid = responseData.getString(AppmTestConstants.ID);
    String appType = AppmTestConstants.WEB_APP;
    appmPublisherRestClient.publishWebApp(uuid);

    HttpResponse appPropertyResponse = appmPublisherRestClient.getWebAppProperty(uuid);
    JSONObject jsonObject = new JSONObject(appPropertyResponse.getData());

    // Check App Id
    String appId = (String) jsonObject.get(AppmTestConstants.ID);
    assertTrue((appId.equals(uuid) == true), "Unable to Retrieve application id.");

    // Check App Type
    String type = (String) jsonObject.get(AppmTestConstants.TYPE);
    assertTrue((type.equals(appType) == true), "Unable to Retrieve application type.");

    // Check lifecycleState
    String lifecycleState = (String) jsonObject.get(AppmTestConstants.LIFE_CYCLE_STATE);
    assertTrue(
        (lifecycleState.equalsIgnoreCase(AppmTestConstants.PUBLISHED) == true),
        "Unable to Retrieve application life cycle.");

    // Check Path attribute
    String appPropertyString = userName + "/" + appName + "/" + appVersion + "/" + appType;
    String path = (String) jsonObject.get("path");
    assertTrue(path.endsWith(appPropertyString), "Unable to Retrieve application path.");
  }
  @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(
     dependsOnMethods = {"testEnrollment"},
     description = "Test Android install apps operation.")
 public void testInstallApps() throws Exception {
   JsonObject operationData =
       PayloadGenerator.getJsonPayload(
           Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
           Constants.AndroidOperations.INSTALL_APPS_OPERATION);
   JsonArray deviceIds = new JsonArray();
   JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID);
   deviceIds.add(deviceID);
   operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
   HttpResponse response =
       rclient.post(Constants.AndroidOperations.INSTALL_APPS_ENDPOINT, operationData.toString());
   Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
 }
  @Test(dataProvider = "validUserModeDataProvider", description = TEST_DESCRIPTION)
  public void testUnpublishedWebAppDeleteWithValidUsers(
      String username, String password, String appId) throws Exception {
    APPMPublisherRestClient publisherRestClient = new APPMPublisherRestClient(backEndUrl);
    publisherRestClient.login(username, password);
    // delete web application
    HttpResponse appDeleteResponse = publisherRestClient.deleteApp(appId);
    publisherRestClient.logout();
    JSONObject jsonObject = new JSONObject(appDeleteResponse.getData());

    Assert.assertTrue(
        (Boolean) jsonObject.get("isDeleted"),
        "Web App delete is not allowed for user :"******" who has sufficient privileges to delete.");
  }
  @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");
  }
  @Test(
      groups = {"wso2.am"},
      description = "Test availability of tiers in API Manage Page before change tiers XML",
      dependsOnMethods = "testAvailabilityOfTiersInPermissionPageBeforeChangeTiersXML")
  public void testAvailabilityOfTiersInAPIManagePageBeforeChangeTiersXML()
      throws APIManagerIntegrationTestException {

    HttpResponse tierManagePageHttpResponse =
        apiPublisherClientUser1.getAPIManagePage(API_NAME, providerName, API_VERSION_1_0_0);
    assertEquals(
        tierManagePageHttpResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Response code mismatched when invoke to get Tier Permission Page");
    assertTrue(
        tierManagePageHttpResponse.getData().contains(TIER_MANAGE_PAGE_TIER_GOLD),
        "default tier  Gold is not available in Tier Permission page before  add new tear in tiers.xml");
    assertFalse(
        tierManagePageHttpResponse.getData().contains(TIER_MANAGE_PAGE_TIER_PLATINUM),
        "new tier Platinum available in Tier Permission page before  add new tear in tiers.xml");
  }
  @Test(
      groups = {"wso2.am"},
      description = "test availability of tiers in Permission Page before change tiers XML")
  public void testAvailabilityOfTiersInPermissionPageBeforeChangeTiersXML()
      throws APIManagerIntegrationTestException {
    // Create a API
    APIIdentifier apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
    createAndPublishAPI(apiIdentifier, apiCreationRequestBean, apiPublisherClientUser1, false);

    HttpResponse tierPermissionPageHttpResponse = apiPublisherClientUser1.getTierPermissionsPage();
    assertEquals(
        tierPermissionPageHttpResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Response code mismatched when invoke to get Tier Permission Page");
    assertTrue(
        tierPermissionPageHttpResponse.getData().contains(TIER_PERMISSION_PAGE_TIER_GOLD),
        "default tier Gold is not available in Tier Permission page before  add new tear in tiers.xml");
    assertFalse(
        tierPermissionPageHttpResponse.getData().contains(TIER_PERMISSION_PAGE_TIER_PLATINUM),
        "new tier Platinum available in Tier Permission page before  add new tear in tiers.xml");
  }
 @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 = "test availability of tiers in Permission Page after change tiers XML",
      dependsOnMethods = "testAvailabilityOfTiersInAPIManagePageBeforeChangeTiersXML")
  public void testAvailabilityOfTiersInPermissionPageAfterChangeTiersXML()
      throws RemoteException, ResourceAdminServiceExceptionException,
          APIManagerIntegrationTestException {
    // Changing the Tier XML
    resourceAdminServiceClient.updateTextContent(TIER_XML_REG_CONFIG_LOCATION, newTiersXML);
    HttpResponse tierPermissionPageHttpResponse = apiPublisherClientUser1.getTierPermissionsPage();
    assertEquals(
        tierPermissionPageHttpResponse.getResponseCode(),
        HTTP_RESPONSE_CODE_OK,
        "Response code mismatched when invoke to get Tier Permission Page");
    assertTrue(
        tierPermissionPageHttpResponse.getData().contains(TIER_PERMISSION_PAGE_TIER_GOLD),
        "default tier Gold is not available in Tier Permission page before  add new tear in tiers.xml");

    assertTrue(
        tierPermissionPageHttpResponse.getData().contains(TIER_PERMISSION_PAGE_TIER_PLATINUM),
        "new tier Platinum  is not available in Tier Permission page before  add new tear in tiers.xml");
  }
 @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.esb"},
      description = "HTTP Endpoint GET test: RESTful",
      priority = 6,
      enabled = false)
  public void testToGet() throws IOException {
    // check whether the student is added.
    String studentGetUri = getProxyServiceURLHttp("getEPProxy") + "/student/" + studentName;
    HttpResponse getResponse = HttpURLConnectionClient.sendGetRequest(studentGetUri, null);

    assertTrue(
        getResponse
            .getData()
            .contains(
                "<ns:getStudentResponse xmlns:ns=\"http://axis2.apache.org\"><ns:return>"
                    + "<ns:age>100</ns:age>"
                    + "<ns:name>"
                    + studentName
                    + "</ns:name>"
                    + "<ns:subjects>testAutomation</ns:subjects>"
                    + "</ns:return></ns:getStudentResponse>"));
  }
  @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.");
  }
  @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");
 }