change http client to okhttp

vpp-v2
Pasindu Rupasinghe 1 year ago
parent f1120baec3
commit 0d70576401

@ -79,8 +79,13 @@
<artifactId>feign-okhttp</artifactId>
</dependency>
<dependency>
<<<<<<< HEAD
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
=======
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
>>>>>>> 2855ef0a30 (change http client to okhttp)
</dependency>
</dependencies>
@ -110,7 +115,6 @@
</Export-Package>
<Import-Package>
javax.net.ssl,
<!-- javax.xml.bind,-->
org.apache.commons.logging,
org.apache.http;version="${httpclient.version.range}",
org.apache.http.client;version="${httpclient.version.range}",
@ -123,17 +127,12 @@
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
<!-- org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",-->
<!-- org.wso2.carbon.utils,-->
org.wso2.carbon.core,
org.apache.commons.ssl,
<!-- org.json.simple,-->
<!-- org.json.simple.parser,-->
<!-- org.apache.http.client.entity,-->
<!-- org.apache.http.message,-->
org.apache.commons.httpclient,
org.wso2.carbon.apimgt.api.model,
okhttp3.*
okhttp3.*,
org.json
</Import-Package>
</instructions>
</configuration>

@ -3,11 +3,10 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api;
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.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException;
public interface APIApplicationServices {
APIApplicationKey createAndRetrieveApplicationCredentials() throws BadRequestException, APIApplicationServicesException;
APIApplicationKey createAndRetrieveApplicationCredentials() throws APIApplicationServicesException;
AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIApplicationServicesException;
AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIApplicationServicesException;

@ -1,48 +1,109 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api;
import com.google.gson.JsonObject;
import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile;
import com.google.gson.Gson;
import org.json.JSONObject;
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.AccessTokenInfo;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil;
import okhttp3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.ssl.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class APIApplicationServicesImpl implements APIApplicationServices {
private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class);
<<<<<<< HEAD
private static final OkHttpClient client = getOkHttpClient();
private static final Gson gson = new Gson();
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String msg = null;
// private ApiApplicationConfigurations ApplicationConfig = null;
private static OkHttpClient getOkHttpClient() {
@Override
public APIApplicationKey createAndRetrieveApplicationCredentials()
throws APIApplicationServicesException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("callbackUrl", Constants.EMPTY_STRING);
jsonObject.put("clientName",Constants.CLIENT_NAME);
jsonObject.put("grantType",Constants.GRANT_TYPE);
jsonObject.put("owner",Constants.OWNER);
jsonObject.put("saasApp",true);
RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON);
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();
return gson.fromJson(response.body().string(), APIApplicationKey.class);
} catch (IOException e) {
msg = "Error occurred while processing the response";
throw new APIApplicationServicesException(msg);
}
}
@Override
public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret)
throws APIApplicationServicesException {
JSONObject params = new JSONObject();
params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.PASSWORD_GRANT_TYPE);
//ToDo: Remove hardcoded value
params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME,"admin");
params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD,"admin");
params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES);
return getToken(params, consumerKey, consumerSecret);
}
@Override
public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret)
throws APIApplicationServicesException {
JSONObject params = new JSONObject();
params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.REFRESH_TOKEN_GRANT_TYPE);
//ToDo: Remove hardcoded value
params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken);
params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES);
return getToken(params, consumerKey, consumerSecret);
}
public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret)
throws APIApplicationServicesException{
RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON);
//application/x-www-form-urlencoded
String keyManagerEndpoint = "https://localhost:9443/oauth2/token";
Request request = new Request.Builder()
.url(keyManagerEndpoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret))
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
return gson.fromJson(response.body().string(), AccessTokenInfo.class);
} catch (IOException e) {
msg = "Error occurred while processing the response";
throw new APIApplicationServicesException(msg);
}
}
protected static OkHttpClient getOkHttpClient() {
X509TrustManager trustAllCerts = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
@ -91,6 +152,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
}
}
<<<<<<< HEAD
@Override
public APIApplicationKey createAndRetrieveApplicationCredentials()
throws APIApplicationServicesException, BadRequestException {
@ -285,4 +347,6 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
static String getBase64Encode(String key, String value) {
return new String(Base64.encodeBase64((key + ":" + value).getBytes()));
}
=======
>>>>>>> 2855ef0a30 (change http client to okhttp)
}

