diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java deleted file mode 100644 index d628c4ce25..0000000000 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; - -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; - -public interface APIApplicationServices { - - APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; - - AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; - - AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIServicesException; - -} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java deleted file mode 100644 index c412d189c0..0000000000 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; - -import com.google.gson.Gson; -import org.json.JSONObject; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.RequestBody; -import okhttp3.Credentials; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import java.io.IOException; - -public class APIApplicationServicesImpl implements APIApplicationServices { - - private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); - private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); - private static final Gson gson = new Gson(); - private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - String msg = null; - APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). - getAPIManagerConfigurationService().getAPIManagerConfiguration(); - - @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException { - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String serverUser = getScopePublishUserName(tenantDomain); - String serverPassword = getScopePublishUserPassword(tenantDomain); - - String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); - - 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", serverUser); - jsonObject.put("saasApp", true); - - RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); - Request request = new Request.Builder() - .url(applicationEndpoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(serverUser, serverPassword)) - .post(requestBody) - .build(); - - try { - 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"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - @Override - public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) - throws APIServicesException { - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String userName = getScopePublishUserName(tenantDomain); - String userPassword = getScopePublishUserPassword(tenantDomain); - - JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); - params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, userName); - params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, userPassword); - params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); - return getToken(params, consumerKey, consumerSecret); - } - - @Override - public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, - String consumerSecret) throws APIServicesException { - JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); - 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 APIServicesException { - - String tokenEndPoint = config.getFirstProperty(Constants.TOKE_END_POINT); - - RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); - Request request = new Request.Builder() - .url(tokenEndPoint) - .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"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - private String getScopePublishUserName(String tenantDomain) { - if(APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { - return config.getFirstProperty(Constants.SERVER_USER); - } else { - return Constants.SCOPE_PUBLISH_RESERVED_USER_NAME + "@" + tenantDomain; - } - } - - private String getScopePublishUserPassword(String tenantDomain) { - if(APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { - return config.getFirstProperty(Constants.SERVER_PASSWORD); - } else { - return Constants.SCOPE_PUBLISH_RESERVED_USER_PASSWORD; - } - } -} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index a263ad2d63..1d15c9f9d8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -18,98 +18,77 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import org.json.JSONObject; import java.util.List; public interface PublisherRESTAPIServices { - Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Scope[] getScopes() throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean isSharedScopeNameExists(String key) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addNewSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean updateSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deleteSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo getApi(String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; - APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo[] getApis() throws APIServicesException, BadRequestException, UnexpectedResponseException; - APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo addAPI(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean updateApi(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String asyncApiDefinition) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean saveAsyncApiDefinition(String uuid, String asyncApiDefinition) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + MediationPolicy[] getAllApiSpecificMediationPolicies(String apiUuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String action) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean changeLifeCycleStatus(String uuid, String action) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - Boolean deploymentStatus) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIRevision[] getAPIRevisions(String uuid, Boolean deploymentStatus) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIRevision addAPIRevision(APIRevision apiRevision) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String apiRevisionId, List apiRevisionDeploymentList) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deployAPIRevision(String uuid, String apiRevisionId, + List apiRevisionDeploymentList) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevisionDeployment, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean undeployAPIRevisionDeployment(APIRevision apiRevisionDeployment, String uuid) throws APIServicesException + , BadRequestException, UnexpectedResponseException; - boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteAPIRevision(APIRevision apiRevision, String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Documentation[] getDocumentations(String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String documentID) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteDocumentations(String uuid, String documentID) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Documentation documentation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Documentation addDocumentation(String uuid, Documentation documentation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid, String docId, String docContent) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addDocumentationContent(String apiUuid, String docId, String docContent) throws APIServicesException, + BadRequestException, UnexpectedResponseException; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java index e322ae0307..acc042d1e5 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java @@ -19,16 +19,19 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherRESTAPIClientResponse; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.PublisherRESTAPIOauthClientException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import okhttp3.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.PublisherRESTAPIOauthClient; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.Request; import okhttp3.Request.Builder; +import okhttp3.RequestBody; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,12 +39,10 @@ import org.apache.commons.ssl.Base64; import org.json.JSONArray; import org.json.JSONObject; -import java.io.IOException; import java.util.List; public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServicesImpl.class); - private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final Gson gson = new Gson(); private static final String host = System.getProperty(Constants.IOT_CORE_HOST); @@ -50,48 +51,26 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { + Constants.COLON + port; @Override - public Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public Scope[] getScopes() throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() .url(getAllScopesUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); - try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray scopeList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(scopeList.toString(), Scope[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getScopes(apiApplicationKey, refreshedAccessToken); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray scopeList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(scopeList.toString(), Scope[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving scopes"; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean isSharedScopeNameExists(String key) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, Constants.EMPTY_STRING); @@ -99,46 +78,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(getScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .head() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return isSharedScopeNameExists(apiApplicationKey, refreshedAccessToken, key); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else if (HttpStatus.SC_NOT_FOUND == response.code()) { - String msg = "Shared scope key not found : " + key; - if (log.isDebugEnabled()) { - log.debug(msg); - } - return false; - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while checking if shared scope exists for the key : " + key; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean addNewSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; @@ -159,41 +113,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addNewSharedScopeEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addNewSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.message(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding new shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean updateSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); @@ -214,41 +149,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while updating shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); JSONArray bindings = new JSONArray(); @@ -268,120 +184,60 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIInfo getApi(String apiUuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid; Request request = new Request.Builder() .url(getAllApi) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return gson.fromJson(response.body().string(), APIInfo.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getApi(apiApplicationKey, refreshedAccessToken, apiUuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIInfo.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving API for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public APIInfo[] getApis() throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllApis = endPointPrefix + Constants.GET_ALL_APIS; Request request = new Request.Builder() .url(getAllApis) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(apiList.toString(), APIInfo[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getApis(apiApplicationKey, refreshedAccessToken); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray apiList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(apiList.toString(), APIInfo[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving APIs"; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIInfo addAPI(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; @@ -406,7 +262,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy()); payload.put("authorizationHeader", api.getAuthorizationHeader()); payload.put("visibility", api.getVisibility()); - payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : "")); + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? + api.getSubscriptionAvailability() : "")); //Lists if (api.getTransport() != null) { @@ -474,54 +331,42 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } //objects - payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null)); - payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); - payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); + payload.put("monetization", (api.getMonetization() != null ? + new JSONObject(gson.toJson(api.getMonetization())) : null)); + payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? + new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); + payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? + new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null)); payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null)); - payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null)); - payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null)); - payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null)); - payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); + payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? + api.getEndpointImplementationType() : null)); + payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? + api.getThreatProtectionPolicies() : null)); + payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) + : null)); + payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? + new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addAPIEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return gson.fromJson(response.body().string(), APIInfo.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addAPI(apiApplicationKey, refreshedAccessToken, api); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response status : " + response.code() + " Response message : " + response.message(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIInfo.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API for API name : " + api.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean updateApi(APIInfo api) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); @@ -546,7 +391,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy()); payload.put("authorizationHeader", api.getAuthorizationHeader()); payload.put("visibility", api.getVisibility()); - payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : "")); + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? + api.getSubscriptionAvailability() : "")); //Lists if (api.getTransport() != null) { @@ -614,55 +460,42 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } //objects - payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null)); - payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); - payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); + payload.put("monetization", (api.getMonetization() != null ? + new JSONObject(gson.toJson(api.getMonetization())) : null)); + payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? + new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); + payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? + new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null)); payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null)); - payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null)); - payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null)); - payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null)); - payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); + payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? + api.getEndpointImplementationType() : null)); + payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? + api.getThreatProtectionPolicies() : null)); + payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) + : null)); + payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? + new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateAPIEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return updateApi(apiApplicationKey, refreshedAccessToken, api); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while updating API for API name : " + api.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String asyncApiDefinition) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean saveAsyncApiDefinition(String uuid, String asyncApiDefinition) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String saveAsyncAPI = endPointPrefix + Constants.API_ENDPOINT + uuid + "/asyncapi"; @@ -674,33 +507,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(saveAsyncAPI) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { //Check the response - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return saveAsyncApiDefinition(apiApplicationKey, refreshedAccessToken, uuid, asyncApiDefinition); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API definition request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while saving async API definition for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -708,49 +522,27 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public MediationPolicy[] getAllApiSpecificMediationPolicies(String apiUuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/mediation-policies"; Request request = new Request.Builder() .url(getAPIMediationEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiUuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving all mediation policies for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) + public boolean addApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIMediation = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies"; @@ -764,33 +556,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Builder() .url(addAPIMediation) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API specific mediation policy for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -798,41 +571,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException { - String deleteApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); + String deleteApiMediationEndPOint = + endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); Request request = new Request.Builder() .url(deleteApiMediationEndPOint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_NO_CONTENT == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid mediation policy"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_NO_CONTENT == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting mediation policy from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -840,8 +594,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String action) + public boolean changeLifeCycleStatus(String uuid, String action) throws APIServicesException, BadRequestException, UnexpectedResponseException { String changeAPIStatusEndPoint = endPointPrefix + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid @@ -850,41 +603,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING); Request request = new Request.Builder() .url(changeAPIStatusEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return changeLifeCycleStatus(apiApplicationKey, refreshedAccessToken, uuid, action); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while changing life cycle state for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - Boolean deploymentStatus) + public APIRevision[] getAPIRevisions(String uuid, Boolean deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:" @@ -892,42 +625,23 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(getAPIRevisionsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray revisionList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(revisionList.toString(), APIRevision[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getAPIRevisions(apiApplicationKey, refreshedAccessToken, uuid, deploymentStatus); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray revisionList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(revisionList.toString(), APIRevision[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving API revisions for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIRevision addAPIRevision(APIRevision apiRevision) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; @@ -937,44 +651,26 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addNewScope) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return gson.fromJson(response.body().string(), APIRevision.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIRevision.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API revision for API UUID : " + apiRevision.getApiUUID(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String apiRevisionId, List apiRevisionDeploymentList) + public boolean deployAPIRevision(String uuid, String apiRevisionId, + List apiRevisionDeploymentList) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; + String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision" + + "?revisionId=" + apiRevisionId; APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0); JSONArray payload = new JSONArray(); @@ -987,45 +683,25 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(deployAPIRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId, - apiRevisionDeploymentList); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deploying API revision for API UUID + " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevisionDeployment, String uuid) + public boolean undeployAPIRevisionDeployment(APIRevision apiRevisionDeployment, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId=" + String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision" + + "?revisionId=" + apiRevisionDeployment.getId(); List apiRevisionDeployments = apiRevisionDeployment.getDeploymentInfo(); APIRevisionDeployment earliestDeployment = apiRevisionDeployments.get(0); @@ -1040,165 +716,86 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(undeployAPIRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return undeployAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, apiRevisionDeployment, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while undeploy an API revision from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteAPIRevision(APIRevision apiRevision, String uuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + apiRevision.getId(); Request request = new Request.Builder() .url(apiRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting an API revision from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public Documentation[] getDocumentations(String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000"; Request request = new Request.Builder() .url(getDocumentationsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray documentList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(documentList.toString(), Documentation[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getDocumentations(apiApplicationKey, refreshedAccessToken, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray documentList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(documentList.toString(), Documentation[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving documentation for API UUID " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String documentID) + public boolean deleteDocumentations(String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException { String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents/" + documentID; Request request = new Request.Builder() .url(getDocumentationsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteDocumentations(apiApplicationKey, refreshedAccessToken, uuid, documentID); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting documentation for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Documentation documentation) + public Documentation addDocumentation(String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents"; @@ -1216,44 +813,25 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(addNewScope) .addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return gson.fromJson(response.body().string(), Documentation.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addDocumentation(apiApplicationKey, refreshedAccessToken, uuid, documentation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid documentation request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), Documentation.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding documentation for API UUID " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid, String docId, String docContent) + public boolean addDocumentationContent(String apiUuid, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/documents/" + docId + "/content"; + String addDocumentationContentEndPoint = + endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/documents/" + docId + "/content"; RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -1263,33 +841,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(addDocumentationContentEndPoint) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addDocumentationContent(apiApplicationKey, refreshedAccessToken, apiUuid, docId, docContent); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid documentation request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding documentation for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java new file mode 100644 index 0000000000..d8605f411d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean; + +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; + +public class PublisherOauthApp { + private final APIApplicationKey apiApplicationKey; + private final AccessTokenInfo accessTokenInfo; + + public PublisherOauthApp(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) { + this.apiApplicationKey = apiApplicationKey; + this.accessTokenInfo = accessTokenInfo; + } + + public AccessTokenInfo getAccessTokenInfo() { + return accessTokenInfo; + } + + public APIApplicationKey getApiApplicationKey() { + return apiApplicationKey; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java new file mode 100644 index 0000000000..148d59b95a --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean; + +public class PublisherRESTAPIClientResponse { + private final int code; + private final String body; + private final boolean isSuccessful; + + public PublisherRESTAPIClientResponse(int code, String body, boolean isSuccessful) { + this.code = code; + this.body = body; + this.isSuccessful = isSuccessful; + } + + public int getCode() { + return code; + } + + public String getBody() { + return body; + } + + public boolean isSuccessful() { + return isSuccessful; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java new file mode 100644 index 0000000000..1ded2c4b80 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions; + +public class PublisherRESTAPIOauthClientException extends Exception { + private static final long serialVersionUID = -896103750774855894L; + + public PublisherRESTAPIOauthClientException(String errorMessage) { + super(errorMessage); + } + + public PublisherRESTAPIOauthClientException(String errorMessage, Throwable t) { + super(errorMessage, t); + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java index fef16ea6ee..bdb0ef44af 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; import org.apache.commons.logging.Log; @@ -48,11 +46,6 @@ public class APIManagerServiceComponent { } try { BundleContext bundleContext = componentContext.getBundleContext(); - - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); - APIManagerServiceDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); - PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); APIManagerServiceDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java index deeeaa2a06..2b021476e4 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java @@ -18,15 +18,12 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; public class APIManagerServiceDataHolder { - - private APIApplicationServices apiApplicationServices; private APIManagerConfigurationService apiManagerConfigurationService; private PublisherRESTAPIServices publisherRESTAPIServices; private RealmService realmService; @@ -37,18 +34,10 @@ public class APIManagerServiceDataHolder { private APIManagerServiceDataHolder() { } - static APIManagerServiceDataHolder getInstance() { + public static APIManagerServiceDataHolder getInstance() { return thisInstance; } - public APIApplicationServices getApiApplicationServices() { - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - public void setAPIManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { this.apiManagerConfigurationService = apiManagerConfigurationService; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java new file mode 100644 index 0000000000..eb688a7ed6 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherOauthApp; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherRESTAPIClientResponse; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.PublisherRESTAPIOauthClientException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import okhttp3.*; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class PublisherRESTAPIOauthClient { + private static final Log log = LogFactory.getLog(PublisherRESTAPIOauthClient.class); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final Gson gson = new Gson(); + private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); + private static final Map publisherOauthAppCache = new ConcurrentHashMap<>(); + private static final APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). + getAPIManagerConfigurationService().getAPIManagerConfiguration(); + + public static PublisherRESTAPIClientResponse execute(Request request) throws PublisherRESTAPIOauthClientException + , BadRequestException, + UnexpectedResponseException { + try { + request = addAuthorizationHeader(request); + try (Response response = client.newCall(request).execute()) { + if (response.isSuccessful()) { + return map(response); + } + + if (response.code() == HttpStatus.SC_UNAUTHORIZED) { + updateCacheWithNewToken(); + return execute(addAuthorizationHeader(request)); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Encountered a bad request! Request failed with code : [ " + response.code() + " ] &" + + " body : [ " + (response.body() != null ? + response.body().string() : " empty body received!") + " ]"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = + "Request failed with code : [ " + response.code() + " ] & body : [ " + + (response.body() != null ? + response.body().string() : " empty body received!") + " ]"; + log.error(msg); + throw new UnexpectedResponseException(msg); + } + } + } catch (IOException ex) { + String msg = "Error occurred while executing the request : [ " + request.method() + ":" + request.url() + + " ]"; + throw new PublisherRESTAPIOauthClientException(msg, ex); + } + } + + private static APIApplicationKey createOauthApplication() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String serverUser = getScopePublishUserName(tenantDomain); + String serverPassword = getScopePublishUserPassword(tenantDomain); + String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("callbackUrl", Constants.EMPTY_STRING); + jsonObject.put("clientName", Constants.CLIENT_NAME + "_for_" + tenantDomain); + jsonObject.put("grantType", Constants.GRANT_TYPE); + jsonObject.put("owner", serverUser); + jsonObject.put("saasApp", true); + + RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); + Request request = new Request.Builder() + .url(applicationEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(serverUser, serverPassword)) + .post(requestBody) + .build(); + + try (Response response = client.newCall(request).execute()) { + return gson.fromJson(response.body() != null ? response.body().string() : null, APIApplicationKey.class); + } + } + + private static AccessTokenInfo getAccessToken() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + APIApplicationKey apiApplicationKey = createOauthApplication(); + String userName = getScopePublishUserName(tenantDomain); + String userPassword = getScopePublishUserPassword(tenantDomain); + + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); + params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, userName); + params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, userPassword); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); + return getToken(params, apiApplicationKey); + } + + public static void updateCacheWithNewToken() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + publisherOauthAppCache.computeIfPresent(tenantDomain, (key, value) -> { + PublisherOauthApp publisherOauthApp = value; + try { + APIApplicationKey apiApplicationKey = value.getApiApplicationKey(); + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); + params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, + value.getAccessTokenInfo().getRefresh_token()); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); + AccessTokenInfo accessTokenInfo = getToken(params, apiApplicationKey); + publisherOauthApp = new PublisherOauthApp(apiApplicationKey, accessTokenInfo); + } catch (IOException e) { + log.error("Error encountered while creating publisher OAuth application", e); + } + return publisherOauthApp; + }); + } + + private static AccessTokenInfo getToken(JSONObject params, APIApplicationKey apiApplicationKey) throws IOException { + String tokenEndPoint = config.getFirstProperty(Constants.TOKE_END_POINT); + RequestBody requestBody = RequestBody.Companion.create(params.toString(), JSON); + Request request = new Request.Builder() + .url(tokenEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, + Credentials.basic(apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret())) + .post(requestBody) + .build(); + try (Response response = client.newCall(request).execute()) { + return gson.fromJson(response.body() != null ? response.body().string() : null, AccessTokenInfo.class); + } + } + + private static PublisherOauthApp getOauthApp() { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + return publisherOauthAppCache.computeIfAbsent(tenantDomain, key -> { + PublisherOauthApp publisherOauthApp = null; + try { + APIApplicationKey apiApplicationKey = createOauthApplication(); + AccessTokenInfo accessTokenInfo = getAccessToken(); + publisherOauthApp = new PublisherOauthApp(apiApplicationKey, accessTokenInfo); + } catch (IOException e) { + log.error("Error encountered while creating publisher OAuth application", e); + } + return publisherOauthApp; + }); + } + + private static Request addAuthorizationHeader(Request request) throws IOException { + return request.newBuilder().addHeader(Constants.AUTHORIZATION_HEADER_NAME, + Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + getOauthApp().getAccessTokenInfo(). + getAccess_token()).build(); + } + + private static String getScopePublishUserName(String tenantDomain) { + if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { + return config.getFirstProperty(Constants.SERVER_USER); + } else { + return Constants.SCOPE_PUBLISH_RESERVED_USER_NAME + "@" + tenantDomain; + } + } + + private static String getScopePublishUserPassword(String tenantDomain) { + if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { + return config.getFirstProperty(Constants.SERVER_PASSWORD); + } else { + return Constants.SCOPE_PUBLISH_RESERVED_USER_PASSWORD; + } + } + + private static PublisherRESTAPIClientResponse map(Response response) throws IOException { + return new PublisherRESTAPIClientResponse(response.code(), + response.body() != null ? response.body().string() : null, response.isSuccessful()); + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index cab16f8482..820f58a962 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,10 +18,8 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher; import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment; @@ -31,7 +29,6 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.MediationPolicy; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Operations; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; @@ -68,8 +65,6 @@ import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantSearchResult; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import java.io.BufferedReader; @@ -117,11 +112,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { tenants.addAll(config.getTenants().getTenant()); RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() .getOSGiService(RealmService.class, null); - - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; try { boolean tenantFound = false; @@ -158,9 +149,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { String errorMsg = "Error occurred while generating the API application"; log.error(errorMsg, e); @@ -174,7 +162,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()), apiConfig.getName(), apiConfig.getVersion()); - APIInfo[] apiList = publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo); + APIInfo[] apiList = publisherRESTAPIServices.getApis(); boolean apiFound = false; for (int i = 0; i < apiList.length; i++) { APIInfo apiObj = apiList[i]; @@ -189,8 +177,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiScope.getKey())) { Scope scope = new Scope(); scope.setDisplayName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); @@ -198,15 +185,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } APIInfo api = getAPI(apiConfig, true); - APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); + APIInfo createdAPI = publisherRESTAPIServices.addAPI(api); apiUuid = createdAPI.getId(); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - apiUuid, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiUuid, apiConfig.getAsyncApiDefinition()); } if (CREATED_STATUS.equals(createdAPI.getLifeCycleStatus())) { // if endpoint type "dynamic" and then add in sequence @@ -216,17 +202,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setType("in"); mediation.setGlobal(false); - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); } - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, - apiUuid, PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiUuid, PUBLISH_ACTION); APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Initial Revision"); - String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getId(); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiRevision).getId(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT); @@ -235,8 +218,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - apiUuid, apiRevisionId, apiRevisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiUuid, apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { @@ -259,8 +241,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (ApiScope apiScope : apiConfig.getScopes()) { // if the scope is not available as shared scope, and it is assigned to an API as a local scope // need remove the local scope and add as a shared scope - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiScope.getKey())) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { // collect scope to move as shared scopes scopesToMoveAsSharedScopes.add(apiScope); @@ -273,20 +254,19 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } } // Get existing API - APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, - apiUuid); + APIInfo existingAPI = publisherRESTAPIServices.getApi(apiUuid); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes APIInfo api = getAPI(apiConfig, false); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); + publisherRESTAPIServices.updateApi(api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { Scope scope = new Scope(); @@ -296,19 +276,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); + existingAPI = publisherRESTAPIServices.getApi(apiUuid); APIInfo api = getAPI(apiConfig, true); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); api.setId(apiUuid); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); + publisherRESTAPIServices.updateApi(api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - apiUuid, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiUuid, apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -320,45 +299,37 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setGlobal(false); MediationPolicy[] mediationList = publisherRESTAPIServices - .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiUuid); + .getAllApiSpecificMediationPolicies(apiUuid); boolean isMediationPolicyFound = false; for (int i = 0; i < mediationList.length; i++) { MediationPolicy mediationPolicy = mediationList[i]; if (apiConfig.getInSequenceName().equals(mediationPolicy.getName())) { mediation.setUuid(mediationPolicy.getId()); - publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); } } - int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, apiUuid, null).length; + int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiUuid, null).length; if (apiRevisionCount >= 5) { // This will retrieve the deployed revision - APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions( - apiApplicationKey, accessTokenInfo, apiUuid, true); + APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions(apiUuid, true); if (revisionDeploymentList.length > 0) { APIRevision latestRevisionDeployment = revisionDeploymentList[0]; - publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, - accessTokenInfo, latestRevisionDeployment, apiUuid); + publisherRESTAPIServices.undeployAPIRevisionDeployment(latestRevisionDeployment, apiUuid); } // This will retrieve the undeployed revision list - APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, apiUuid, false); + APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiUuid, false); if (undeployedRevisionList.length > 0) { APIRevision earliestUndeployRevision = undeployedRevisionList[0]; - publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, - earliestUndeployRevision, apiUuid); + publisherRESTAPIServices.deleteAPIRevision(earliestUndeployRevision, apiUuid); } } @@ -366,8 +337,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Updated Revision"); - String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getId(); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiRevision).getId(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT); @@ -377,12 +347,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - apiUuid, apiRevisionId, apiRevisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiUuid, apiRevisionId, apiRevisionDeploymentList); if (CREATED_STATUS.equals(existingAPI.getLifeCycleStatus())) { - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, - apiUuid, PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiUuid, PUBLISH_ACTION); } } } @@ -412,26 +380,23 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setOtherTypeName(null); - Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiApplicationKey, - accessTokenInfo, apiUuid); + Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiUuid); if (documentList.length > 0) { for (int i = 0; i < documentList.length; i++) { Documentation existingDoc = documentList[i]; if (existingDoc.getName().equals(apiConfig.getApiDocumentationName()) && existingDoc.getType().equals(Documentation.DocumentationType.HOWTO.name())) { - publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, - apiUuid, existingDoc.getDocumentId()); + publisherRESTAPIServices.deleteDocumentations(apiUuid, existingDoc.getDocumentId()); } } } else { log.info("There is no any existing api documentation."); } - Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, - apiUuid, apiDocumentation); + Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiUuid, apiDocumentation); - publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid, + publisherRESTAPIServices.addDocumentationContent(apiUuid, createdDoc.getDocumentId(), docContent); } @@ -461,7 +426,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); for (String tenantDomain : tenants) { @@ -470,16 +434,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - APIApplicationKey apiApplicationKey = - apiApplicationServices.createAndRetrieveApplicationCredentials(); - AccessTokenInfo accessTokenInfo = - apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); Scope scope = new Scope(); for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - defaultPermission.getScopeMapping().getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(defaultPermission.getScopeMapping().getKey())) { ScopeMapping scopeMapping = defaultPermission.getScopeMapping(); List bindings = new ArrayList<>( @@ -489,7 +447,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(scopeMapping.getName()); scope.setDisplayName(scopeMapping.getName()); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } } catch (BadRequestException | UnexpectedResponseException | APIServicesException e) { @@ -511,12 +469,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { WebappPublisherConfig config = WebappPublisherConfig.getInstance(); List tenants = new ArrayList<>(Collections.singletonList(APIConstants.SUPER_TENANT_DOMAIN)); tenants.addAll(config.getTenants().getTenant()); - - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; UserStoreManager userStoreManager; String fileName = null; @@ -526,9 +480,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { String errorMsg = "Error occurred while generating the API application"; log.error(errorMsg, e); @@ -599,7 +550,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } //Set scope details which related to the scope key - Scope[] scopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] scopes = publisherRESTAPIServices.getScopes(); for (int i = 0; i < scopes.length; i++) { Scope relatedScope = scopes[i]; if (relatedScope.getName().equals(scopeMapping[2].toString())) { @@ -611,13 +562,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { } scope.setBindings(rolesList); - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { - publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); + if (publisherRESTAPIServices.isSharedScopeNameExists(scope.getName())) { + publisherRESTAPIServices.updateSharedScope(scope); // todo: permission changed in update path, is not handled yet. } else { // This scope doesn't have an api attached. log.warn(scope.getName() + " not available as shared, add as new scope"); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); // add permission if not exist try { PermissionUtils.putPermission(permission); @@ -661,15 +612,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { @Override public void updateScopeRoleMapping(String roleName, String[] permissions, String[] removedPermissions) throws APIManagerPublisherException { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; + try { APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { String errorMsg = "Error occurred while generating the API application"; log.error(errorMsg, e); @@ -678,14 +624,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { try { - Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] scopeList = publisherRESTAPIServices.getScopes(); Map permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); if (permissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, permissions, permScopeMap, false); + updateScopes(roleName, publisherRESTAPIServices, scopeList, permissions, permScopeMap, false); } if (removedPermissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, removedPermissions, permScopeMap, true); + updateScopes(roleName, publisherRESTAPIServices, scopeList, removedPermissions, permScopeMap, true); } try { @@ -717,17 +663,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { * * @param roleName Role Name * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} - * @param apiApplicationKey {@link APIApplicationKey} - * @param accessTokenInfo {@link AccessTokenInfo} * @param scopeList scope list returning from APIM * @param permissions List of permissions * @param permScopeMap Permission Scope map * @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false. * @throws APIManagerPublisherException If the method receives invalid permission to update. */ - private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, - APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - Scope[] scopeList, String[] permissions, Map permScopeMap, boolean removingPermissions ) + private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, Scope[] scopeList, String[] permissions, Map permScopeMap, boolean removingPermissions ) throws APIManagerPublisherException { for (String permission : permissions) { String scopeValue = permScopeMap.get(permission); @@ -765,8 +707,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setBindings(existingRoleList); try { - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { - publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); + if (publisherRESTAPIServices.isSharedScopeNameExists(scope.getName())) { + publisherRESTAPIServices.updateSharedScope(scope); } else { // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list log.warn(scope.getName() + " not available as shared scope"); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index d00f50e35f..4457be5fea 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; @@ -49,7 +48,6 @@ public class APIPublisherDataHolder { private boolean isServerStarted; private Stack unpublishedApis = new Stack<>(); private Map permScopeMapping; - private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; private MetadataManagementService metadataManagementService; @@ -160,14 +158,6 @@ public class APIPublisherDataHolder { this.permScopeMapping = permScopeMapping; } - public APIApplicationServices getApiApplicationServices() { - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - public PublisherRESTAPIServices getPublisherRESTAPIServices() { return publisherRESTAPIServices; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 62684c2215..015fc69e9a 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever; @@ -49,12 +48,6 @@ import java.util.HashMap; * policy="dynamic" * bind="setRegistryService" * unbind="unsetRegistryService" - * @scr.reference name="APIM.application.service" - * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices" - * cardinality="1..1" - * policy="dynamic" - * bind="setAPIApplicationServices" - * unbind="unsetAPIApplicationServices" * @scr.reference name="APIM.publisher.service" * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices" * cardinality="1..1" @@ -144,20 +137,6 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRegistryService(null); } - protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { - if (log.isDebugEnabled()) { - log.debug("Setting DCR REST API Service"); - } - APIPublisherDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); - } - - protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { - if (log.isDebugEnabled()) { - log.debug("Unsetting DCR REST API Service"); - } - APIPublisherDataHolder.getInstance().setApiApplicationServices(null); - } - protected void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { if (log.isDebugEnabled()) { log.debug("Setting APIM Publisher REST API Service"); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java index 48d573a5fa..db370f4d9c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; @@ -98,7 +97,6 @@ public class DeviceManagementDataHolder { private WhiteLabelManagementService whiteLabelManagementService; private TraccarManagementService traccarManagementService; private DeviceStatusManagementService deviceStatusManagementService; - private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( @@ -416,23 +414,6 @@ public class DeviceManagementDataHolder { this.traccarManagementService = traccarManagementService; } - /** - * Retrieves the Dynamic Client Registration REST API Service instance from OSGI service context. - * @return {@link APIApplicationServices} Dynamic Client Registration REST API Service - */ - public APIApplicationServices getApiApplicationServices() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - apiApplicationServices = (APIApplicationServices) ctx.getOSGiService(APIApplicationServices.class, null); - if (apiApplicationServices == null) { - throw new IllegalStateException("Dynamic Client Registration REST API Service was not initialized."); - } - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - /** * Retrieves the API Manager Publisher REST API Service instance from OSGI service context. * @return {@link PublisherRESTAPIServices} API Manager Publisher REST API Service diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java index eb5fe919d2..4189314ec1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java @@ -18,12 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; @@ -46,7 +43,6 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.ArrayList; import java.util.Arrays; @@ -163,18 +159,11 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser return; } - APIApplicationServices apiApplicationServices = DeviceManagementDataHolder.getInstance().getApiApplicationServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; - try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { msg = "Error occurred while generating the API application for tenant: '" + tenantDomain + "'."; log.error(msg, e); @@ -183,14 +172,14 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser try { PublisherRESTAPIServices publisherRESTAPIServices = DeviceManagementDataHolder.getInstance().getPublisherRESTAPIServices(); - Scope[] superTenantScopes = getAllScopesFromSuperTenant(apiApplicationServices, publisherRESTAPIServices); + Scope[] superTenantScopes = getAllScopesFromSuperTenant(publisherRESTAPIServices); if (superTenantScopes != null) { if (log.isDebugEnabled()) { log.debug("Number of super tenant scopes already published - " + superTenantScopes.length); } - Scope[] subTenantScopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] subTenantScopes = publisherRESTAPIServices.getScopes(); if (subTenantScopes.length > 0) { // If there is already existing scopes on the sub tenant space then do a comparison with the @@ -230,8 +219,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser if (log.isDebugEnabled()) { log.debug("Starting to add new/updated shared scopes to the tenant: '" + tenantDomain + "'."); } - publishSharedScopes(missingScopes, publisherRESTAPIServices, apiApplicationKey, - accessTokenInfo); + publishSharedScopes(missingScopes, publisherRESTAPIServices); } for (Scope subTenantScope : subTenantScopes) { @@ -261,10 +249,9 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser log.debug("Starting to delete shared scopes from the tenant: '" + tenantDomain + "'."); } for (Scope deletedScope : deletedScopes) { - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - deletedScope.getName())) { + if (publisherRESTAPIServices.isSharedScopeNameExists(deletedScope.getName())) { Scope scope = createScopeObject(deletedScope); - publisherRESTAPIServices.deleteSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.deleteSharedScope(scope); } } } @@ -277,8 +264,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser log.debug("Starting to publish shared scopes to newly created tenant: '" + tenantDomain + "'."); } - publishSharedScopes(Arrays.asList(superTenantScopes), publisherRESTAPIServices, - apiApplicationKey, accessTokenInfo); + publishSharedScopes(Arrays.asList(superTenantScopes), publisherRESTAPIServices); updatePermScopeMetaData(superTenantPermScopeMapping, metadataManagementService); } } else { @@ -367,15 +353,13 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser /** * Get all the scopes from the super tenant space - * @param apiApplicationServices {@link APIApplicationServices} is used to create an OAuth application and retrieve client ID and secret * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to get all scopes under a given tenant using client credentials * @return array of {@link Scope} * @throws BadRequestException if an invalid request is sent to the API Manager Publisher REST API Service * @throws UnexpectedResponseException if an unexpected response is received from the API Manager Publisher REST API Service * @throws TenantManagementException if an error occurred while processing the request sent to API Manager Publisher REST API Service */ - private Scope[] getAllScopesFromSuperTenant(APIApplicationServices apiApplicationServices, - PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, + private Scope[] getAllScopesFromSuperTenant(PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, UnexpectedResponseException, TenantManagementException { try { @@ -383,10 +367,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser // in order to see if any new scopes were added or deleted PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - APIApplicationKey superTenantApiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - AccessTokenInfo superTenantAccessToken = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - superTenantApiApplicationKey.getClientId(), superTenantApiApplicationKey.getClientSecret()); - return publisherRESTAPIServices.getScopes(superTenantApiApplicationKey, superTenantAccessToken); + return publisherRESTAPIServices.getScopes(); } catch (APIServicesException e) { msg = "Error occurred while retrieving access token from super tenant"; log.error(msg, e); @@ -399,22 +380,18 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser /** * Add shared scopes to the tenant space. * @param scopeList {@link List} of {@link Scope} - * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to add shared scopes to a given tenant using client credentials - * @param apiApplicationKey {@link APIApplicationKey} contains client credentials of the OAuth application - * @param accessTokenInfo {@link AccessTokenInfo} contains token information generated from the client credentials + * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to add shared scopes to a given tenant using client credential * @throws BadRequestException if an invalid request is sent to the API Manager Publisher REST API Service * @throws UnexpectedResponseException if an unexpected response is received from the API Manager Publisher REST API Service * @throws APIServicesException if an error occurred while processing the request sent to API Manager Publisher REST API Service */ - private void publishSharedScopes (List scopeList, PublisherRESTAPIServices publisherRESTAPIServices, - APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + private void publishSharedScopes (List scopeList, PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, UnexpectedResponseException, APIServicesException { for (Scope tenantScope : scopeList) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - tenantScope.getName())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(tenantScope.getName())) { Scope scope = createScopeObject(tenantScope); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } }