/*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.identity.integration.test.oauth2;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
import org.wso2.carbon.integration.common.admin.client.AuthenticatorClient;
import org.wso2.identity.integration.test.utils.OAuth2Constant;

import java.util.ArrayList;
import java.util.List;

public class OAuth2ServiceRefreshTokenGrantTestCase extends OAuth2ServiceAbstractIntegrationTest {
    private AuthenticatorClient logManger;
    private String adminUsername;
    private String adminPassword;
    private String refreshToken;
    private String consumerKey;
    private String consumerSecret;

    private DefaultHttpClient client;

    @BeforeClass(alwaysRun = true)
    public void testInit() throws Exception {
        super.init(TestUserMode.SUPER_TENANT_USER);
        logManger = new AuthenticatorClient(backendURL);
        adminUsername = userInfo.getUserName();
        adminPassword = userInfo.getPassword();
        logManger.login(isServer.getSuperTenant().getTenantAdmin().getUserName(),
                isServer.getSuperTenant().getTenantAdmin().getPassword(),
                isServer.getInstance().getHosts().get("default"));

        setSystemproperties();
        client = new DefaultHttpClient();
    }

    @AfterClass(alwaysRun = true)
    public void atEnd() throws Exception {
        deleteApplication();
        removeOAuthApplicationData();

        logManger = null;
        consumerKey = null;
        refreshToken = null;
    }

    @Test(alwaysRun = true, description = "Check Oauth2 application registration")
    public void testRegisterApplication() throws Exception {
        OAuthConsumerAppDTO appDto = createApplication();
        Assert.assertNotNull(appDto, "Application creation failed.");

        consumerKey = appDto.getOauthConsumerKey();
        Assert.assertNotNull(consumerKey, "Application creation failed.");

        consumerSecret = appDto.getOauthConsumerSecret();
    }

    @Test(groups = "wso2.is", description = "Validate refresh token", dependsOnMethods = "testRegisterApplication")
    public void testSendAuthorizedPost() throws Exception {
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("username", adminUsername));
        postParameters.add(new BasicNameValuePair("password", adminPassword));
        postParameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER));
        JSONObject responseObject = responseObject(postParameters);
        refreshToken = responseObject.get("refresh_token").toString();

        Assert.assertNotNull(refreshToken, "Refresh token is null.");
    }

    @Test(groups = "wso2.is", description = "Validate refresh token", dependsOnMethods = "testSendAuthorozedPost")
    public void testRefreshTokenGrant() throws Exception {
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN));
        postParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken));
        JSONObject responseObject = responseObject(postParameters);
        String accessToken = responseObject.get("access_token").toString();

        Assert.assertNotNull(accessToken, "Access token is null.");
    }

    private JSONObject responseObject(List<NameValuePair> postParameters) throws Exception {
        HttpPost httpPost = new HttpPost(OAuth2Constant.ACCESS_TOKEN_ENDPOINT);
        //generate post request
        httpPost.setHeader("Authorization", "Basic " + getBase64EncodedString(consumerKey, consumerSecret));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
        HttpResponse response = client.execute(httpPost);
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
        EntityUtils.consume(response.getEntity());

        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(responseString);
        if (json == null) {
            throw new Exception(
                    "Error occurred while getting the response");
        }

        return json;
    }

}

@@ -1,11 +1,12 @@
 /*%0A
+ 
 * Copyri
@@ -12,16 +12,22 @@
 ight (c)
+ 2017,
  WSO2 In
@@ -76,47 +76,22 @@
 ed.%0A
+ 
 *%0A
+ 
 * 
-WSO2 Inc. licenses this file to you
+Licensed
  und
@@ -112,18 +112,16 @@
 License,
-%0A*
  Version
@@ -141,16 +141,19 @@
 cense%22);
+%0A *
  you may
@@ -177,18 +177,16 @@
 e except
-%0A*
  in comp
@@ -210,16 +210,17 @@
 icense.%0A
+ 
 * You ma
@@ -253,19 +253,26 @@
 ense at%0A
+ 
 *%0A
+ 
 *
+     
  http://
@@ -307,18 +307,20 @@
 NSE-2.0%0A
+ 
 *%0A
+ 
 * Unless
@@ -371,18 +371,16 @@
 writing,
-%0A*
  softwar
@@ -380,16 +380,19 @@
 software
+%0A *
  distrib
@@ -434,18 +434,16 @@
 ed on an
-%0A*
  %22AS IS%22
@@ -449,16 +449,19 @@
 %22 BASIS,
+%0A *
  WITHOUT
@@ -492,18 +492,16 @@
 S OF ANY
-%0A*
  KIND, e
@@ -525,16 +525,19 @@
 implied.
+%0A *
  See the
@@ -552,18 +552,16 @@
  for the
-%0A*
  specifi
@@ -596,16 +596,19 @@
 ions and
+%0A *
  limitat
@@ -611,18 +611,16 @@
 itations
-%0A*
  under t
@@ -631,16 +631,17 @@
 icense.%0A
+ 
 */%0A%0Apack

Update OAuth2ServiceRefreshTokenGrantTestCase.java