@ -1,159 +0,0 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
public class PublisherAPIServiceStartupHandler implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(PublisherAPIServiceStartupHandler.class);
private PublisherRESTAPIServices publisherRESTAPIServices;
private AccessTokenInfo accessTokenInfo;
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
// String cid = null;
// String cS = null;
// String token = null;
// AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
//
// 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.setOwner(Constants.OWNER);
// registrationProfile.setGrantType(Constants.GRANT_TYPE);
// registrationProfile.setIsSaasApp(true);
//
// String jsonString = registrationProfile.toJSON();
// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
// request.setEntity(entity);
//
// String basicAuth = PublisherRESTAPIServices.getBase64Encode("admin", "admin");
//
// request.setHeader("Authorization", "Basic " + basicAuth);
// request.setHeader("Content-Type", "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);
// String clientId = (String) jsonPayload.get(Constants.CLIENT_ID);
// String clientSecret = (String) jsonPayload.get(Constants.CLIENT_SECRET);
// cid = clientId;
// cS = clientSecret;
// }
// } catch (ParseException e) {
// throw new RuntimeException(e);
// }
//
// System.out.println(response);
// }
// System.out.println(httpResponse.getStatusLine().getStatusCode());
//
//
// } catch (IOException | NoSuchAlgorithmException | KeyStoreException |
// KeyManagementException e) {
// log.error("failed to call http client.", e);
// }
//
//
// String response = null;
//
// List<NameValuePair> params = new ArrayList<>();
// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE));
// 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));
// try {
// URL url = new URL("https://localhost:9443/oauth2/token");
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpPost request = new HttpPost(url.toString());
//
// request.addHeader("Authorization", "Basic " + PublisherRESTAPIServices.getBase64Encode(cid, cS));
// request.addHeader("Content-Type", "application/x-www-form-urlencoded");
// request.setEntity(new UrlEncodedFormEntity(params));
// HttpResponse httpResponse = httpclient.execute(request);
// response = PublisherRESTAPIUtil.getResponseString(httpResponse);
// JSONParser jsonParser = new JSONParser();
// JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME);
// if (token != null && !token.isEmpty()){
// accessTokenInfo.setRefreshToken(token);
// 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));
// }
// System.out.println(accessTokenInfo);
//
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException |
// KeyManagementException| ParseException e) {
// throw new RuntimeException(e);
// }
//
// String key = "perm:sms-handler:view-configuration";
// String value = new String(Base64.encodeBase64((key).getBytes())).replace("=", "");
//
//
// String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + value;
// try {
// URL url = new URL(getScopeUrl);
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpHead request = new HttpHead(url.toString());
//
// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
// HttpResponse httpResponse = httpclient.execute(request);
//
// String code = String.valueOf(httpResponse.getStatusLine().getStatusCode());
// System.out.println(code);
//
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
// throw new RuntimeException(e);
// }
//
// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + "27fce6f1-6741-4ad5-b700-a56427fd3dbb";
// try {
// URL url = new URL(updateScopeUrl);
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpPut request = new HttpPut(url.toString());
//
// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
// request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
//
//
// String jsonString = "{\"name\": \"" + "name" + "\",\"displayName\": \"" + "displayname" +
// "\", \"description\": \"" + "description" + "\"," + "\"bindings\": [" +
// "\"Internal/devicemgt-user\"]}";
// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
// request.setEntity(entity);
//
// HttpResponse httpResponse = httpclient.execute(request);
// int code = httpResponse.getStatusLine().getStatusCode();
// System.out.println(code);
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
// throw new RuntimeException(e);
// }
// publisherRESTAPIServices = new PublisherRESTAPIServices();
// publisherRESTAPIServices.isSharedScopeNameExists("perm:sms-handler:view-configuration");
}
}

