Test okhttp

ios-user-enrollment
Pasindu Rupasinghe 1 year ago
parent a9bb2fcb93
commit 8e4998ede8

@ -74,6 +74,10 @@
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -85,7 +89,7 @@
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version> <version>5.1.7</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
@ -102,7 +106,7 @@
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
javax.net.ssl, javax.net.ssl,
javax.xml.bind, <!-- javax.xml.bind,-->
org.apache.commons.logging, org.apache.commons.logging,
org.apache.http;version="${httpclient.version.range}", org.apache.http;version="${httpclient.version.range}",
org.apache.http.client;version="${httpclient.version.range}", org.apache.http.client;version="${httpclient.version.range}",
@ -115,14 +119,14 @@
org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}", org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", <!-- org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",-->
org.wso2.carbon.utils, <!-- org.wso2.carbon.utils,-->
org.wso2.carbon.core, org.wso2.carbon.core,
org.apache.commons.ssl, org.apache.commons.ssl,
org.json.simple, <!-- org.json.simple,-->
org.json.simple.parser, <!-- org.json.simple.parser,-->
org.apache.http.client.entity, <!-- org.apache.http.client.entity,-->
org.apache.http.message, <!-- org.apache.http.message,-->
org.apache.commons.httpclient, org.apache.commons.httpclient,
org.wso2.carbon.apimgt.api.model, org.wso2.carbon.apimgt.api.model,
okhttp3.* okhttp3.*

@ -1,11 +1,12 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api; package io.entgra.devicemgt.apimgt.extension.publisher.api;
import com.google.gson.JsonObject;
import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile; import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile;
import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo;
import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil;
import okhttp3.OkHttpClient; 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 org.apache.commons.ssl.Base64;
@ -22,71 +23,141 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.*;
import java.util.List;
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);
private final OkHttpClient client; private static final OkHttpClient client = getOkHttpClient();
public APIApplicationServicesImpl() { private static OkHttpClient getOkHttpClient() {
this.client = new OkHttpClient(); X509TrustManager trustAllCerts = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
};
return new OkHttpClient.Builder()
.sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
.hostnameVerifier((hostname, sslSession) -> true).build();
} }
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
return sc.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
return null;
}
}
@Override @Override
public APIApplicationKey createAndRetrieveApplicationCredentials() { public APIApplicationKey createAndRetrieveApplicationCredentials() {
try { JsonObject jsonObject = new JsonObject();
URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); jsonObject.addProperty("callbackUrl",Constants.EMPTY_STRING);
HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); jsonObject.addProperty("clientName",Constants.CLIENT_NAME);
HttpPost request = new HttpPost(url.toString()); jsonObject.addProperty("grantType",Constants.EMPTY_STRING);
jsonObject.addProperty("owner",Constants.OWNER);
jsonObject.addProperty("saasApp",true);
RegistrationProfile registrationProfile = new RegistrationProfile(); MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); RequestBody requestBody = RequestBody.create(jsonMediaType, jsonObject.toString());
registrationProfile.setClientName(Constants.CLIENT_NAME);
registrationProfile.setGrantType(Constants.GRANT_TYPE);
registrationProfile.setOwner(Constants.OWNER);
registrationProfile.setIsSaasApp(true);
String jsonString = registrationProfile.toJSON(); String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register";
StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
request.setEntity(entity);
//ToDo: Remove hardcoded value Request request = new Request.Builder()
String basicAuth = getBase64Encode("admin", "admin"); .url(keyManagerEndpoint)
request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin"))
request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); .post(requestBody)
.build();
HttpResponse httpResponse = httpclient.execute(request); try {
Response response = client.newCall(request).execute();
System.out.println(request);
System.out.println("---------------------------");
System.out.println(response);
if (httpResponse != null) { // JSONObject responseObj = new JSONObject(Objects.requireNonNull(response.body()).string());
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 | } catch (IOException e) {
KeyManagementException e) { throw new RuntimeException(e);
log.error("failed to call http client.", 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; return null;
} }

Loading…
Cancel
Save