Minor changes

pull/104/head
Pasindu Rupasinghe 2 years ago
parent 0d70576401
commit e920df6da3

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.21-SNAPSHOT</version> <version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -79,13 +79,12 @@
<artifactId>feign-okhttp</artifactId> <artifactId>feign-okhttp</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<<<<<<< HEAD
<groupId>org.wso2.carbon.apimgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId> <artifactId>org.wso2.carbon.apimgt.api</artifactId>
======= </dependency>
<dependency>
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
>>>>>>> 2855ef0a30 (change http client to okhttp)
</dependency> </dependency>
</dependencies> </dependencies>

@ -9,7 +9,6 @@ import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicat
import okhttp3.*; import okhttp3.*;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.ssl.Base64;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
@ -22,7 +21,6 @@ import java.security.NoSuchAlgorithmException;
public class APIApplicationServicesImpl implements APIApplicationServices { public class APIApplicationServicesImpl implements APIApplicationServices {
private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class);
<<<<<<< HEAD
private static final OkHttpClient client = getOkHttpClient(); private static final OkHttpClient client = getOkHttpClient();
private static final Gson gson = new Gson(); private static final Gson gson = new Gson();
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
@ -53,6 +51,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
return gson.fromJson(response.body().string(), APIApplicationKey.class); return gson.fromJson(response.body().string(), APIApplicationKey.class);
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while processing the response"; msg = "Error occurred while processing the response";
log.error(msg);
throw new APIApplicationServicesException(msg); throw new APIApplicationServicesException(msg);
} }
} }
@ -86,10 +85,10 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON);
//application/x-www-form-urlencoded //application/x-www-form-urlencoded
String keyManagerEndpoint = "https://localhost:9443/oauth2/token"; String tokenEndPoint = "https://localhost:9443/oauth2/token";
Request request = new Request.Builder() Request request = new Request.Builder()
.url(keyManagerEndpoint) .url(tokenEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret)) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret))
.post(requestBody) .post(requestBody)
.build(); .build();
@ -99,6 +98,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
return gson.fromJson(response.body().string(), AccessTokenInfo.class); return gson.fromJson(response.body().string(), AccessTokenInfo.class);
} catch (IOException e) { } catch (IOException e) {
msg = "Error occurred while processing the response"; msg = "Error occurred while processing the response";
log.error(msg);
throw new APIApplicationServicesException(msg); throw new APIApplicationServicesException(msg);
} }
} }
@ -121,13 +121,6 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
.sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
.hostnameVerifier((hostname, sslSession) -> true).build(); .hostnameVerifier((hostname, sslSession) -> true).build();
} }
=======
// private final OkHttpClient client;
// public APIApplicationServicesImpl() {
// this.client = new OkHttpClient();
// }
>>>>>>> e76624c1de (Add exceptions)
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
try { try {
@ -152,201 +145,4 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
} }
} }
<<<<<<< HEAD
@Override
public APIApplicationKey createAndRetrieveApplicationCredentials()
throws APIApplicationServicesException, BadRequestException {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("callbackUrl",Constants.EMPTY_STRING);
jsonObject.addProperty("clientName",Constants.CLIENT_NAME);
jsonObject.addProperty("grantType",Constants.EMPTY_STRING);
jsonObject.addProperty("owner",Constants.OWNER);
jsonObject.addProperty("saasApp",true);
MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(jsonMediaType, jsonObject.toString());
String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register";
Request request = new Request.Builder()
.url(keyManagerEndpoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin"))
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(request);
System.out.println("---------------------------");
System.out.println(response);
// JSONObject responseObj = new JSONObject(Objects.requireNonNull(response.body()).string());
<<<<<<< HEAD
} catch (IOException e) {
throw new RuntimeException(e);
}
// try {
// URL url = new URL("https://localhost:9443/client-registration/v0.17/register");
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpPost request = new HttpPost(url.toString());
//
// RegistrationProfile registrationProfile = new RegistrationProfile();
// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING);
// registrationProfile.setClientName(Constants.CLIENT_NAME);
// registrationProfile.setGrantType(Constants.GRANT_TYPE);
// registrationProfile.setOwner(Constants.OWNER);
// registrationProfile.setIsSaasApp(true);
//
// String jsonString = registrationProfile.toJSON();
// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
// request.setEntity(entity);
//
// //ToDo: Remove hardcoded value
// String basicAuth = getBase64Encode("admin", "admin");
// request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth);
// request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON);
//
// HttpResponse httpResponse = httpclient.execute(request);
//
// if (httpResponse != null) {
// String response = PublisherRESTAPIUtil.getResponseString(httpResponse);
// try {
// if(response != null){
// JSONParser jsonParser = new JSONParser();
// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response);
// APIApplicationKey apiApplicationKey = new APIApplicationKey();
// apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID));
// apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET));
// return apiApplicationKey;
// } else {
// return null;
// }
// } catch (ParseException e) {
// throw new RuntimeException(e);
// }
// }
//
// } catch (IOException | NoSuchAlgorithmException | KeyStoreException |
// KeyManagementException e) {
// log.error("failed to call http client.", e);
// }
return null;
=======
String jsonString = registrationProfile.toJSON();
StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
request.setEntity(entity);
//ToDo: Remove hardcoded value
String basicAuth = getBase64Encode("admin", "admin");
request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth);
request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON);
HttpResponse httpResponse = httpclient.execute(request);
if (httpResponse != null) {
String response = PublisherRESTAPIUtil.getResponseString(httpResponse);
try {
if(response != null){
JSONParser jsonParser = new JSONParser();
JSONObject jsonPayload = (JSONObject) jsonParser.parse(response);
APIApplicationKey apiApplicationKey = new APIApplicationKey();
apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID));
apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET));
return apiApplicationKey;
} else {
String msg = "Request payload is null. Please verify the request payload.";
log.error(msg);
throw new BadRequestException(msg);
}
} catch (ParseException e) {
throw new APIApplicationServicesException("Error when parsing the response " + response, e);
}
} else {
return null;
}
} catch (IOException e) {
throw new APIApplicationServicesException("Error when reading the response from buffer.", e);
} catch (KeyStoreException e) {
throw new APIApplicationServicesException("Failed loading the keystore.", e);
} catch (NoSuchAlgorithmException e) {
throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e);
} catch (KeyManagementException e) {
throw new APIApplicationServicesException("Failed setting up the ssl http client.", e);
}
>>>>>>> e76624c1de (Add exceptions)
}
@Override
public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret)
throws APIApplicationServicesException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE));
//ToDo: Remove hardcoded value
params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin"));
params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin"));
params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES));
return getToken(params, consumerKey, consumerSecret);
}
@Override
public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret)
throws APIApplicationServicesException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE));
params.add(new BasicNameValuePair(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken));
params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES));
return getToken(params, consumerKey, consumerSecret);
}
public AccessTokenInfo getToken(List<NameValuePair> nameValuePairs, String clientId, String clientSecret)
throws APIApplicationServicesException{
String response = null;
try {
URL url = new URL("https://localhost:9443/oauth2/token");
HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
HttpPost request = new HttpPost(url.toString());
request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64Encode(clientId, clientSecret));
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(request);
response = PublisherRESTAPIUtil.getResponseString(httpResponse);
if (log.isDebugEnabled()) {
log.debug(response);
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
String accessToken = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME);
if (accessToken != null && !accessToken.isEmpty()){
accessTokenInfo.setAccessToken(accessToken);
accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME));
accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN));
accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE));
accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE));
}
return accessTokenInfo;
} catch (IOException e) {
throw new APIApplicationServicesException("Error when reading the response from buffer.", e);
} catch (KeyStoreException e) {
throw new APIApplicationServicesException("Failed loading the keystore.", e);
} catch (NoSuchAlgorithmException e) {
throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e);
} catch (ParseException e) {
throw new APIApplicationServicesException("Error when parsing the response " + response, e);
} catch (KeyManagementException e) {
throw new APIApplicationServicesException("Failed setting up the ssl http client.", e);
}
}
static String getBase64Encode(String key, String value) {
return new String(Base64.encodeBase64((key + ":" + value).getBytes()));
}
=======
>>>>>>> 2855ef0a30 (change http client to okhttp)
} }

@ -125,10 +125,7 @@
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId> <artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
</dependency> <scope>provided</scope>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>

@ -25,6 +25,24 @@
<version>5.0.26-SNAPSHOT</version> <version>5.0.26-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>

Loading…
Cancel
Save