@ -5,111 +5,92 @@ 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.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil;
import io.entgra.devicemgt.apimgt.extension.publisher.api.util.ScopeUtils;
import okhttp3.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPut;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.ssl.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.Scope;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import static io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl.getOkHttpClient;
public class PublisherRESTAPIServices {
private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class);
private static final OkHttpClient client = getOkHttpClient();
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key)
throws APIApplicationServicesException, BadRequestException {
String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", "");
String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue;
try {
URL url = new URL(getScopeUrl);
HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
HttpHead request = new HttpHead(url.toString());
request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenInfo.getAccessToken());
HttpResponse httpResponse = httpclient.execute(request);
if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()){
Request request = new Request.Builder()
.url(getScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken())
.head()
.build();
try {
Response response = client.newCall(request).execute();
if (response.code() == HttpStatus.SC_OK){
return true;
} else if(HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()) {
}else if(HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() );
//max attempt count
return isSharedScopeNameExists(apiApplicationKey,refreshedAccessToken, key);
} else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){
String response = httpResponse.toString();
} else if (HttpStatus.SC_BAD_REQUEST == response.code()){
log.info(response);
throw new BadRequestException(response);
throw new BadRequestException(response.toString());
} else {
return false;
}
} 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);
String msg = "Error occurred while processing the response";
throw new APIApplicationServicesException(msg);
}
}
public void updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIApplicationServicesException, BadRequestException {
String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId();
try {
URL url = new URL(updateScopeUrl);
HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
HttpPut request = new HttpPut(url.toString());
request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER +
accessTokenInfo.getAccessToken());
request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON);
JSONObject setScope = new JSONObject();
setScope.put("name", scope.getKey());
setScope.put("displayName", scope.getName());
setScope.put("description", scope.getDescription());
setScope.put("bindings", scope.getRoles());
ScopeUtils setScope = new ScopeUtils();
setScope.setKey(scope.getKey());
setScope.setName(scope.getName());
setScope.setDescription(scope.getDescription());
setScope.setRoles(scope.getRoles());
String jsonString = setScope.toJSON();
StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
request.setEntity(entity);
RequestBody requestBody = RequestBody.Companion.create(setScope.toString(), JSON);
Request request = new Request.Builder()
.url(updateScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken())
.put(requestBody)
.build();
HttpResponse httpResponse = httpclient.execute(request);
if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode() && HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()){
try {
Response response = client.newCall(request).execute();
if (response.code() == HttpStatus.SC_OK) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo accessTokenInfo1 = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() );
updateSharedScope(apiApplicationKey, accessTokenInfo1, scope);
} else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){
String response = httpResponse.toString();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
log.info(response);
throw new BadRequestException(response);
throw new BadRequestException(response.toString());
} else {
return false;
}
} 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);
String msg = "Error occurred while processing the response";
throw new APIApplicationServicesException(msg);
}
}
}

@ -4,9 +4,20 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api.dto;
* This holds api application consumer id and secret.
*/
public class APIApplicationKey {
private String clientName;
private String clientId;
private String clientSecret;
private String callBackURL;
private String isSaasApplication;
private String appOwner;
private String jsonString;
private String jsonAppAttribute;
private String tokenType;
public APIApplicationKey(String clientId, String clientSecret){
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public String getClientId() {
return clientId;
@ -23,4 +34,61 @@ public class APIApplicationKey {
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCallBackURL() {
return callBackURL;
}
public void setCallBackURL(String callBackURL) {
this.callBackURL = callBackURL;
}
public String getIsSaasApplication() {
return isSaasApplication;
}
public void setIsSaasApplication(String isSaasApplication) {
this.isSaasApplication = isSaasApplication;
}
public String getAppOwner() {
return appOwner;
}
public void setAppOwner(String appOwner) {
this.appOwner = appOwner;
}
public String getJsonString() {
return jsonString;
}
public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}
public String getJsonAppAttribute() {
return jsonAppAttribute;
}
public void setJsonAppAttribute(String jsonAppAttribute) {
this.jsonAppAttribute = jsonAppAttribute;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
}

@ -24,6 +24,8 @@
*/
package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions;
import okhttp3.Response;
public class BadRequestException extends Exception {
private static final long serialVersionUID = -2387103750774855056L;

@ -0,0 +1,30 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api.internal;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices;
public class PublisherRESTAPIDataHolder {
private static final PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder();
private APIApplicationServices apiApplicationServices;
//
// private PublisherRESTAPIServices publisherRESTAPIServices;
public static PublisherRESTAPIDataHolder getInstance(){
return thisInstance;
}
public APIApplicationServices getApiApplicationServices() {
return apiApplicationServices;
}
public void setApiApplicationServices(APIApplicationServices apiApplicationServices) {
this.apiApplicationServices = apiApplicationServices;
}
// public PublisherRESTAPIServices getPublisherRESTAPIServices() {
// return publisherRESTAPIServices;
// }
// public void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) {
// this.publisherRESTAPIServices = publisherRESTAPIServices;
// }
}

@ -1,13 +1,12 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api.internal;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceStartupHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerShutdownHandler;
import org.wso2.carbon.core.ServerStartupObserver;
/**
* @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherRESTAPIServiceComponent"
@ -24,17 +23,19 @@ public class PublisherRESTAPIServiceComponent {
try {
BundleContext bundleContext = componentContext.getBundleContext();
PublisherAPIServiceStartupHandler publisherAPIServiceStartupHandler = new PublisherAPIServiceStartupHandler();
bundleContext.registerService(PublisherAPIServiceStartupHandler.class.getName(), publisherAPIServiceStartupHandler, null);
bundleContext.registerService(ServerStartupObserver.class.getName(), publisherAPIServiceStartupHandler, null);
bundleContext.registerService(ServerShutdownHandler.class.getName(), publisherAPIServiceStartupHandler, null);
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices();
bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null);
// PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices();
// bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null);
// PublisherRESTAPIDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices);
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null);
PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices);
if (log.isDebugEnabled()) {
log.debug("API Application bundle has been successfully initialized");
}
} catch (Exception e) {
throw new RuntimeException(e);
log.error("Error occurred while initializing API Application bundle", e);
}
}

@ -126,6 +126,10 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId>
</dependency>
</dependencies>
@ -171,6 +175,7 @@
org.w3c.dom,
io.entgra.devicemgt.apimgt.extension.publisher.api,
io.entgra.devicemgt.apimgt.extension.publisher.api.dto,
io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions,
org.wso2.carbon.apimgt.annotations.api,
org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model,

@ -371,12 +371,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials();
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (BadRequestException e) {
} catch (APIApplicationServicesException e) {
String errorMsg = "Error while generating application";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
} catch (APIApplicationServicesException e) {
throw new RuntimeException(e);
}
try {
@ -384,9 +382,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices();
// APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(MultitenantUtils.getTenantAwareUsername(
// PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
// .getAdminUserName()));
try {
String fileName =
@ -447,7 +442,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} catch (IOException | DirectoryIteratorException ex) {
log.error("failed to read scopes from file.", ex);
} catch (APIApplicationServicesException | BadRequestException e) {
String errorMsg = "Error while generating an OAuth token";
String errorMsg = "Error while Calling APIs";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
}

@ -19,6 +19,11 @@
package org.wso2.carbon.apimgt.webapp.publisher;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl;
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.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -53,10 +58,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
log.debug("Total number of unpublished APIs: "
+ APIPublisherDataHolder.getInstance().getUnpublishedApis().size());
}
try {
} catch (Exception e) {
throw new RuntimeException(e);
}
publisher = APIPublisherDataHolder.getInstance().getApiPublisherService();
int retryCount = 0;
while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) {

@ -25,52 +25,6 @@
<version>5.0.26-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
</dependencies>
<modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId>

Loading…
Cancel
Save