From ac834d03595fc59132e55a67a2d1ec866a03bdd8 Mon Sep 17 00:00:00 2001 From: pasindu Date: Mon, 27 Mar 2023 21:42:25 +0530 Subject: [PATCH 01/17] Automated api calls with http client --- .../pom.xml | 148 ++++++++++++++++++ .../PublisherAPIService.java | 6 + .../PublisherAPIServiceImpl.java | 72 +++++++++ .../dto/AccessTokenInfo.java | 50 ++++++ .../PublisherAPIServiceComponent.java | 33 ++++ .../util/PublisherAPIUtil.java | 72 +++++++++ .../pom.xml | 5 + .../publisher/APIPublisherStartupHandler.java | 8 + components/apimgt-extensions/pom.xml | 19 +++ pom.xml | 5 + 10 files changed, 418 insertions(+) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml new file mode 100644 index 00000000000..adb72670cfa --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -0,0 +1,148 @@ + + + + + + + apimgt-extensions + org.wso2.carbon.devicemgt + 5.0.21-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.devicemgt.apimgt.extension.publisher.api + bundle + Entgra - Device API Management Extension Publisher API + Entgra - Device API Management Extension Publisher API + https://entgra.io + + + + org.apache.httpcomponents.wso2 + httpcore + + + org.wso2.orbit.org.apache.httpcomponents + httpclient + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Publisher API Management Bundle + + io.entgra.devicemgt.apimgt.extension.publisher.api.* + + + javax.net.ssl, + javax.xml.bind, + org.apache.commons.logging, + org.apache.http;version="${httpclient.version.range}", + org.apache.http.client;version="${httpclient.version.range}", + org.apache.http.client.methods;version="${httpclient.version.range}", + org.apache.http.conn.socket, + org.apache.http.conn.ssl, + org.apache.http.entity, + org.apache.http.impl.client, + org.apache.http.util;version="${httpclient.version.range}", + + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + com.sun.jndi.toolkit.ctx, + org.wso2.carbon.utils + + + + + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + + + + + + + + + + + true + + + \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java new file mode 100644 index 00000000000..2a377623630 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java @@ -0,0 +1,6 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +public interface PublisherAPIService { + + void registerApplication(); +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java new file mode 100644 index 00000000000..9b33fe4ab18 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java @@ -0,0 +1,72 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.StringEntity; + +import javax.xml.bind.DatatypeConverter; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +public class PublisherAPIServiceImpl implements PublisherAPIService { + private static final Log log = LogFactory.getLog(PublisherAPIServiceImpl.class); + + @Override + public void registerApplication() { + try { + HttpClient httpclient; + SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); + httpclient = org.apache.http.impl.client.HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); + + URL url =new URL("https://localhost:9443/client-registration/v0.17/register"); + HttpPost request = new HttpPost(url.toString()); + + String payload = "{\n" + + " \"callbackUrl\":\"www.google.lk\",\n" + + " \"clientName\":\"rest_api_publisher_code\",\n" + + " \"owner\":\"admin\",\n" + + " \"grantType\":\"client_credentials password refresh_token\",\n" + + " \"saasApp\":true\n" + + " }"; + + StringEntity entity = new StringEntity(payload); + request.setEntity(entity); + String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8")); + + request.setHeader("Authorization", "Basic " + encoding); + request.setHeader("Content-Type", "application/json"); + + HttpResponse httpResponse = httpclient.execute(request); + + if (httpResponse != null) { + BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); + String readLine; + String response = ""; + while (((readLine = br.readLine()) != null)) { + response += readLine; + } + System.out.println(response); + } + + System.out.println(httpResponse.getStatusLine().getStatusCode()); + + } catch (IOException | NoSuchAlgorithmException | KeyStoreException | + KeyManagementException e) { + log.error("failed to call http client.", e); + } + + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java new file mode 100644 index 00000000000..5c1487451ed --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java @@ -0,0 +1,50 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; + +public class AccessTokenInfo { + + private String tokenType; + private long expiresIn; + private String refreshToken; + private String accessToken; + private String scope; + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public long getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(long expiresIn) { + this.expiresIn = expiresIn; + } + + public String getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java new file mode 100644 index 00000000000..f7059ac20c7 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java @@ -0,0 +1,33 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; + + +import com.sun.jndi.toolkit.ctx.ComponentContext; +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIService; +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; + +import java.io.IOException; + +/** + * @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherAPIServiceComponent" + * immediate="true" + */ +public class PublisherAPIServiceComponent { + + private static Log log = LogFactory.getLog(PublisherAPIServiceComponent.class); + + protected void activate(ComponentContext componentContext) { + if (log.isDebugEnabled()) { + log.debug("Initializing publisher API extension bundle"); + } + + PublisherAPIService publisherAPIService = new PublisherAPIServiceImpl(); + + } + + protected void deactivate(ComponentContext componentContext) { + //do nothing + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java new file mode 100644 index 00000000000..028d40f1900 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java @@ -0,0 +1,72 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +public class PublisherAPIUtil { + + private static final Log log = LogFactory.getLog(PublisherAPIUtil.class); + private static final String HTTPS_PROTOCOL = "https"; + private static final String TENANT_JWT_CONFIG_LOCATION = File.separator + "jwt-config" + File.separator + "jwt.properties"; + private static final String JWT_CONFIG_FILE_NAME = "jwt.properties"; + private static final String SUPERTENANT_JWT_CONFIG_LOCATION = + CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + JWT_CONFIG_FILE_NAME; + + /** + * Return a http client instance + * + * @param protocol- service endpoint protocol http/https + * @return + */ + public static HttpClient getHttpClient(String protocol) + throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { + HttpClient httpclient; + if (HTTPS_PROTOCOL.equals(protocol)) { + SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); + httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); + } else { + httpclient = HttpClients.createDefault(); + } + return httpclient; + } + + public static String getResponseString(HttpResponse httpResponse) throws IOException { + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); + String readLine; + String response = ""; + while (((readLine = br.readLine()) != null)) { + response += readLine; + } + return response; + } finally { + EntityUtils.consumeQuietly(httpResponse.getEntity()); + if (br != null) { + try { + br.close(); + } catch (IOException e) { + log.warn("Error while closing the connection! " + e.getMessage()); + } + } + } + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 25fa414b151..fce4b944960 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -122,6 +122,10 @@ h2-database-engine test + + org.wso2.carbon.devicemgt + io.entgra.devicemgt.apimgt.extension.publisher.api + @@ -165,6 +169,7 @@ org.scannotation;version="1.0", org.scannotation.archiveiterator;version="1.0", org.w3c.dom, + io.entgra.devicemgt.apimgt.extension.publisher.api, org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index 949f16c3e9e..e491d35d6ec 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -19,6 +19,7 @@ package org.wso2.carbon.apimgt.webapp.publisher; +import io.entgra.devicemgt.apimgt.extension.publisher.api.ScopeServices; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; @@ -37,6 +38,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { private static Stack currentAPIsStack; private APIPublisherService publisher; + private ScopeServices scopeServices; @Override public void completingServerStartup() { @@ -55,6 +57,12 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { log.debug("Total number of unpublished APIs: " + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); } + + try { + scopeServices.registerApplication(); + } catch (Exception e) { + throw new RuntimeException(e); + } publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); int retryCount = 0; while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) { diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index c877688505d..968c5bb3d1f 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,6 +25,24 @@ 5.0.26-SNAPSHOT ../../pom.xml + + + org.apache.httpcomponents.wso2 + httpcore + + + org.wso2.orbit.org.apache.httpcomponents + httpclient + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + 4.0.0 apimgt-extensions @@ -40,6 +58,7 @@ org.wso2.carbon.apimgt.keymgt.extension org.wso2.carbon.apimgt.keymgt.extension.api io.entgra.device.mgt.core.apimgt.analytics.extension + io.entgra.devicemgt.apimgt.extension.publisher.api diff --git a/pom.xml b/pom.xml index b61ce5221b3..b5435d623d5 100644 --- a/pom.xml +++ b/pom.xml @@ -238,6 +238,11 @@ org.wso2.carbon.apimgt.annotations ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + io.entgra.devicemgt.apimgt.extension.publisher.api + ${carbon.device.mgt.version} + org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.oauth.extensions From a9bb2fcb93be48ac27870b74cabc15a8f18ab4d7 Mon Sep 17 00:00:00 2001 From: pasindu Date: Sun, 9 Apr 2023 14:32:17 +0530 Subject: [PATCH 02/17] Use apache http client --- .../pom.xml | 33 ++- .../APIApplicationServices.java | 13 ++ .../APIApplicationServicesImpl.java | 151 ++++++++++++++ .../PublisherAPIService.java | 6 - .../PublisherAPIServiceImpl.java | 72 ------- .../PublisherAPIServiceStartupHandler.java | 159 ++++++++++++++ .../PublisherRESTAPIServices.java | 197 ++++++++++++++++++ .../bean/RegistrationProfile.java | 82 ++++++++ .../constants/Constants.java | 52 +++++ .../dto/APIApplicationKey.java | 26 +++ .../dto/AccessTokenInfo.java | 3 + .../PublisherAPIServiceComponent.java | 33 --- .../PublisherRESTAPIServiceComponent.java | 44 ++++ ...APIUtil.java => PublisherRESTAPIUtil.java} | 9 +- .../util/ScopeUtils.java | 59 ++++++ .../pom.xml | 1 + .../publisher/APIPublisherServiceImpl.java | 45 ++-- .../publisher/APIPublisherStartupHandler.java | 7 - .../lifecycle/util/AnnotationProcessor.java | 4 +- components/apimgt-extensions/pom.xml | 28 +++ 20 files changed, 880 insertions(+), 144 deletions(-) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java rename components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/{PublisherAPIUtil.java => PublisherRESTAPIUtil.java} (83%) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml index adb72670cfa..6601a501126 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -58,6 +58,22 @@ org.eclipse.osgi org.eclipse.osgi.services + + org.wso2.carbon + org.wso2.carbon.core + + + com.googlecode.json-simple.wso2 + json-simple + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + com.squareup.okhttp3 + okhttp + @@ -77,7 +93,11 @@ ${project.artifactId} ${carbon.device.mgt.version} Publisher API Management Bundle + + io.entgra.devicemgt.apimgt.extension.publisher.api.internal + + !io.entgra.devicemgt.apimgt.extension.publisher.api.internal, io.entgra.devicemgt.apimgt.extension.publisher.api.* @@ -95,8 +115,17 @@ org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - com.sun.jndi.toolkit.ctx, - org.wso2.carbon.utils + org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", + org.wso2.carbon.utils, + org.wso2.carbon.core, + org.apache.commons.ssl, + org.json.simple, + org.json.simple.parser, + org.apache.http.client.entity, + org.apache.http.message, + org.apache.commons.httpclient, + org.wso2.carbon.apimgt.api.model, + okhttp3.* diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java new file mode 100644 index 00000000000..342f5aa9549 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java @@ -0,0 +1,13 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; + +public interface APIApplicationServices { + + APIApplicationKey createAndRetrieveApplicationCredentials(); + + AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret); + AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret); + +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java new file mode 100644 index 00000000000..06c1fe97bff --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java @@ -0,0 +1,151 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile; +import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; +import okhttp3.OkHttpClient; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.ssl.Base64; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicNameValuePair; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; + +public class APIApplicationServicesImpl implements APIApplicationServices { + + private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); + private final OkHttpClient client; + + public APIApplicationServicesImpl() { + this.client = new OkHttpClient(); + } + + @Override + public APIApplicationKey createAndRetrieveApplicationCredentials() { + + try { + URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); + HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); + HttpPost request = new HttpPost(url.toString()); + + RegistrationProfile registrationProfile = new RegistrationProfile(); + registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); + registrationProfile.setClientName(Constants.CLIENT_NAME); + registrationProfile.setGrantType(Constants.GRANT_TYPE); + registrationProfile.setOwner(Constants.OWNER); + registrationProfile.setIsSaasApp(true); + + String jsonString = registrationProfile.toJSON(); + StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); + request.setEntity(entity); + + //ToDo: Remove hardcoded value + String basicAuth = getBase64Encode("admin", "admin"); + request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); + request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); + + HttpResponse httpResponse = httpclient.execute(request); + + if (httpResponse != null) { + String response = PublisherRESTAPIUtil.getResponseString(httpResponse); + try { + if(response != null){ + JSONParser jsonParser = new JSONParser(); + JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); + APIApplicationKey apiApplicationKey = new APIApplicationKey(); + apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); + apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); + return apiApplicationKey; + } else { + return null; + } + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + } catch (IOException | NoSuchAlgorithmException | KeyStoreException | + KeyManagementException e) { + log.error("failed to call http client.", e); + } + return null; + } + + @Override + public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) { + List params = new ArrayList<>(); + params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); + //ToDo: Remove hardcoded value + params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); + params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); + params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); + return getToken(params, consumerKey, consumerSecret); + } + + @Override + public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret) { + List params = new ArrayList<>(); + params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE)); + params.add(new BasicNameValuePair(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken)); + params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); + return getToken(params, consumerKey, consumerSecret); + } + + public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) { + + try { + URL url = new URL("https://localhost:9443/oauth2/token"); + HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); + HttpPost request = new HttpPost(url.toString()); + + request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64Encode(clientId, clientSecret)); + request.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); + request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + + HttpResponse httpResponse = httpclient.execute(request); + String response = PublisherRESTAPIUtil.getResponseString(httpResponse); + if (log.isDebugEnabled()) { + log.debug(response); + } + JSONParser jsonParser = new JSONParser(); + JSONObject jsonObject = (JSONObject) jsonParser.parse(response); + AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); + String accessToken = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); + if (accessToken != null && !accessToken.isEmpty()){ + accessTokenInfo.setAccessToken(accessToken); + accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); + accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); + accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); + accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); + } + return accessTokenInfo; + + } catch (IOException | KeyStoreException | NoSuchAlgorithmException | + KeyManagementException| ParseException e) { + throw new RuntimeException(e); + } + } + + static String getBase64Encode(String key, String value) { + return new String(Base64.encodeBase64((key + ":" + value).getBytes())); + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java deleted file mode 100644 index 2a377623630..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIService.java +++ /dev/null @@ -1,6 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; - -public interface PublisherAPIService { - - void registerApplication(); -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java deleted file mode 100644 index 9b33fe4ab18..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.entity.StringEntity; - -import javax.xml.bind.DatatypeConverter; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; - -public class PublisherAPIServiceImpl implements PublisherAPIService { - private static final Log log = LogFactory.getLog(PublisherAPIServiceImpl.class); - - @Override - public void registerApplication() { - try { - HttpClient httpclient; - SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); - httpclient = org.apache.http.impl.client.HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); - - URL url =new URL("https://localhost:9443/client-registration/v0.17/register"); - HttpPost request = new HttpPost(url.toString()); - - String payload = "{\n" + - " \"callbackUrl\":\"www.google.lk\",\n" + - " \"clientName\":\"rest_api_publisher_code\",\n" + - " \"owner\":\"admin\",\n" + - " \"grantType\":\"client_credentials password refresh_token\",\n" + - " \"saasApp\":true\n" + - " }"; - - StringEntity entity = new StringEntity(payload); - request.setEntity(entity); - String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8")); - - request.setHeader("Authorization", "Basic " + encoding); - request.setHeader("Content-Type", "application/json"); - - HttpResponse httpResponse = httpclient.execute(request); - - if (httpResponse != null) { - BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); - String readLine; - String response = ""; - while (((readLine = br.readLine()) != null)) { - response += readLine; - } - System.out.println(response); - } - - System.out.println(httpResponse.getStatusLine().getStatusCode()); - - } catch (IOException | NoSuchAlgorithmException | KeyStoreException | - KeyManagementException e) { - log.error("failed to call http client.", e); - } - - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java new file mode 100644 index 00000000000..2b005b0cc0d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java @@ -0,0 +1,159 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.core.ServerStartupObserver; + +public class PublisherAPIServiceStartupHandler implements ServerStartupObserver { + + private static final Log log = LogFactory.getLog(PublisherAPIServiceStartupHandler.class); + private PublisherRESTAPIServices publisherRESTAPIServices; + private AccessTokenInfo accessTokenInfo; + + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + +// String cid = null; +// String cS = null; +// String token = null; +// AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); +// +// try { +// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPost request = new HttpPost(url.toString()); +// +// RegistrationProfile registrationProfile = new RegistrationProfile(); +// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); +// registrationProfile.setClientName(Constants.CLIENT_NAME); +// registrationProfile.setOwner(Constants.OWNER); +// registrationProfile.setGrantType(Constants.GRANT_TYPE); +// registrationProfile.setIsSaasApp(true); +// +// String jsonString = registrationProfile.toJSON(); +// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); +// request.setEntity(entity); +// +// String basicAuth = PublisherRESTAPIServices.getBase64Encode("admin", "admin"); +// +// request.setHeader("Authorization", "Basic " + basicAuth); +// request.setHeader("Content-Type", "application/json"); +// +// HttpResponse httpResponse = httpclient.execute(request); +// +// if (httpResponse != null) { +// +// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); +// try { +// if(response != null){ +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); +// String clientId = (String) jsonPayload.get(Constants.CLIENT_ID); +// String clientSecret = (String) jsonPayload.get(Constants.CLIENT_SECRET); +// cid = clientId; +// cS = clientSecret; +// } +// } catch (ParseException e) { +// throw new RuntimeException(e); +// } +// +// System.out.println(response); +// } +// System.out.println(httpResponse.getStatusLine().getStatusCode()); +// +// +// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | +// KeyManagementException e) { +// log.error("failed to call http client.", e); +// } +// +// +// String response = null; +// +// List params = new ArrayList<>(); +// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); +// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); +// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); +// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); +// try { +// URL url = new URL("https://localhost:9443/oauth2/token"); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPost request = new HttpPost(url.toString()); +// +// request.addHeader("Authorization", "Basic " + PublisherRESTAPIServices.getBase64Encode(cid, cS)); +// request.addHeader("Content-Type", "application/x-www-form-urlencoded"); +// request.setEntity(new UrlEncodedFormEntity(params)); +// HttpResponse httpResponse = httpclient.execute(request); +// response = PublisherRESTAPIUtil.getResponseString(httpResponse); +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonObject = (JSONObject) jsonParser.parse(response); +// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); +// if (token != null && !token.isEmpty()){ +// accessTokenInfo.setRefreshToken(token); +// accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); +// accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); +// accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); +// accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); +// } +// System.out.println(accessTokenInfo); +// +// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | +// KeyManagementException| ParseException e) { +// throw new RuntimeException(e); +// } +// +// String key = "perm:sms-handler:view-configuration"; +// String value = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); +// +// +// String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + value; +// try { +// URL url = new URL(getScopeUrl); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpHead request = new HttpHead(url.toString()); +// +// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); +// HttpResponse httpResponse = httpclient.execute(request); +// +// String code = String.valueOf(httpResponse.getStatusLine().getStatusCode()); +// System.out.println(code); +// +// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { +// throw new RuntimeException(e); +// } +// +// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + "27fce6f1-6741-4ad5-b700-a56427fd3dbb"; +// try { +// URL url = new URL(updateScopeUrl); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPut request = new HttpPut(url.toString()); +// +// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); +// request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); +// +// +// String jsonString = "{\"name\": \"" + "name" + "\",\"displayName\": \"" + "displayname" + +// "\", \"description\": \"" + "description" + "\"," + "\"bindings\": [" + +// "\"Internal/devicemgt-user\"]}"; +// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); +// request.setEntity(entity); +// +// HttpResponse httpResponse = httpclient.execute(request); +// int code = httpResponse.getStatusLine().getStatusCode(); +// System.out.println(code); +// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { +// throw new RuntimeException(e); +// } + + +// publisherRESTAPIServices = new PublisherRESTAPIServices(); +// publisherRESTAPIServices.isSharedScopeNameExists("perm:sms-handler:view-configuration"); + + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java new file mode 100644 index 00000000000..335680a84dd --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java @@ -0,0 +1,197 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; +import io.entgra.devicemgt.apimgt.extension.publisher.api.util.ScopeUtils; +import org.apache.axis2.databinding.types.xsd._boolean; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.http.HttpHeaders; +import org.apache.http.client.methods.HttpHead; +import org.apache.http.client.methods.HttpPut; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.ssl.Base64; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.wso2.carbon.apimgt.api.model.Scope; + +import java.io.IOException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; + +public class PublisherRESTAPIServices { + private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); + +// private String clientId; +// private String clientSecret; +// private String accessToken; +// +// public AccessTokenInfo registerApplication() { +// +// try { +// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPost request = new HttpPost(url.toString()); +// +// RegistrationProfile registrationProfile = new RegistrationProfile(); +// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); +// registrationProfile.setClientName(Constants.CLIENT_NAME); +// registrationProfile.setGrantType(Constants.GRANT_TYPE); +// registrationProfile.setOwner(Constants.OWNER); +// registrationProfile.setIsSaasApp(true); +// +// String jsonString = registrationProfile.toJSON(); +// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); +// request.setEntity(entity); +// +// String basicAuth = getBase64Encode("admin", "admin"); +// +// request.setHeader("Authorization", "Basic " + basicAuth); +// request.setHeader("Content-Type", "application/json"); +// +// HttpResponse httpResponse = httpclient.execute(request); +// +// if (httpResponse != null) { +// +// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); +// try { +// if(response != null){ +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); +// clientId = (String) jsonPayload.get(Constants.CLIENT_ID); +// clientSecret = (String) jsonPayload.get(Constants.CLIENT_SECRET); +// } +// } catch (ParseException e) { +// throw new RuntimeException(e); +// } +// System.out.println(response); +// } +// System.out.println(httpResponse.getStatusLine().getStatusCode()); +// +// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | +// KeyManagementException e) { +// log.error("failed to call http client.", e); +// } +// return getAccessTokenFromRegisteredApplication(clientId, clientSecret); +// +// } +// +// public AccessTokenInfo getAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) { +// List params = new ArrayList<>(); +// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); +// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); +// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); +// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); +// return getToken(params, consumerKey, consumerSecret); +// } +// +// public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) { +// +// String token = null; +// String response = null; +// try { +// URL url = new URL("https://localhost:9443/oauth2/token"); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPost request = new HttpPost(url.toString()); +// +// request.addHeader("Authorization", "Basic " + getBase64Encode(clientId, clientSecret)); +// request.addHeader("Content-Type", "application/x-www-form-urlencoded"); +// request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); +// HttpResponse httpResponse = httpclient.execute(request); +// response = PublisherRESTAPIUtil.getResponseString(httpResponse); +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonObject = (JSONObject) jsonParser.parse(response); +// AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); +// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); +// if (token != null && !token.isEmpty()){ +// accessTokenInfo.setRefreshToken(token); +// accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); +// accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); +// accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); +// accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); +// } +// accessToken = token; +// return accessTokenInfo; +// +// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | +// KeyManagementException| ParseException e) { +// throw new RuntimeException(e); +// } +// } + + public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key){ + + String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); + String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; + try { + URL url = new URL(getScopeUrl); + HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); + HttpHead request = new HttpHead(url.toString()); + + request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenInfo.getAccessToken()); + HttpResponse httpResponse = httpclient.execute(request); + + if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()){ + return true; + } else if(HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); + return isSharedScopeNameExists(apiApplicationKey,refreshedAccessToken, key); + } else{ + return false; + } + + } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { + throw new RuntimeException(e); + } + } + + public void updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope){ + +// String keyValue = new String(Base64.encodeBase64((scope.getKey()).getBytes())).replace("=", ""); +// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; + String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); + try { + URL url = new URL(updateScopeUrl); + HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); + HttpPut request = new HttpPut(url.toString()); + + request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccessToken()); + request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); + + ScopeUtils setScope = new ScopeUtils(); + setScope.setKey(scope.getKey()); + setScope.setName(scope.getName()); + setScope.setDescription(scope.getDescription()); + setScope.setRoles(scope.getRoles()); + String jsonString = setScope.toJSON(); + StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); + request.setEntity(entity); + + HttpResponse httpResponse = httpclient.execute(request); + if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode() && HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()){ + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo accessTokenInfo1 = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); + updateSharedScope(apiApplicationKey, accessTokenInfo1, scope); + } else { + String response = httpResponse.toString(); + log.info(response); + } + + } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { + throw new RuntimeException(e); + } + } +// static String getBase64Encode(String key, String value) { +// return new String(Base64.encodeBase64((key + ":" + value).getBytes())); +// } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java new file mode 100644 index 00000000000..242788ed26e --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java @@ -0,0 +1,82 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.bean; + +/** + * This class represents the data that are required to register + * the oauth application. + */ +public class RegistrationProfile { + + private String callbackUrl; + private String clientName; + private String tokenScope; + private String owner; + private String grantType; + private String applicationType; + private boolean isSaasApp; + + private static final String TAG = RegistrationProfile.class.getSimpleName(); + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callBackUrl) { + this.callbackUrl = callBackUrl; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public String getTokenScope() { + return tokenScope; + } + + public void setTokenScope(String tokenScope) { + this.tokenScope = tokenScope; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getGrantType() { + return grantType; + } + + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + public String getApplicationType() { + return applicationType; + } + + public void setApplicationType(String applicationType) { + this.applicationType = applicationType; + } + + public boolean isSaasApp() { + return isSaasApp; + } + + public void setIsSaasApp(boolean isSaasApp) { + this.isSaasApp = isSaasApp; + } + + public String toJSON() { + String jsonString = + "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + + "\", \"saasApp\" : " + isSaasApp + " }\n"; + return jsonString; + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java new file mode 100644 index 00000000000..0144e129f10 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java @@ -0,0 +1,52 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.constants; + +public final class Constants { + + private Constants() { + } + + public static final String EMPTY_STRING = ""; + public static final String CLIENT_NAME = "rest_api_publisher_code"; + public static final String OWNER = "admin"; + public static final String GRANT_TYPE = "client_credentials password refresh_token"; + public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; + public static final String OAUTH_EXPIRES_IN = "expires_in"; + public static final String OAUTH_TOKEN_SCOPE = "scope"; + public static final String OAUTH_TOKEN_TYPE = "token_type"; + public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; + public static final String SCOPE_PARAM_NAME = "scope"; + public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage"; + + public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; + public static final int ADAPTER_CONF_DEFAULT_KEEP_ALIVE = 60000; + + public static final int DEFAULT_MIN_THREAD_POOL_SIZE = 8; + public static final int DEFAULT_MAX_THREAD_POOL_SIZE = 100; + public static final int DEFAULT_EXECUTOR_JOB_QUEUE_SIZE = 2000; + public static final long DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS = 20000; + public static final String ADAPTER_MIN_THREAD_POOL_SIZE_NAME = "minThread"; + public static final String ADAPTER_MAX_THREAD_POOL_SIZE_NAME = "maxThread"; + public static final String ADAPTER_KEEP_ALIVE_TIME_NAME = "keepAliveTimeInMillis"; + public static final String ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME = "jobQueueSize"; + + public static final String DEFAULT_CALLBACK = ""; + public static final String DEFAULT_PASSWORD = ""; + public static final String TOKEN_SCOPE = "production"; + public static final String APPLICATION_NAME_PREFIX = "OutputAdapter_"; + public static final String CLIENT_ID = "clientId"; + public static final String CLIENT_SECRET = "clientSecret"; + + public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; + public static final String AUTHORIZATION_HEADER_VALUE_PREFIX = "Basic "; + public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer "; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + public static final String APPLICATION_JSON = "application/json"; + public static final String PASSWORD_GRANT_TYPE = "password"; + public static final String PASSWORD_GRANT_TYPE_USERNAME = "username"; + public static final String PASSWORD_GRANT_TYPE_PASSWORD = "password"; + public static final String PASSWORD_GRANT_TYPE_SCOPES = "scopes"; + public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token"; + public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; +} + + diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java new file mode 100644 index 00000000000..fdd20f2f221 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java @@ -0,0 +1,26 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; + +/** + * This holds api application consumer id and secret. + */ +public class APIApplicationKey { + + private String clientId; + private String clientSecret; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java index 5c1487451ed..e738c71f458 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java @@ -1,5 +1,8 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; +/** + * This holds the token information that return from the token endpoint. + */ public class AccessTokenInfo { private String tokenType; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java deleted file mode 100644 index f7059ac20c7..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherAPIServiceComponent.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; - - -import com.sun.jndi.toolkit.ctx.ComponentContext; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIService; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; - -import java.io.IOException; - -/** - * @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherAPIServiceComponent" - * immediate="true" - */ -public class PublisherAPIServiceComponent { - - private static Log log = LogFactory.getLog(PublisherAPIServiceComponent.class); - - protected void activate(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Initializing publisher API extension bundle"); - } - - PublisherAPIService publisherAPIService = new PublisherAPIServiceImpl(); - - } - - protected void deactivate(ComponentContext componentContext) { - //do nothing - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java new file mode 100644 index 00000000000..612f77a8d96 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java @@ -0,0 +1,44 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceStartupHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.core.ServerShutdownHandler; +import org.wso2.carbon.core.ServerStartupObserver; + +/** + * @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherRESTAPIServiceComponent" + * immediate="true" + */ +public class PublisherRESTAPIServiceComponent { + + private static Log log = LogFactory.getLog(PublisherRESTAPIServiceComponent.class); + + protected void activate(ComponentContext componentContext) { + if (log.isDebugEnabled()) { + log.debug("Initializing publisher API extension bundle"); + } + try { + BundleContext bundleContext = componentContext.getBundleContext(); + + PublisherAPIServiceStartupHandler publisherAPIServiceStartupHandler = new PublisherAPIServiceStartupHandler(); + bundleContext.registerService(PublisherAPIServiceStartupHandler.class.getName(), publisherAPIServiceStartupHandler, null); + bundleContext.registerService(ServerStartupObserver.class.getName(), publisherAPIServiceStartupHandler, null); + bundleContext.registerService(ServerShutdownHandler.class.getName(), publisherAPIServiceStartupHandler, null); + + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); + bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); + + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected void deactivate(ComponentContext componentContext) { + //do nothing + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java similarity index 83% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java index 028d40f1900..1d532d17a7c 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherAPIUtil.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java @@ -19,14 +19,9 @@ import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; -public class PublisherAPIUtil { - - private static final Log log = LogFactory.getLog(PublisherAPIUtil.class); +public class PublisherRESTAPIUtil { + private static final Log log = LogFactory.getLog(PublisherRESTAPIUtil.class); private static final String HTTPS_PROTOCOL = "https"; - private static final String TENANT_JWT_CONFIG_LOCATION = File.separator + "jwt-config" + File.separator + "jwt.properties"; - private static final String JWT_CONFIG_FILE_NAME = "jwt.properties"; - private static final String SUPERTENANT_JWT_CONFIG_LOCATION = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + JWT_CONFIG_FILE_NAME; /** * Return a http client instance diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java new file mode 100644 index 00000000000..db8011521dd --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java @@ -0,0 +1,59 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.util; + +/** + * This class represents the data that are required to register + * the oauth application. + */ +public class ScopeUtils { + + private String key; + private String name; + private String roles; + private String description; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String toJSON() { + String jsonString = + "{\"name\": \"" + key + "\",\"displayName\": \"" + name + + "\", \"description\": \"" + description + "\"," + "\"bindings\": [" + + roles + "]" + " }"; + +// String jsonString = +// "{\"name\": \"" + name + "\",\"displayName\": \"" + name + +// "\", \"description\": \"" + description + "\"," + "\"bindings\": [" + +// "\"Internal/devicemgt-user\"" + +// "]" + " }"; + return jsonString; + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index fce4b944960..0ca58492f50 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -170,6 +170,7 @@ org.scannotation.archiveiterator;version="1.0", org.w3c.dom, io.entgra.devicemgt.apimgt.extension.publisher.api, + io.entgra.devicemgt.apimgt.extension.publisher.api.dto, org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 0dcc92e6381..ea7f2e11089 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,6 +18,11 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -50,7 +55,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 java.io.BufferedReader; import java.io.File; @@ -357,13 +361,19 @@ 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 = new APIApplicationServicesImpl(); + APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + AccessTokenInfo accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + try { for (String tenantDomain : tenants) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(MultitenantUtils.getTenantAwareUsername( - PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() - .getAdminUserName())); + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); +// APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(MultitenantUtils.getTenantAwareUsername( +// PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() +// .getAdminUserName())); try { String fileName = @@ -409,8 +419,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { } scope.setRoles(roleString); - if (apiProvider.isSharedScopeNameExists(scope.getKey(), tenantDomain)) { - apiProvider.updateSharedScope(scope, tenantDomain); +// if (apiProvider.isSharedScopeNameExists(scope.getKey(), tenantDomain)) { +// apiProvider.updateSharedScope(scope, tenantDomain); + if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { + publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, 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 if (log.isDebugEnabled()) { @@ -424,15 +436,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } - } catch (UserStoreException e) { - String msg = "Error occurred while reading tenant admin username"; - log.error(msg, e); - throw new APIManagerPublisherException(e); - } catch (APIManagementException e) { - String msg = "Error occurred while loading api provider"; - log.error(msg, e); - throw new APIManagerPublisherException(e); - } finally { + } +// catch (UserStoreException e) { +// String msg = "Error occurred while reading tenant admin username"; +// log.error(msg, e); +// throw new APIManagerPublisherException(e); +// } +// catch (APIManagementException e) { +// String msg = "Error occurred while loading api provider"; +// log.error(msg, e); +// throw new APIManagerPublisherException(e); +// } + finally { PrivilegedCarbonContext.endTenantFlow(); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index e491d35d6ec..bfcafcc2c84 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -19,13 +19,11 @@ package org.wso2.carbon.apimgt.webapp.publisher; -import io.entgra.devicemgt.apimgt.extension.publisher.api.ScopeServices; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.core.ServerStartupObserver; - import java.util.Stack; public class APIPublisherStartupHandler implements ServerStartupObserver { @@ -36,13 +34,10 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { private static final int MAX_RETRY_COUNT = 5; private static Stack failedAPIsStack = new Stack<>(); private static Stack currentAPIsStack; - private APIPublisherService publisher; - private ScopeServices scopeServices; @Override public void completingServerStartup() { - } @Override @@ -57,9 +52,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { log.debug("Total number of unpublished APIs: " + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); } - try { - scopeServices.registerApplication(); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index f41c07967a5..7cdede5bcb6 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -299,7 +299,7 @@ public class AnnotationProcessor { // if (scope != null) { // resource.setScope(scope); // } else { -// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + +// log.warn("ScopeUtils is not defined for '" + makeContextURLReady(resourceRootContext) + // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); // scope = new ApiScope(); // scope.setName(DEFAULT_SCOPE_NAME); @@ -537,7 +537,7 @@ public class AnnotationProcessor { if (scope != null) { apiResource.setScope(scope); } else { -// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + +// log.warn("ScopeUtils is not defined for '" + makeContextURLReady(resourceRootContext) + // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); scope = new ApiScope(); scope.setName(DEFAULT_SCOPE_NAME); diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 968c5bb3d1f..747eb843dda 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -42,6 +42,34 @@ org.wso2.carbon org.wso2.carbon.utils + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.core + + + com.googlecode.json-simple.wso2 + json-simple + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + com.squareup.okhttp3 + okhttp + + + io.github.openfeign + feign-okhttp + 4.0.0 From 8e4998ede8f11a6dfd1ca078a412ae4b9b6aeb61 Mon Sep 17 00:00:00 2001 From: pasindu Date: Sun, 9 Apr 2023 20:37:37 +0530 Subject: [PATCH 03/17] Test okhttp --- .../pom.xml | 20 ++- .../APIApplicationServicesImpl.java | 161 +++++++++++++----- 2 files changed, 128 insertions(+), 53 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml index 6601a501126..e5fec434f06 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -74,6 +74,10 @@ com.squareup.okhttp3 okhttp + + io.github.openfeign + feign-okhttp + @@ -85,7 +89,7 @@ org.apache.felix maven-bundle-plugin - 1.4.0 + 5.1.7 true @@ -102,7 +106,7 @@ javax.net.ssl, - javax.xml.bind, + org.apache.commons.logging, org.apache.http;version="${httpclient.version.range}", org.apache.http.client;version="${httpclient.version.range}", @@ -115,14 +119,14 @@ org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", - org.wso2.carbon.utils, + + org.wso2.carbon.core, org.apache.commons.ssl, - org.json.simple, - org.json.simple.parser, - org.apache.http.client.entity, - org.apache.http.message, + + + + org.apache.commons.httpclient, org.wso2.carbon.apimgt.api.model, okhttp3.* diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java index 06c1fe97bff..8932384f6dc 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java @@ -1,11 +1,12 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api; +import com.google.gson.JsonObject; import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile; import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; -import okhttp3.OkHttpClient; +import okhttp3.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.ssl.Base64; @@ -22,71 +23,141 @@ import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; +import java.util.*; public class APIApplicationServicesImpl implements APIApplicationServices { private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); - private final OkHttpClient client; + private static final OkHttpClient client = getOkHttpClient(); - public APIApplicationServicesImpl() { - this.client = new OkHttpClient(); + private static OkHttpClient getOkHttpClient() { + X509TrustManager trustAllCerts = new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[0]; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + }; + return new OkHttpClient.Builder() + .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) + .hostnameVerifier((hostname, sslSession) -> true).build(); } + private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { + try { + TrustManager[] trustAllCerts = new TrustManager[]{ + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + return sc.getSocketFactory(); + } catch (KeyManagementException | NoSuchAlgorithmException e) { + return null; + } + + } @Override public APIApplicationKey createAndRetrieveApplicationCredentials() { - try { - URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); - HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); - HttpPost request = new HttpPost(url.toString()); + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("callbackUrl",Constants.EMPTY_STRING); + jsonObject.addProperty("clientName",Constants.CLIENT_NAME); + jsonObject.addProperty("grantType",Constants.EMPTY_STRING); + jsonObject.addProperty("owner",Constants.OWNER); + jsonObject.addProperty("saasApp",true); - RegistrationProfile registrationProfile = new RegistrationProfile(); - registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); - registrationProfile.setClientName(Constants.CLIENT_NAME); - registrationProfile.setGrantType(Constants.GRANT_TYPE); - registrationProfile.setOwner(Constants.OWNER); - registrationProfile.setIsSaasApp(true); + MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8"); + RequestBody requestBody = RequestBody.create(jsonMediaType, jsonObject.toString()); - String jsonString = registrationProfile.toJSON(); - StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); - request.setEntity(entity); + String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register"; - //ToDo: Remove hardcoded value - String basicAuth = getBase64Encode("admin", "admin"); - request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); - request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); - - HttpResponse httpResponse = httpclient.execute(request); + Request request = new Request.Builder() + .url(keyManagerEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) + .post(requestBody) + .build(); + try { + Response response = client.newCall(request).execute(); + System.out.println(request); + System.out.println("---------------------------"); + System.out.println(response); - if (httpResponse != null) { - String response = PublisherRESTAPIUtil.getResponseString(httpResponse); - try { - if(response != null){ - JSONParser jsonParser = new JSONParser(); - JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); - APIApplicationKey apiApplicationKey = new APIApplicationKey(); - apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); - apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); - return apiApplicationKey; - } else { - return null; - } - } catch (ParseException e) { - throw new RuntimeException(e); - } - } +// JSONObject responseObj = new JSONObject(Objects.requireNonNull(response.body()).string()); - } catch (IOException | NoSuchAlgorithmException | KeyStoreException | - KeyManagementException e) { - log.error("failed to call http client.", e); + } catch (IOException e) { + throw new RuntimeException(e); } + +// try { +// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); +// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); +// HttpPost request = new HttpPost(url.toString()); +// +// RegistrationProfile registrationProfile = new RegistrationProfile(); +// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); +// registrationProfile.setClientName(Constants.CLIENT_NAME); +// registrationProfile.setGrantType(Constants.GRANT_TYPE); +// registrationProfile.setOwner(Constants.OWNER); +// registrationProfile.setIsSaasApp(true); +// +// String jsonString = registrationProfile.toJSON(); +// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); +// request.setEntity(entity); +// +// //ToDo: Remove hardcoded value +// String basicAuth = getBase64Encode("admin", "admin"); +// request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); +// request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); +// +// HttpResponse httpResponse = httpclient.execute(request); +// +// if (httpResponse != null) { +// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); +// try { +// if(response != null){ +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); +// APIApplicationKey apiApplicationKey = new APIApplicationKey(); +// apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); +// apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); +// return apiApplicationKey; +// } else { +// return null; +// } +// } catch (ParseException e) { +// throw new RuntimeException(e); +// } +// } +// +// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | +// KeyManagementException e) { +// log.error("failed to call http client.", e); +// } return null; } From f1120baec3878dbfe5ca5709c8b47fa8cce85a84 Mon Sep 17 00:00:00 2001 From: pasindu Date: Mon, 10 Apr 2023 09:33:51 +0530 Subject: [PATCH 04/17] Implement exception handling --- .../pom.xml | 4 + .../APIApplicationServices.java | 8 +- .../APIApplicationServicesImpl.java | 82 +++++++++- .../PublisherRESTAPIServices.java | 140 ++++-------------- .../APIApplicationServicesException.java | 12 ++ .../exceptions/BadRequestException.java | 34 +++++ .../webapp/publisher/APIPublisherService.java | 1 + .../publisher/APIPublisherServiceImpl.java | 23 ++- .../publisher/APIPublisherStartupHandler.java | 1 + 9 files changed, 180 insertions(+), 125 deletions(-) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml index e5fec434f06..002909f6444 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -78,6 +78,10 @@ io.github.openfeign feign-okhttp + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java index 342f5aa9549..5ca41cf6e2f 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java @@ -2,12 +2,14 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; public interface APIApplicationServices { - APIApplicationKey createAndRetrieveApplicationCredentials(); + APIApplicationKey createAndRetrieveApplicationCredentials() throws BadRequestException, APIApplicationServicesException; - AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret); - AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret); + AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIApplicationServicesException; + AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIApplicationServicesException; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java index 8932384f6dc..55c544d25b2 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java @@ -5,6 +5,8 @@ import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfi import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; import okhttp3.*; import org.apache.commons.logging.Log; @@ -37,6 +39,7 @@ import java.util.*; public class APIApplicationServicesImpl implements APIApplicationServices { private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); +<<<<<<< HEAD private static final OkHttpClient client = getOkHttpClient(); private static OkHttpClient getOkHttpClient() { @@ -57,6 +60,13 @@ public class APIApplicationServicesImpl implements APIApplicationServices { .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) .hostnameVerifier((hostname, sslSession) -> true).build(); } +======= +// private final OkHttpClient client; + +// public APIApplicationServicesImpl() { +// this.client = new OkHttpClient(); +// } +>>>>>>> e76624c1de (Add exceptions) private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { try { @@ -82,7 +92,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() { + public APIApplicationKey createAndRetrieveApplicationCredentials() + throws APIApplicationServicesException, BadRequestException { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("callbackUrl",Constants.EMPTY_STRING); @@ -109,6 +120,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { // JSONObject responseObj = new JSONObject(Objects.requireNonNull(response.body()).string()); +<<<<<<< HEAD } catch (IOException e) { throw new RuntimeException(e); } @@ -159,10 +171,54 @@ public class APIApplicationServicesImpl implements APIApplicationServices { // log.error("failed to call http client.", e); // } return null; +======= + String jsonString = registrationProfile.toJSON(); + StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); + request.setEntity(entity); + + //ToDo: Remove hardcoded value + String basicAuth = getBase64Encode("admin", "admin"); + request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); + request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); + + HttpResponse httpResponse = httpclient.execute(request); + + if (httpResponse != null) { + String response = PublisherRESTAPIUtil.getResponseString(httpResponse); + try { + if(response != null){ + JSONParser jsonParser = new JSONParser(); + JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); + APIApplicationKey apiApplicationKey = new APIApplicationKey(); + apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); + apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); + return apiApplicationKey; + } else { + String msg = "Request payload is null. Please verify the request payload."; + log.error(msg); + throw new BadRequestException(msg); + } + } catch (ParseException e) { + throw new APIApplicationServicesException("Error when parsing the response " + response, e); + } + } else { + return null; + } + } catch (IOException e) { + throw new APIApplicationServicesException("Error when reading the response from buffer.", e); + } catch (KeyStoreException e) { + throw new APIApplicationServicesException("Failed loading the keystore.", e); + } catch (NoSuchAlgorithmException e) { + throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); + } catch (KeyManagementException e) { + throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); + } +>>>>>>> e76624c1de (Add exceptions) } @Override - public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) { + public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) + throws APIApplicationServicesException { List params = new ArrayList<>(); params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); //ToDo: Remove hardcoded value @@ -173,7 +229,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } @Override - public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret) { + public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret) + throws APIApplicationServicesException { List params = new ArrayList<>(); params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE)); params.add(new BasicNameValuePair(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken)); @@ -181,8 +238,10 @@ public class APIApplicationServicesImpl implements APIApplicationServices { return getToken(params, consumerKey, consumerSecret); } - public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) { + public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) + throws APIApplicationServicesException{ + String response = null; try { URL url = new URL("https://localhost:9443/oauth2/token"); HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); @@ -193,7 +252,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse httpResponse = httpclient.execute(request); - String response = PublisherRESTAPIUtil.getResponseString(httpResponse); + response = PublisherRESTAPIUtil.getResponseString(httpResponse); if (log.isDebugEnabled()) { log.debug(response); } @@ -210,9 +269,16 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } return accessTokenInfo; - } catch (IOException | KeyStoreException | NoSuchAlgorithmException | - KeyManagementException| ParseException e) { - throw new RuntimeException(e); + } catch (IOException e) { + throw new APIApplicationServicesException("Error when reading the response from buffer.", e); + } catch (KeyStoreException e) { + throw new APIApplicationServicesException("Failed loading the keystore.", e); + } catch (NoSuchAlgorithmException e) { + throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); + } catch (ParseException e) { + throw new APIApplicationServicesException("Error when parsing the response " + response, e); + } catch (KeyManagementException e) { + throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java index 335680a84dd..6e37e019862 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java @@ -3,9 +3,10 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api; import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; import io.entgra.devicemgt.apimgt.extension.publisher.api.util.ScopeUtils; -import org.apache.axis2.databinding.types.xsd._boolean; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.HttpHead; @@ -28,104 +29,8 @@ import java.security.NoSuchAlgorithmException; public class PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); -// private String clientId; -// private String clientSecret; -// private String accessToken; -// -// public AccessTokenInfo registerApplication() { -// -// try { -// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPost request = new HttpPost(url.toString()); -// -// RegistrationProfile registrationProfile = new RegistrationProfile(); -// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); -// registrationProfile.setClientName(Constants.CLIENT_NAME); -// registrationProfile.setGrantType(Constants.GRANT_TYPE); -// registrationProfile.setOwner(Constants.OWNER); -// registrationProfile.setIsSaasApp(true); -// -// String jsonString = registrationProfile.toJSON(); -// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); -// request.setEntity(entity); -// -// String basicAuth = getBase64Encode("admin", "admin"); -// -// request.setHeader("Authorization", "Basic " + basicAuth); -// request.setHeader("Content-Type", "application/json"); -// -// HttpResponse httpResponse = httpclient.execute(request); -// -// if (httpResponse != null) { -// -// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); -// try { -// if(response != null){ -// JSONParser jsonParser = new JSONParser(); -// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); -// clientId = (String) jsonPayload.get(Constants.CLIENT_ID); -// clientSecret = (String) jsonPayload.get(Constants.CLIENT_SECRET); -// } -// } catch (ParseException e) { -// throw new RuntimeException(e); -// } -// System.out.println(response); -// } -// System.out.println(httpResponse.getStatusLine().getStatusCode()); -// -// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | -// KeyManagementException e) { -// log.error("failed to call http client.", e); -// } -// return getAccessTokenFromRegisteredApplication(clientId, clientSecret); -// -// } -// -// public AccessTokenInfo getAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) { -// List params = new ArrayList<>(); -// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); -// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); -// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); -// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); -// return getToken(params, consumerKey, consumerSecret); -// } -// -// public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) { -// -// String token = null; -// String response = null; -// try { -// URL url = new URL("https://localhost:9443/oauth2/token"); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPost request = new HttpPost(url.toString()); -// -// request.addHeader("Authorization", "Basic " + getBase64Encode(clientId, clientSecret)); -// request.addHeader("Content-Type", "application/x-www-form-urlencoded"); -// request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); -// HttpResponse httpResponse = httpclient.execute(request); -// response = PublisherRESTAPIUtil.getResponseString(httpResponse); -// JSONParser jsonParser = new JSONParser(); -// JSONObject jsonObject = (JSONObject) jsonParser.parse(response); -// AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); -// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); -// if (token != null && !token.isEmpty()){ -// accessTokenInfo.setRefreshToken(token); -// accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); -// accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); -// accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); -// accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); -// } -// accessToken = token; -// return accessTokenInfo; -// -// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | -// KeyManagementException| ParseException e) { -// throw new RuntimeException(e); -// } -// } - - public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key){ + public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) + throws APIApplicationServicesException, BadRequestException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; @@ -144,19 +49,28 @@ public class PublisherRESTAPIServices { AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); return isSharedScopeNameExists(apiApplicationKey,refreshedAccessToken, key); - } else{ + } else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){ + String response = httpResponse.toString(); + log.info(response); + throw new BadRequestException(response); + } else { return false; } - } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { - throw new RuntimeException(e); + } catch (IOException e) { + throw new APIApplicationServicesException("Error when reading the response from buffer.", e); + } catch (KeyStoreException e) { + throw new APIApplicationServicesException("Failed loading the keystore.", e); + } catch (NoSuchAlgorithmException e) { + throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); + } catch (KeyManagementException e) { + throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); } } - public void updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope){ + public void updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIApplicationServicesException, BadRequestException { -// String keyValue = new String(Base64.encodeBase64((scope.getKey()).getBytes())).replace("=", ""); -// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); try { URL url = new URL(updateScopeUrl); @@ -182,16 +96,20 @@ public class PublisherRESTAPIServices { AccessTokenInfo accessTokenInfo1 = apiApplicationServices. generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); updateSharedScope(apiApplicationKey, accessTokenInfo1, scope); - } else { + } else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){ String response = httpResponse.toString(); log.info(response); + throw new BadRequestException(response); } - } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { - throw new RuntimeException(e); + } catch (IOException e) { + throw new APIApplicationServicesException("Error when reading the response from buffer.", e); + } catch (KeyStoreException e) { + throw new APIApplicationServicesException("Failed loading the keystore.", e); + } catch (NoSuchAlgorithmException e) { + throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); + } catch (KeyManagementException e) { + throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); } } -// static String getBase64Encode(String key, String value) { -// return new String(Base64.encodeBase64((key + ":" + value).getBytes())); -// } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java new file mode 100644 index 00000000000..bd7aa85cd96 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java @@ -0,0 +1,12 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; + +public class APIApplicationServicesException extends Exception{ + + public APIApplicationServicesException() {super();} + + public APIApplicationServicesException(String message) {super();} + + public APIApplicationServicesException(String message, Throwable cause){super();} + + public APIApplicationServicesException(Throwable cause){super();} +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java new file mode 100644 index 00000000000..1e58e27d7ba --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java @@ -0,0 +1,34 @@ +/* + * + * * Copyright (c) 2022, 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. + * + * + */ + +/** + * Custom exception class for handling bad request exceptions. + */ +package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; + +public class BadRequestException extends Exception { + + private static final long serialVersionUID = -2387103750774855056L; + + public BadRequestException(String errorMessage) { + super(errorMessage); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java index a7299501bdd..85dcf72d138 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java @@ -19,6 +19,7 @@ package org.wso2.carbon.apimgt.webapp.publisher; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; /** diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index ea7f2e11089..c6f16436a19 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -23,6 +23,8 @@ import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -361,10 +363,21 @@ 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 = new APIApplicationServicesImpl(); - APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - AccessTokenInfo accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + APIApplicationKey apiApplicationKey; + AccessTokenInfo accessTokenInfo; + try { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + } catch (BadRequestException e) { + String errorMsg = "Error while generating application"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); + } catch (APIApplicationServicesException e) { + throw new RuntimeException(e); + } try { for (String tenantDomain : tenants) { @@ -433,6 +446,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } catch (IOException | DirectoryIteratorException ex) { log.error("failed to read scopes from file.", ex); + } catch (APIApplicationServicesException | BadRequestException e) { + String errorMsg = "Error while generating an OAuth token"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index bfcafcc2c84..a530fa5b479 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -19,6 +19,7 @@ package org.wso2.carbon.apimgt.webapp.publisher; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; From 0d7057640110c7ee92f59867fde681a20a124bd7 Mon Sep 17 00:00:00 2001 From: pasindu Date: Mon, 17 Apr 2023 09:49:43 +0530 Subject: [PATCH 05/17] change http client to okhttp --- .../pom.xml | 15 +- .../APIApplicationServices.java | 3 +- .../APIApplicationServicesImpl.java | 104 +++++++++--- .../PublisherAPIServiceStartupHandler.java | 159 ------------------ .../PublisherRESTAPIServices.java | 111 +++++------- .../dto/APIApplicationKey.java | 70 +++++++- .../exceptions/BadRequestException.java | 2 + .../internal/PublisherRESTAPIDataHolder.java | 30 ++++ .../PublisherRESTAPIServiceComponent.java | 23 +-- .../pom.xml | 5 + .../publisher/APIPublisherServiceImpl.java | 9 +- .../publisher/APIPublisherStartupHandler.java | 10 +- components/apimgt-extensions/pom.xml | 46 ----- 13 files changed, 264 insertions(+), 323 deletions(-) delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml index 002909f6444..8e25736b1f9 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -79,8 +79,13 @@ feign-okhttp +<<<<<<< HEAD org.wso2.carbon.apimgt org.wso2.carbon.apimgt.api +======= + org.json.wso2 + json +>>>>>>> 2855ef0a30 (change http client to okhttp) @@ -110,7 +115,6 @@ javax.net.ssl, - org.apache.commons.logging, org.apache.http;version="${httpclient.version.range}", org.apache.http.client;version="${httpclient.version.range}", @@ -123,17 +127,12 @@ org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - - org.wso2.carbon.core, org.apache.commons.ssl, - - - - org.apache.commons.httpclient, org.wso2.carbon.apimgt.api.model, - okhttp3.* + okhttp3.*, + org.json diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java index 5ca41cf6e2f..401f680214f 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java @@ -3,11 +3,10 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; public interface APIApplicationServices { - APIApplicationKey createAndRetrieveApplicationCredentials() throws BadRequestException, APIApplicationServicesException; + APIApplicationKey createAndRetrieveApplicationCredentials() throws APIApplicationServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIApplicationServicesException; AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIApplicationServicesException; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java index 55c544d25b2..c2aa63c4329 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java @@ -1,48 +1,109 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api; -import com.google.gson.JsonObject; -import io.entgra.devicemgt.apimgt.extension.publisher.api.bean.RegistrationProfile; +import com.google.gson.Gson; +import org.json.JSONObject; import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; import okhttp3.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.ssl.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicNameValuePair; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; -import java.net.URL; import java.security.KeyManagementException; -import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; -import java.util.*; public class APIApplicationServicesImpl implements APIApplicationServices { private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); <<<<<<< HEAD private static final OkHttpClient client = getOkHttpClient(); + private static final Gson gson = new Gson(); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + String msg = null; + // private ApiApplicationConfigurations ApplicationConfig = null; - private static OkHttpClient getOkHttpClient() { + @Override + public APIApplicationKey createAndRetrieveApplicationCredentials() + throws APIApplicationServicesException { + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("callbackUrl", Constants.EMPTY_STRING); + jsonObject.put("clientName",Constants.CLIENT_NAME); + jsonObject.put("grantType",Constants.GRANT_TYPE); + jsonObject.put("owner",Constants.OWNER); + jsonObject.put("saasApp",true); + + RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); + String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register"; + + Request request = new Request.Builder() + .url(keyManagerEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) + .post(requestBody) + .build(); + try { + Response response = client.newCall(request).execute(); + return gson.fromJson(response.body().string(), APIApplicationKey.class); + } catch (IOException e) { + msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); + } + } + + @Override + public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) + throws APIApplicationServicesException { + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.PASSWORD_GRANT_TYPE); + //ToDo: Remove hardcoded value + params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME,"admin"); + params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD,"admin"); + params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES); + return getToken(params, consumerKey, consumerSecret); + } + + @Override + public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret) + throws APIApplicationServicesException { + + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.REFRESH_TOKEN_GRANT_TYPE); + //ToDo: Remove hardcoded value + params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken); + params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES); + return getToken(params, consumerKey, consumerSecret); + } + + public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret) + throws APIApplicationServicesException{ + + RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); + //application/x-www-form-urlencoded + String keyManagerEndpoint = "https://localhost:9443/oauth2/token"; + + Request request = new Request.Builder() + .url(keyManagerEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret)) + .post(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + return gson.fromJson(response.body().string(), AccessTokenInfo.class); + } catch (IOException e) { + msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); + } + } + + protected static OkHttpClient getOkHttpClient() { X509TrustManager trustAllCerts = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; @@ -91,6 +152,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } } +<<<<<<< HEAD @Override public APIApplicationKey createAndRetrieveApplicationCredentials() throws APIApplicationServicesException, BadRequestException { @@ -285,4 +347,6 @@ public class APIApplicationServicesImpl implements APIApplicationServices { static String getBase64Encode(String key, String value) { return new String(Base64.encodeBase64((key + ":" + value).getBytes())); } +======= +>>>>>>> 2855ef0a30 (change http client to okhttp) } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java deleted file mode 100644 index 2b005b0cc0d..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherAPIServiceStartupHandler.java +++ /dev/null @@ -1,159 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; - -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.core.ServerStartupObserver; - -public class PublisherAPIServiceStartupHandler implements ServerStartupObserver { - - private static final Log log = LogFactory.getLog(PublisherAPIServiceStartupHandler.class); - private PublisherRESTAPIServices publisherRESTAPIServices; - private AccessTokenInfo accessTokenInfo; - - @Override - public void completingServerStartup() { - - } - - @Override - public void completedServerStartup() { - -// String cid = null; -// String cS = null; -// String token = null; -// AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); -// -// try { -// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPost request = new HttpPost(url.toString()); -// -// RegistrationProfile registrationProfile = new RegistrationProfile(); -// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); -// registrationProfile.setClientName(Constants.CLIENT_NAME); -// registrationProfile.setOwner(Constants.OWNER); -// registrationProfile.setGrantType(Constants.GRANT_TYPE); -// registrationProfile.setIsSaasApp(true); -// -// String jsonString = registrationProfile.toJSON(); -// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); -// request.setEntity(entity); -// -// String basicAuth = PublisherRESTAPIServices.getBase64Encode("admin", "admin"); -// -// request.setHeader("Authorization", "Basic " + basicAuth); -// request.setHeader("Content-Type", "application/json"); -// -// HttpResponse httpResponse = httpclient.execute(request); -// -// if (httpResponse != null) { -// -// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); -// try { -// if(response != null){ -// JSONParser jsonParser = new JSONParser(); -// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); -// String clientId = (String) jsonPayload.get(Constants.CLIENT_ID); -// String clientSecret = (String) jsonPayload.get(Constants.CLIENT_SECRET); -// cid = clientId; -// cS = clientSecret; -// } -// } catch (ParseException e) { -// throw new RuntimeException(e); -// } -// -// System.out.println(response); -// } -// System.out.println(httpResponse.getStatusLine().getStatusCode()); -// -// -// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | -// KeyManagementException e) { -// log.error("failed to call http client.", e); -// } -// -// -// String response = null; -// -// List params = new ArrayList<>(); -// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); -// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); -// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); -// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); -// try { -// URL url = new URL("https://localhost:9443/oauth2/token"); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPost request = new HttpPost(url.toString()); -// -// request.addHeader("Authorization", "Basic " + PublisherRESTAPIServices.getBase64Encode(cid, cS)); -// request.addHeader("Content-Type", "application/x-www-form-urlencoded"); -// request.setEntity(new UrlEncodedFormEntity(params)); -// HttpResponse httpResponse = httpclient.execute(request); -// response = PublisherRESTAPIUtil.getResponseString(httpResponse); -// JSONParser jsonParser = new JSONParser(); -// JSONObject jsonObject = (JSONObject) jsonParser.parse(response); -// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); -// if (token != null && !token.isEmpty()){ -// accessTokenInfo.setRefreshToken(token); -// accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); -// accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); -// accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); -// accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); -// } -// System.out.println(accessTokenInfo); -// -// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | -// KeyManagementException| ParseException e) { -// throw new RuntimeException(e); -// } -// -// String key = "perm:sms-handler:view-configuration"; -// String value = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); -// -// -// String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + value; -// try { -// URL url = new URL(getScopeUrl); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpHead request = new HttpHead(url.toString()); -// -// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); -// HttpResponse httpResponse = httpclient.execute(request); -// -// String code = String.valueOf(httpResponse.getStatusLine().getStatusCode()); -// System.out.println(code); -// -// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { -// throw new RuntimeException(e); -// } -// -// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + "27fce6f1-6741-4ad5-b700-a56427fd3dbb"; -// try { -// URL url = new URL(updateScopeUrl); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPut request = new HttpPut(url.toString()); -// -// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); -// request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); -// -// -// String jsonString = "{\"name\": \"" + "name" + "\",\"displayName\": \"" + "displayname" + -// "\", \"description\": \"" + "description" + "\"," + "\"bindings\": [" + -// "\"Internal/devicemgt-user\"]}"; -// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); -// request.setEntity(entity); -// -// HttpResponse httpResponse = httpclient.execute(request); -// int code = httpResponse.getStatusLine().getStatusCode(); -// System.out.println(code); -// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { -// throw new RuntimeException(e); -// } - - -// publisherRESTAPIServices = new PublisherRESTAPIServices(); -// publisherRESTAPIServices.isSharedScopeNameExists("perm:sms-handler:view-configuration"); - - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java index 6e37e019862..a0bb43217d0 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java @@ -5,111 +5,92 @@ import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.util.PublisherRESTAPIUtil; -import io.entgra.devicemgt.apimgt.extension.publisher.api.util.ScopeUtils; +import okhttp3.*; import org.apache.commons.httpclient.HttpStatus; -import org.apache.http.HttpHeaders; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpPut; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.ssl.Base64; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; +import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.Scope; import java.io.IOException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; +import static io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl.getOkHttpClient; public class PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); + private static final OkHttpClient client = getOkHttpClient(); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) throws APIApplicationServicesException, BadRequestException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; - try { - URL url = new URL(getScopeUrl); - HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); - HttpHead request = new HttpHead(url.toString()); - - request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessTokenInfo.getAccessToken()); - HttpResponse httpResponse = httpclient.execute(request); - if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()){ + Request request = new Request.Builder() + .url(getScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken()) + .head() + .build(); + try { + Response response = client.newCall(request).execute(); + if (response.code() == HttpStatus.SC_OK){ return true; - } else if(HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()) { + }else if(HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); + //max attempt count return isSharedScopeNameExists(apiApplicationKey,refreshedAccessToken, key); - } else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){ - String response = httpResponse.toString(); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()){ log.info(response); - throw new BadRequestException(response); + throw new BadRequestException(response.toString()); } else { return false; } - } catch (IOException e) { - throw new APIApplicationServicesException("Error when reading the response from buffer.", e); - } catch (KeyStoreException e) { - throw new APIApplicationServicesException("Failed loading the keystore.", e); - } catch (NoSuchAlgorithmException e) { - throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); - } catch (KeyManagementException e) { - throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); + String msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); } } - public void updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIApplicationServicesException, BadRequestException { String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); - try { - URL url = new URL(updateScopeUrl); - HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); - HttpPut request = new HttpPut(url.toString()); - request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + - accessTokenInfo.getAccessToken()); - request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); + JSONObject setScope = new JSONObject(); + setScope.put("name", scope.getKey()); + setScope.put("displayName", scope.getName()); + setScope.put("description", scope.getDescription()); + setScope.put("bindings", scope.getRoles()); + - ScopeUtils setScope = new ScopeUtils(); - setScope.setKey(scope.getKey()); - setScope.setName(scope.getName()); - setScope.setDescription(scope.getDescription()); - setScope.setRoles(scope.getRoles()); - String jsonString = setScope.toJSON(); - StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); - request.setEntity(entity); + RequestBody requestBody = RequestBody.Companion.create(setScope.toString(), JSON); + Request request = new Request.Builder() + .url(updateScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken()) + .put(requestBody) + .build(); - HttpResponse httpResponse = httpclient.execute(request); - if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode() && HttpStatus.SC_UNAUTHORIZED == httpResponse.getStatusLine().getStatusCode()){ + try { + Response response = client.newCall(request).execute(); + if (response.code() == HttpStatus.SC_OK) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo accessTokenInfo1 = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); - updateSharedScope(apiApplicationKey, accessTokenInfo1, scope); - } else if (HttpStatus.SC_BAD_REQUEST == httpResponse.getStatusLine().getStatusCode()){ - String response = httpResponse.toString(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { log.info(response); - throw new BadRequestException(response); + throw new BadRequestException(response.toString()); + } else { + return false; } - } catch (IOException e) { - throw new APIApplicationServicesException("Error when reading the response from buffer.", e); - } catch (KeyStoreException e) { - throw new APIApplicationServicesException("Failed loading the keystore.", e); - } catch (NoSuchAlgorithmException e) { - throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); - } catch (KeyManagementException e) { - throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); + String msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); } } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java index fdd20f2f221..d0fc3b9f68b 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java @@ -4,9 +4,20 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; * This holds api application consumer id and secret. */ public class APIApplicationKey { - + private String clientName; private String clientId; private String clientSecret; + private String callBackURL; + private String isSaasApplication; + private String appOwner; + private String jsonString; + private String jsonAppAttribute; + private String tokenType; + + public APIApplicationKey(String clientId, String clientSecret){ + this.clientId = clientId; + this.clientSecret = clientSecret; + } public String getClientId() { return clientId; @@ -23,4 +34,61 @@ public class APIApplicationKey { public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + + public String getCallBackURL() { + return callBackURL; + } + + public void setCallBackURL(String callBackURL) { + this.callBackURL = callBackURL; + } + + public String getIsSaasApplication() { + return isSaasApplication; + } + + public void setIsSaasApplication(String isSaasApplication) { + this.isSaasApplication = isSaasApplication; + } + + public String getAppOwner() { + return appOwner; + } + + public void setAppOwner(String appOwner) { + this.appOwner = appOwner; + } + + public String getJsonString() { + return jsonString; + } + + public void setJsonString(String jsonString) { + this.jsonString = jsonString; + } + + public String getJsonAppAttribute() { + return jsonAppAttribute; + } + + public void setJsonAppAttribute(String jsonAppAttribute) { + this.jsonAppAttribute = jsonAppAttribute; + } + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java index 1e58e27d7ba..427c4b5e358 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java @@ -24,6 +24,8 @@ */ package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; +import okhttp3.Response; + public class BadRequestException extends Exception { private static final long serialVersionUID = -2387103750774855056L; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java new file mode 100644 index 00000000000..885f3ead7aa --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java @@ -0,0 +1,30 @@ +package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; + +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; + +public class PublisherRESTAPIDataHolder { + + private static final PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); + + private APIApplicationServices apiApplicationServices; +// +// private PublisherRESTAPIServices publisherRESTAPIServices; + + public static PublisherRESTAPIDataHolder getInstance(){ + return thisInstance; + } + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } +// public PublisherRESTAPIServices getPublisherRESTAPIServices() { +// return publisherRESTAPIServices; +// } +// public void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { +// this.publisherRESTAPIServices = publisherRESTAPIServices; +// } + +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java index 612f77a8d96..d34012c1f46 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java @@ -1,13 +1,12 @@ package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherAPIServiceStartupHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.core.ServerShutdownHandler; -import org.wso2.carbon.core.ServerStartupObserver; /** * @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherRESTAPIServiceComponent" @@ -24,17 +23,19 @@ public class PublisherRESTAPIServiceComponent { try { BundleContext bundleContext = componentContext.getBundleContext(); - PublisherAPIServiceStartupHandler publisherAPIServiceStartupHandler = new PublisherAPIServiceStartupHandler(); - bundleContext.registerService(PublisherAPIServiceStartupHandler.class.getName(), publisherAPIServiceStartupHandler, null); - bundleContext.registerService(ServerStartupObserver.class.getName(), publisherAPIServiceStartupHandler, null); - bundleContext.registerService(ServerShutdownHandler.class.getName(), publisherAPIServiceStartupHandler, null); - - PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); - bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); +// PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); +// bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); +// PublisherRESTAPIDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); + PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + if (log.isDebugEnabled()) { + log.debug("API Application bundle has been successfully initialized"); + } } catch (Exception e) { - throw new RuntimeException(e); + log.error("Error occurred while initializing API Application bundle", e); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 0ca58492f50..d9246c253a2 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -126,6 +126,10 @@ org.wso2.carbon.devicemgt io.entgra.devicemgt.apimgt.extension.publisher.api + + org.wso2.carbon.devicemgt + io.entgra.devicemgt.apimgt.extension.publisher.api + @@ -171,6 +175,7 @@ org.w3c.dom, io.entgra.devicemgt.apimgt.extension.publisher.api, io.entgra.devicemgt.apimgt.extension.publisher.api.dto, + io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions, org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index c6f16436a19..2fe4883df58 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -371,12 +371,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (BadRequestException e) { + } catch (APIApplicationServicesException e) { String errorMsg = "Error while generating application"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); - } catch (APIApplicationServicesException e) { - throw new RuntimeException(e); } try { @@ -384,9 +382,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); -// APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(MultitenantUtils.getTenantAwareUsername( -// PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() -// .getAdminUserName())); try { String fileName = @@ -447,7 +442,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } catch (IOException | DirectoryIteratorException ex) { log.error("failed to read scopes from file.", ex); } catch (APIApplicationServicesException | BadRequestException e) { - String errorMsg = "Error while generating an OAuth token"; + String errorMsg = "Error while Calling APIs"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index a530fa5b479..3933f60716d 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -19,6 +19,11 @@ package org.wso2.carbon.apimgt.webapp.publisher; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -53,10 +58,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { log.debug("Total number of unpublished APIs: " + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); } - try { - } catch (Exception e) { - throw new RuntimeException(e); - } + publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); int retryCount = 0; while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) { diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 747eb843dda..ae822fd4eb6 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,52 +25,6 @@ 5.0.26-SNAPSHOT ../../pom.xml - - - org.apache.httpcomponents.wso2 - httpcore - - - org.wso2.orbit.org.apache.httpcomponents - httpclient - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.core - - - com.googlecode.json-simple.wso2 - json-simple - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.api - - - com.squareup.okhttp3 - okhttp - - - io.github.openfeign - feign-okhttp - - 4.0.0 apimgt-extensions From e920df6da3ff4a9d8f104e9e8027c3e1e6dacfc4 Mon Sep 17 00:00:00 2001 From: pasindu Date: Mon, 17 Apr 2023 13:31:49 +0530 Subject: [PATCH 06/17] Minor changes --- .../pom.xml | 7 +- .../APIApplicationServicesImpl.java | 212 +----------------- .../pom.xml | 5 +- components/apimgt-extensions/pom.xml | 18 ++ 4 files changed, 26 insertions(+), 216 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml index 8e25736b1f9..0b2d3f034b1 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.21-SNAPSHOT + 5.0.25-SNAPSHOT ../pom.xml @@ -79,13 +79,12 @@ feign-okhttp -<<<<<<< HEAD org.wso2.carbon.apimgt org.wso2.carbon.apimgt.api -======= + + org.json.wso2 json ->>>>>>> 2855ef0a30 (change http client to okhttp) diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java index c2aa63c4329..5e6439edbbd 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java @@ -9,7 +9,6 @@ import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicat import okhttp3.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.commons.ssl.Base64; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; @@ -22,7 +21,6 @@ import java.security.NoSuchAlgorithmException; public class APIApplicationServicesImpl implements APIApplicationServices { private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); -<<<<<<< HEAD private static final OkHttpClient client = getOkHttpClient(); private static final Gson gson = new Gson(); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); @@ -53,6 +51,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { return gson.fromJson(response.body().string(), APIApplicationKey.class); } catch (IOException e) { msg = "Error occurred while processing the response"; + log.error(msg); throw new APIApplicationServicesException(msg); } } @@ -86,10 +85,10 @@ public class APIApplicationServicesImpl implements APIApplicationServices { RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); //application/x-www-form-urlencoded - String keyManagerEndpoint = "https://localhost:9443/oauth2/token"; + String tokenEndPoint = "https://localhost:9443/oauth2/token"; Request request = new Request.Builder() - .url(keyManagerEndpoint) + .url(tokenEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret)) .post(requestBody) .build(); @@ -99,6 +98,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { return gson.fromJson(response.body().string(), AccessTokenInfo.class); } catch (IOException e) { msg = "Error occurred while processing the response"; + log.error(msg); throw new APIApplicationServicesException(msg); } } @@ -121,13 +121,6 @@ public class APIApplicationServicesImpl implements APIApplicationServices { .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) .hostnameVerifier((hostname, sslSession) -> true).build(); } -======= -// private final OkHttpClient client; - -// public APIApplicationServicesImpl() { -// this.client = new OkHttpClient(); -// } ->>>>>>> e76624c1de (Add exceptions) private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { try { @@ -152,201 +145,4 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } } -<<<<<<< HEAD - @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() - throws APIApplicationServicesException, BadRequestException { - - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("callbackUrl",Constants.EMPTY_STRING); - jsonObject.addProperty("clientName",Constants.CLIENT_NAME); - jsonObject.addProperty("grantType",Constants.EMPTY_STRING); - jsonObject.addProperty("owner",Constants.OWNER); - jsonObject.addProperty("saasApp",true); - - MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8"); - RequestBody requestBody = RequestBody.create(jsonMediaType, jsonObject.toString()); - - String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register"; - - Request request = new Request.Builder() - .url(keyManagerEndpoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) - .post(requestBody) - .build(); - try { - Response response = client.newCall(request).execute(); - System.out.println(request); - System.out.println("---------------------------"); - System.out.println(response); - -// JSONObject responseObj = new JSONObject(Objects.requireNonNull(response.body()).string()); - -<<<<<<< HEAD - } catch (IOException e) { - throw new RuntimeException(e); - } - -// try { -// URL url = new URL("https://localhost:9443/client-registration/v0.17/register"); -// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); -// HttpPost request = new HttpPost(url.toString()); -// -// RegistrationProfile registrationProfile = new RegistrationProfile(); -// registrationProfile.setCallbackUrl(Constants.EMPTY_STRING); -// registrationProfile.setClientName(Constants.CLIENT_NAME); -// registrationProfile.setGrantType(Constants.GRANT_TYPE); -// registrationProfile.setOwner(Constants.OWNER); -// registrationProfile.setIsSaasApp(true); -// -// String jsonString = registrationProfile.toJSON(); -// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); -// request.setEntity(entity); -// -// //ToDo: Remove hardcoded value -// String basicAuth = getBase64Encode("admin", "admin"); -// request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); -// request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); -// -// HttpResponse httpResponse = httpclient.execute(request); -// -// if (httpResponse != null) { -// String response = PublisherRESTAPIUtil.getResponseString(httpResponse); -// try { -// if(response != null){ -// JSONParser jsonParser = new JSONParser(); -// JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); -// APIApplicationKey apiApplicationKey = new APIApplicationKey(); -// apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); -// apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); -// return apiApplicationKey; -// } else { -// return null; -// } -// } catch (ParseException e) { -// throw new RuntimeException(e); -// } -// } -// -// } catch (IOException | NoSuchAlgorithmException | KeyStoreException | -// KeyManagementException e) { -// log.error("failed to call http client.", e); -// } - return null; -======= - String jsonString = registrationProfile.toJSON(); - StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); - request.setEntity(entity); - - //ToDo: Remove hardcoded value - String basicAuth = getBase64Encode("admin", "admin"); - request.setHeader(HttpHeaders.AUTHORIZATION, Constants.AUTHORIZATION_HEADER_VALUE_PREFIX + basicAuth); - request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON); - - HttpResponse httpResponse = httpclient.execute(request); - - if (httpResponse != null) { - String response = PublisherRESTAPIUtil.getResponseString(httpResponse); - try { - if(response != null){ - JSONParser jsonParser = new JSONParser(); - JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); - APIApplicationKey apiApplicationKey = new APIApplicationKey(); - apiApplicationKey.setClientId((String) jsonPayload.get(Constants.CLIENT_ID)); - apiApplicationKey.setClientSecret((String) jsonPayload.get(Constants.CLIENT_SECRET)); - return apiApplicationKey; - } else { - String msg = "Request payload is null. Please verify the request payload."; - log.error(msg); - throw new BadRequestException(msg); - } - } catch (ParseException e) { - throw new APIApplicationServicesException("Error when parsing the response " + response, e); - } - } else { - return null; - } - } catch (IOException e) { - throw new APIApplicationServicesException("Error when reading the response from buffer.", e); - } catch (KeyStoreException e) { - throw new APIApplicationServicesException("Failed loading the keystore.", e); - } catch (NoSuchAlgorithmException e) { - throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); - } catch (KeyManagementException e) { - throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); - } ->>>>>>> e76624c1de (Add exceptions) - } - - @Override - public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) - throws APIApplicationServicesException { - List params = new ArrayList<>(); - params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE)); - //ToDo: Remove hardcoded value - params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin")); - params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin")); - params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); - return getToken(params, consumerKey, consumerSecret); - } - - @Override - public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, String consumerSecret) - throws APIApplicationServicesException { - List params = new ArrayList<>(); - params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE)); - params.add(new BasicNameValuePair(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken)); - params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES)); - return getToken(params, consumerKey, consumerSecret); - } - - public AccessTokenInfo getToken(List nameValuePairs, String clientId, String clientSecret) - throws APIApplicationServicesException{ - - String response = null; - try { - URL url = new URL("https://localhost:9443/oauth2/token"); - HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol()); - HttpPost request = new HttpPost(url.toString()); - - request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64Encode(clientId, clientSecret)); - request.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); - request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - - HttpResponse httpResponse = httpclient.execute(request); - response = PublisherRESTAPIUtil.getResponseString(httpResponse); - if (log.isDebugEnabled()) { - log.debug(response); - } - JSONParser jsonParser = new JSONParser(); - JSONObject jsonObject = (JSONObject) jsonParser.parse(response); - AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); - String accessToken = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); - if (accessToken != null && !accessToken.isEmpty()){ - accessTokenInfo.setAccessToken(accessToken); - accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME)); - accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN)); - accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE)); - accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE)); - } - return accessTokenInfo; - - } catch (IOException e) { - throw new APIApplicationServicesException("Error when reading the response from buffer.", e); - } catch (KeyStoreException e) { - throw new APIApplicationServicesException("Failed loading the keystore.", e); - } catch (NoSuchAlgorithmException e) { - throw new APIApplicationServicesException("No such algorithm found when loading the ssl socket", e); - } catch (ParseException e) { - throw new APIApplicationServicesException("Error when parsing the response " + response, e); - } catch (KeyManagementException e) { - throw new APIApplicationServicesException("Failed setting up the ssl http client.", e); - } - } - - static String getBase64Encode(String key, String value) { - return new String(Base64.encodeBase64((key + ":" + value).getBytes())); - } -======= ->>>>>>> 2855ef0a30 (change http client to okhttp) } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index d9246c253a2..c08735db3fd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -125,10 +125,7 @@ org.wso2.carbon.devicemgt io.entgra.devicemgt.apimgt.extension.publisher.api - - - org.wso2.carbon.devicemgt - io.entgra.devicemgt.apimgt.extension.publisher.api + provided diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index ae822fd4eb6..137f35b5724 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,6 +25,24 @@ 5.0.26-SNAPSHOT ../../pom.xml + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + org.json.wso2 + json + + + io.github.openfeign + feign-okhttp + + + com.google.code.gson + gson + + 4.0.0 apimgt-extensions From aab94d8fdd5263762c90a9ae3978c3b963b5009f Mon Sep 17 00:00:00 2001 From: pasindu Date: Fri, 21 Apr 2023 00:26:16 +0530 Subject: [PATCH 07/17] Implement get scopesID API call and rename the module --- .../PublisherRESTAPIServices.java | 96 ------------ .../dto/AccessTokenInfo.java | 53 ------- .../internal/PublisherRESTAPIDataHolder.java | 30 ---- .../util/PublisherRESTAPIUtil.java | 67 --------- .../util/ScopeUtils.java | 59 -------- .../pom.xml | 12 +- .../rest/api}/APIApplicationServices.java | 8 +- .../rest/api}/APIApplicationServicesImpl.java | 57 +++++--- .../rest/api/PublisherRESTAPIServices.java | 137 ++++++++++++++++++ .../rest/api}/bean/RegistrationProfile.java | 2 +- .../rest/api}/constants/Constants.java | 2 +- .../rest/api}/dto/APIApplicationKey.java | 2 +- .../rest/api/dto/AccessTokenInfo.java | 53 +++++++ .../APIApplicationServicesException.java | 2 +- .../api}/exceptions/BadRequestException.java | 4 +- .../internal/PublisherRESTAPIDataHolder.java | 21 +++ .../PublisherRESTAPIServiceComponent.java | 13 +- .../extension/rest/api/util/ScopeUtils.java | 57 ++++++++ .../pom.xml | 15 +- .../webapp/publisher/APIPublisherService.java | 2 - .../publisher/APIPublisherServiceImpl.java | 49 ++++--- .../publisher/APIPublisherStartupHandler.java | 6 - components/apimgt-extensions/pom.xml | 18 ++- pom.xml | 2 +- 24 files changed, 377 insertions(+), 390 deletions(-) delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java delete mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api}/pom.xml (96%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/APIApplicationServices.java (58%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/APIApplicationServicesImpl.java (73%) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/bean/RegistrationProfile.java (96%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/constants/Constants.java (97%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/dto/APIApplicationKey.java (97%) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/exceptions/APIApplicationServicesException.java (83%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/exceptions/BadRequestException.java (91%) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api => io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api}/internal/PublisherRESTAPIServiceComponent.java (62%) create mode 100644 components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java deleted file mode 100644 index a0bb43217d0..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/PublisherRESTAPIServices.java +++ /dev/null @@ -1,96 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; - -import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; -import okhttp3.*; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.ssl.Base64; -import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.Scope; - -import java.io.IOException; -import static io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl.getOkHttpClient; - -public class PublisherRESTAPIServices { - private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); - private static final OkHttpClient client = getOkHttpClient(); - private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - - public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIApplicationServicesException, BadRequestException { - - String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); - String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; - - Request request = new Request.Builder() - .url(getScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken()) - .head() - .build(); - try { - Response response = client.newCall(request).execute(); - if (response.code() == HttpStatus.SC_OK){ - return true; - }else if(HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret() ); - //max attempt count - return isSharedScopeNameExists(apiApplicationKey,refreshedAccessToken, key); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()){ - log.info(response); - throw new BadRequestException(response.toString()); - } else { - return false; - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; - throw new APIApplicationServicesException(msg); - } - } - - public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIApplicationServicesException, BadRequestException { - - String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); - - JSONObject setScope = new JSONObject(); - setScope.put("name", scope.getKey()); - setScope.put("displayName", scope.getName()); - setScope.put("description", scope.getDescription()); - setScope.put("bindings", scope.getRoles()); - - - RequestBody requestBody = RequestBody.Companion.create(setScope.toString(), JSON); - Request request = new Request.Builder() - .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccessToken()) - .put(requestBody) - .build(); - - try { - Response response = client.newCall(request).execute(); - if (response.code() == HttpStatus.SC_OK) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefreshToken(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - log.info(response); - throw new BadRequestException(response.toString()); - } else { - return false; - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; - throw new APIApplicationServicesException(msg); - } - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java deleted file mode 100644 index e738c71f458..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/AccessTokenInfo.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; - -/** - * This holds the token information that return from the token endpoint. - */ -public class AccessTokenInfo { - - private String tokenType; - private long expiresIn; - private String refreshToken; - private String accessToken; - private String scope; - - public String getTokenType() { - return tokenType; - } - - public void setTokenType(String tokenType) { - this.tokenType = tokenType; - } - - public long getExpiresIn() { - return expiresIn; - } - - public void setExpiresIn(long expiresIn) { - this.expiresIn = expiresIn; - } - - public String getRefreshToken() { - return refreshToken; - } - - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java deleted file mode 100644 index 885f3ead7aa..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIDataHolder.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; - -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; - -public class PublisherRESTAPIDataHolder { - - private static final PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); - - private APIApplicationServices apiApplicationServices; -// -// private PublisherRESTAPIServices publisherRESTAPIServices; - - public static PublisherRESTAPIDataHolder getInstance(){ - return thisInstance; - } - public APIApplicationServices getApiApplicationServices() { - return apiApplicationServices; - } - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } -// public PublisherRESTAPIServices getPublisherRESTAPIServices() { -// return publisherRESTAPIServices; -// } -// public void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { -// this.publisherRESTAPIServices = publisherRESTAPIServices; -// } - -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java deleted file mode 100644 index 1d532d17a7c..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/PublisherRESTAPIUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.wso2.carbon.utils.CarbonUtils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; - -public class PublisherRESTAPIUtil { - private static final Log log = LogFactory.getLog(PublisherRESTAPIUtil.class); - private static final String HTTPS_PROTOCOL = "https"; - - /** - * Return a http client instance - * - * @param protocol- service endpoint protocol http/https - * @return - */ - public static HttpClient getHttpClient(String protocol) - throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { - HttpClient httpclient; - if (HTTPS_PROTOCOL.equals(protocol)) { - SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); - httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); - } else { - httpclient = HttpClients.createDefault(); - } - return httpclient; - } - - public static String getResponseString(HttpResponse httpResponse) throws IOException { - BufferedReader br = null; - try { - br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); - String readLine; - String response = ""; - while (((readLine = br.readLine()) != null)) { - response += readLine; - } - return response; - } finally { - EntityUtils.consumeQuietly(httpResponse.getEntity()); - if (br != null) { - try { - br.close(); - } catch (IOException e) { - log.warn("Error while closing the connection! " + e.getMessage()); - } - } - } - } -} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java deleted file mode 100644 index db8011521dd..00000000000 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/util/ScopeUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.util; - -/** - * This class represents the data that are required to register - * the oauth application. - */ -public class ScopeUtils { - - private String key; - private String name; - private String roles; - private String description; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getRoles() { - return roles; - } - - public void setRoles(String roles) { - this.roles = roles; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String toJSON() { - String jsonString = - "{\"name\": \"" + key + "\",\"displayName\": \"" + name + - "\", \"description\": \"" + description + "\"," + "\"bindings\": [" + - roles + "]" + " }"; - -// String jsonString = -// "{\"name\": \"" + name + "\",\"displayName\": \"" + name + -// "\", \"description\": \"" + description + "\"," + "\"bindings\": [" + -// "\"Internal/devicemgt-user\"" + -// "]" + " }"; - return jsonString; - } -} \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml similarity index 96% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml index 0b2d3f034b1..2471b48fed9 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml @@ -27,7 +27,7 @@ 4.0.0 - io.entgra.devicemgt.apimgt.extension.publisher.api + io.entgra.devicemgt.apimgt.extension.rest.api bundle Entgra - Device API Management Extension Publisher API Entgra - Device API Management Extension Publisher API @@ -86,6 +86,10 @@ org.json.wso2 json + + com.google.code.gson + gson + @@ -106,11 +110,11 @@ ${carbon.device.mgt.version} Publisher API Management Bundle - io.entgra.devicemgt.apimgt.extension.publisher.api.internal + io.entgra.devicemgt.apimgt.extension.rest.api.internal - !io.entgra.devicemgt.apimgt.extension.publisher.api.internal, - io.entgra.devicemgt.apimgt.extension.publisher.api.* + !io.entgra.devicemgt.apimgt.extension.rest.api.internal, + io.entgra.devicemgt.apimgt.extension.rest.api.* javax.net.ssl, diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java similarity index 58% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java index 401f680214f..1816df83d8a 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java @@ -1,8 +1,8 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; +package io.entgra.devicemgt.apimgt.extension.rest.api; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; public interface APIApplicationServices { diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java similarity index 73% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java index 5e6439edbbd..50c6c7d4d45 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java @@ -1,12 +1,18 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api; +package io.entgra.devicemgt.apimgt.extension.rest.api; import com.google.gson.Gson; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; import org.json.JSONObject; -import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import okhttp3.*; +import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.RequestBody; +import okhttp3.Credentials; +import okhttp3.ConnectionPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -17,6 +23,7 @@ import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; +import java.util.concurrent.TimeUnit; public class APIApplicationServicesImpl implements APIApplicationServices { @@ -33,16 +40,16 @@ public class APIApplicationServicesImpl implements APIApplicationServices { JSONObject jsonObject = new JSONObject(); jsonObject.put("callbackUrl", Constants.EMPTY_STRING); - jsonObject.put("clientName",Constants.CLIENT_NAME); - jsonObject.put("grantType",Constants.GRANT_TYPE); - jsonObject.put("owner",Constants.OWNER); - jsonObject.put("saasApp",true); + jsonObject.put("clientName", Constants.CLIENT_NAME); + jsonObject.put("grantType", Constants.GRANT_TYPE); + jsonObject.put("owner", Constants.OWNER); + jsonObject.put("saasApp", true); RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); - String keyManagerEndpoint = "https://localhost:9443/client-registration/v0.17/register"; + String applicationEndpoint = "https://localhost:9443/client-registration/v0.17/register"; Request request = new Request.Builder() - .url(keyManagerEndpoint) + .url(applicationEndpoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) .post(requestBody) .build(); @@ -58,13 +65,13 @@ public class APIApplicationServicesImpl implements APIApplicationServices { @Override public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) - throws APIApplicationServicesException { + throws APIApplicationServicesException { JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.PASSWORD_GRANT_TYPE); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); //ToDo: Remove hardcoded value - params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME,"admin"); - params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD,"admin"); - params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES); + params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin"); + params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin"); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); return getToken(params, consumerKey, consumerSecret); } @@ -73,18 +80,17 @@ public class APIApplicationServicesImpl implements APIApplicationServices { throws APIApplicationServicesException { JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME,Constants.REFRESH_TOKEN_GRANT_TYPE); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); //ToDo: Remove hardcoded value params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken); - params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); return getToken(params, consumerKey, consumerSecret); } public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret) - throws APIApplicationServicesException{ + throws APIApplicationServicesException { RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); - //application/x-www-form-urlencoded String tokenEndPoint = "https://localhost:9443/oauth2/token"; Request request = new Request.Builder() @@ -117,9 +123,14 @@ public class APIApplicationServicesImpl implements APIApplicationServices { java.security.cert.X509Certificate[] certs, String authType) { } }; - return new OkHttpClient.Builder() + OkHttpClient okHttpClient = new OkHttpClient.Builder() + .connectTimeout(300, TimeUnit.SECONDS) + .writeTimeout(300, TimeUnit.SECONDS) + .readTimeout(300, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(500, 500, TimeUnit.SECONDS)) .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) .hostnameVerifier((hostname, sslSession) -> true).build(); + return okHttpClient; } private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { @@ -129,9 +140,11 @@ public class APIApplicationServicesImpl implements APIApplicationServices { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } + public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } + public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java new file mode 100644 index 00000000000..c2c0202c8a7 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -0,0 +1,137 @@ +package io.entgra.devicemgt.apimgt.extension.rest.api; + +import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.devicemgt.apimgt.extension.rest.api.util.ScopeUtils; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.RequestBody; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.ssl.Base64; +import org.json.JSONObject; +import org.wso2.carbon.apimgt.api.model.Scope; + +import java.io.IOException; + +import static io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl.getOkHttpClient; + +public class PublisherRESTAPIServices { + private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); + private static final OkHttpClient client = getOkHttpClient(); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIApplicationServicesException, BadRequestException { + + String getScopesUrl = "https://localhost:9443/api/am/publisher/v2/scopes?limit=1000"; + Request request = new Request.Builder() + .url(getScopesUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (response.code() == HttpStatus.SC_OK) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } 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()) { + log.info(response); + throw new BadRequestException(response.toString()); + } else { + return null; + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); + } + } + + public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) + throws APIApplicationServicesException, BadRequestException { + + String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); + String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; + + Request request = new Request.Builder() + .url(getScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .head() + .build(); + try { + Response response = client.newCall(request).execute(); + if (response.code() == HttpStatus.SC_OK) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo 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()) { + log.info(response); + throw new BadRequestException(response.toString()); + } else { + return false; + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); + } + } + + public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIApplicationServicesException, BadRequestException { + + String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); + + ScopeUtils scopeUtil = new ScopeUtils(); + scopeUtil.setKey(scope.getKey()); + scopeUtil.setName(scope.getName()); + scopeUtil.setDescription(scope.getDescription()); + scopeUtil.setRoles(scope.getRoles()); + String scopeString = scopeUtil.toJSON(); + + RequestBody requestBody = RequestBody.create(JSON, scopeString); + Request request = new Request.Builder() + .url(updateScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .put(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + if (response.code() == HttpStatus.SC_OK) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo 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()) { + log.info(response); + throw new BadRequestException(response.toString()); + } else { + return false; + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + throw new APIApplicationServicesException(msg); + } + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java similarity index 96% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java index 242788ed26e..c4544445980 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/bean/RegistrationProfile.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java @@ -1,4 +1,4 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.bean; +package io.entgra.devicemgt.apimgt.extension.rest.api.bean; /** * This class represents the data that are required to register diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java similarity index 97% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java index 0144e129f10..4e92ad6d93e 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/constants/Constants.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java @@ -1,4 +1,4 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.constants; +package io.entgra.devicemgt.apimgt.extension.rest.api.constants; public final class Constants { diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java similarity index 97% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java index d0fc3b9f68b..e18c4b3d90a 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/dto/APIApplicationKey.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java @@ -1,4 +1,4 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.dto; +package io.entgra.devicemgt.apimgt.extension.rest.api.dto; /** * This holds api application consumer id and secret. diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java new file mode 100644 index 00000000000..f9c9a4db673 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java @@ -0,0 +1,53 @@ +package io.entgra.devicemgt.apimgt.extension.rest.api.dto; + +/** + * This holds the token information that return from the token endpoint. + */ +public class AccessTokenInfo { + + private String token_type; + private long expires_in; + private String refresh_token; + private String access_token; + private String scope; + + public String getToken_type() { + return token_type; + } + + public void setToken_type(String token_type) { + this.token_type = token_type; + } + + public long getExpires_in() { + return expires_in; + } + + public void setExpires_in(long expires_in) { + this.expires_in = expires_in; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java similarity index 83% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java index bd7aa85cd96..897146bbcd5 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/APIApplicationServicesException.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java @@ -1,4 +1,4 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; +package io.entgra.devicemgt.apimgt.extension.rest.api.exceptions; public class APIApplicationServicesException extends Exception{ diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java similarity index 91% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java index 427c4b5e358..00d4b423fa2 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/exceptions/BadRequestException.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java @@ -22,9 +22,7 @@ /** * Custom exception class for handling bad request exceptions. */ -package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; - -import okhttp3.Response; +package io.entgra.devicemgt.apimgt.extension.rest.api.exceptions; public class BadRequestException extends Exception { diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java new file mode 100644 index 00000000000..ce651eeb368 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java @@ -0,0 +1,21 @@ +package io.entgra.devicemgt.apimgt.extension.rest.api.internal; + +import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; + +public class PublisherRESTAPIDataHolder { + + private static final PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); + + private APIApplicationServices apiApplicationServices; + + public static PublisherRESTAPIDataHolder getInstance(){ + return thisInstance; + } + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } + +} diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java similarity index 62% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java rename to components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java index d34012c1f46..3817e365a4f 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.publisher.api/src/main/java/io.entgra.devicemgt.apimgt.extension.publisher.api/internal/PublisherRESTAPIServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java @@ -1,15 +1,14 @@ -package io.entgra.devicemgt.apimgt.extension.publisher.api.internal; +package io.entgra.devicemgt.apimgt.extension.rest.api.internal; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; +import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; /** - * @scr.component name="io.entgra.devicemgt.apimgt.extension.publisher.api.internal.PublisherRESTAPIServiceComponent" + * @scr.component name="io.entgra.devicemgt.apimgt.extension.rest.api.internal.PublisherRESTAPIServiceComponent" * immediate="true" */ public class PublisherRESTAPIServiceComponent { @@ -23,10 +22,6 @@ public class PublisherRESTAPIServiceComponent { try { BundleContext bundleContext = componentContext.getBundleContext(); -// PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); -// bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); -// PublisherRESTAPIDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java new file mode 100644 index 00000000000..8a7e6d2fbbb --- /dev/null +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java @@ -0,0 +1,57 @@ +package io.entgra.devicemgt.apimgt.extension.rest.api.util; + +/** + * This class represents the data that are required to register + * the oauth application. + */ +public class ScopeUtils { + + private String key; + private String name; + private String roles; + private String description; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String toJSON() { + String jsonString = "{\n" + + " \"name\":\" " + key + "\",\n" + + " \"displayName\":\" " + name + "\",\n" + + " \"description\":\" " + description + " \",\n" + + " \"bindings\":[\n" + + " \" " + roles + " \"\n" + + " ]\n" + + "}"; + return jsonString; + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index c08735db3fd..d1bc922c545 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -124,9 +124,13 @@ org.wso2.carbon.devicemgt - io.entgra.devicemgt.apimgt.extension.publisher.api + io.entgra.devicemgt.apimgt.extension.rest.api provided + + org.json.wso2 + json + @@ -170,9 +174,9 @@ org.scannotation;version="1.0", org.scannotation.archiveiterator;version="1.0", org.w3c.dom, - io.entgra.devicemgt.apimgt.extension.publisher.api, - io.entgra.devicemgt.apimgt.extension.publisher.api.dto, - io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions, + io.entgra.devicemgt.apimgt.extension.rest.api, + io.entgra.devicemgt.apimgt.extension.rest.api.dto, + io.entgra.devicemgt.apimgt.extension.rest.api.exceptions, org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, @@ -195,7 +199,8 @@ org.wso2.carbon.utils;version="4.6", org.wso2.carbon.utils.multitenancy;version="4.6", org.wso2.carbon.apimgt.impl.definitions, - org.apache.commons.lang + org.apache.commons.lang, + org.json jsr311-api;scope=compile|runtime;inline=false diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java index 85dcf72d138..fd111a46de9 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java @@ -18,8 +18,6 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; - -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; /** diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 2fe4883df58..0aebefbaa49 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,18 +18,20 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; -import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; +import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.devicemgt.apimgt.extension.rest.api.PublisherRESTAPIServices; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; +import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.BadRequestException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.api.model.DocumentationType; +import org.json.JSONArray; +import org.json.JSONObject; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.FaultGatewaysException; @@ -382,6 +384,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); + JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); try { String fileName = @@ -427,8 +430,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { } scope.setRoles(roleString); -// if (apiProvider.isSharedScopeNameExists(scope.getKey(), tenantDomain)) { -// apiProvider.updateSharedScope(scope, tenantDomain); + //Set scope id which related to the scope key + JSONArray scopeList = (JSONArray) scopeObject.get("list"); + JSONObject object = null; + for (int i = 0; i < scopeList.length(); i++) { + JSONObject obj = null; + obj = scopeList.getJSONObject(i); + if (obj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { + object = obj; + } + } + scope.setId(object.getString("id")); + if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); } else { @@ -449,17 +462,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } -// catch (UserStoreException e) { -// String msg = "Error occurred while reading tenant admin username"; -// log.error(msg, e); -// throw new APIManagerPublisherException(e); -// } -// catch (APIManagementException e) { -// String msg = "Error occurred while loading api provider"; -// log.error(msg, e); -// throw new APIManagerPublisherException(e); -// } - finally { + catch (APIApplicationServicesException e) { + log.error(e); + throw new RuntimeException(e); + } catch (BadRequestException e) { + log.error(e); + throw new RuntimeException(e); + } finally { PrivilegedCarbonContext.endTenantFlow(); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index 3933f60716d..01b1cd810cf 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -19,12 +19,6 @@ package org.wso2.carbon.apimgt.webapp.publisher; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 137f35b5724..2c175c1ea1e 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -31,17 +31,25 @@ org.wso2.carbon.apimgt.api - org.json.wso2 - json + com.squareup.okhttp3 + okhttp - io.github.openfeign - feign-okhttp + org.json.wso2 + json com.google.code.gson gson + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + 4.0.0 @@ -58,7 +66,7 @@ org.wso2.carbon.apimgt.keymgt.extension org.wso2.carbon.apimgt.keymgt.extension.api io.entgra.device.mgt.core.apimgt.analytics.extension - io.entgra.devicemgt.apimgt.extension.publisher.api + io.entgra.devicemgt.apimgt.extension.rest.api diff --git a/pom.xml b/pom.xml index b5435d623d5..e52350555b1 100644 --- a/pom.xml +++ b/pom.xml @@ -240,7 +240,7 @@ org.wso2.carbon.devicemgt - io.entgra.devicemgt.apimgt.extension.publisher.api + io.entgra.devicemgt.apimgt.extension.rest.api ${carbon.device.mgt.version} From 34ae40e233885417b9f432460841b9c68101db5d Mon Sep 17 00:00:00 2001 From: pasindu Date: Fri, 21 Apr 2023 00:53:50 +0530 Subject: [PATCH 08/17] Code format fixes --- .../rest/api/APIApplicationServices.java | 19 +++ .../rest/api/APIApplicationServicesImpl.java | 19 ++- .../rest/api/PublisherRESTAPIServices.java | 18 +++ .../rest/api/bean/RegistrationProfile.java | 116 ++++++++++-------- .../rest/api/constants/Constants.java | 9 -- .../rest/api/dto/APIApplicationKey.java | 23 +++- .../rest/api/dto/AccessTokenInfo.java | 18 +++ .../APIApplicationServicesException.java | 36 +++++- .../api/exceptions/BadRequestException.java | 27 ++-- .../internal/PublisherRESTAPIDataHolder.java | 22 +++- .../PublisherRESTAPIServiceComponent.java | 18 +++ .../extension/rest/api/util/ScopeUtils.java | 21 +++- .../publisher/APIPublisherServiceImpl.java | 12 +- .../publisher/APIPublisherStartupHandler.java | 4 +- .../lifecycle/util/AnnotationProcessor.java | 4 +- components/apimgt-extensions/pom.xml | 26 ---- 16 files changed, 273 insertions(+), 119 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java index 1816df83d8a..d420bbc6222 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api; import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; @@ -9,6 +27,7 @@ public interface APIApplicationServices { APIApplicationKey createAndRetrieveApplicationCredentials() throws APIApplicationServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIApplicationServicesException; + AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIApplicationServicesException; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java index 50c6c7d4d45..d1613f3d74f 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api; import com.google.gson.Gson; @@ -81,7 +99,6 @@ public class APIApplicationServicesImpl implements APIApplicationServices { JSONObject params = new JSONObject(); params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); - //ToDo: Remove hardcoded value params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken); params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); return getToken(params, consumerKey, consumerSecret); diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java index c2c0202c8a7..7148286aa31 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api; import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java index c4544445980..97033b6d5cb 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.bean; /** @@ -6,63 +24,63 @@ package io.entgra.devicemgt.apimgt.extension.rest.api.bean; */ public class RegistrationProfile { - private String callbackUrl; - private String clientName; - private String tokenScope; - private String owner; - private String grantType; - private String applicationType; + private String callbackUrl; + private String clientName; + private String tokenScope; + private String owner; + private String grantType; + private String applicationType; private boolean isSaasApp; - private static final String TAG = RegistrationProfile.class.getSimpleName(); + private static final String TAG = RegistrationProfile.class.getSimpleName(); - public String getCallbackUrl() { - return callbackUrl; - } + public String getCallbackUrl() { + return callbackUrl; + } - public void setCallbackUrl(String callBackUrl) { - this.callbackUrl = callBackUrl; - } + public void setCallbackUrl(String callBackUrl) { + this.callbackUrl = callBackUrl; + } - public String getClientName() { - return clientName; - } + public String getClientName() { + return clientName; + } - public void setClientName(String clientName) { - this.clientName = clientName; - } + public void setClientName(String clientName) { + this.clientName = clientName; + } - public String getTokenScope() { - return tokenScope; - } + public String getTokenScope() { + return tokenScope; + } - public void setTokenScope(String tokenScope) { - this.tokenScope = tokenScope; - } + public void setTokenScope(String tokenScope) { + this.tokenScope = tokenScope; + } - public String getOwner() { - return owner; - } + public String getOwner() { + return owner; + } - public void setOwner(String owner) { - this.owner = owner; - } + public void setOwner(String owner) { + this.owner = owner; + } - public String getGrantType() { - return grantType; - } + public String getGrantType() { + return grantType; + } - public void setGrantType(String grantType) { - this.grantType = grantType; - } + public void setGrantType(String grantType) { + this.grantType = grantType; + } - public String getApplicationType() { - return applicationType; - } + public String getApplicationType() { + return applicationType; + } - public void setApplicationType(String applicationType) { - this.applicationType = applicationType; - } + public void setApplicationType(String applicationType) { + this.applicationType = applicationType; + } public boolean isSaasApp() { return isSaasApp; @@ -73,10 +91,10 @@ public class RegistrationProfile { } public String toJSON() { - String jsonString = - "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + - "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + - "\", \"saasApp\" : " + isSaasApp + " }\n"; - return jsonString; - } + String jsonString = + "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + + "\", \"saasApp\" : " + isSaasApp + " }\n"; + return jsonString; + } } \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java index 4e92ad6d93e..73b4a3a842d 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java @@ -20,15 +20,6 @@ public final class Constants { public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; public static final int ADAPTER_CONF_DEFAULT_KEEP_ALIVE = 60000; - public static final int DEFAULT_MIN_THREAD_POOL_SIZE = 8; - public static final int DEFAULT_MAX_THREAD_POOL_SIZE = 100; - public static final int DEFAULT_EXECUTOR_JOB_QUEUE_SIZE = 2000; - public static final long DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS = 20000; - public static final String ADAPTER_MIN_THREAD_POOL_SIZE_NAME = "minThread"; - public static final String ADAPTER_MAX_THREAD_POOL_SIZE_NAME = "maxThread"; - public static final String ADAPTER_KEEP_ALIVE_TIME_NAME = "keepAliveTimeInMillis"; - public static final String ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME = "jobQueueSize"; - public static final String DEFAULT_CALLBACK = ""; public static final String DEFAULT_PASSWORD = ""; public static final String TOKEN_SCOPE = "production"; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java index e18c4b3d90a..cbadf626b26 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java @@ -1,7 +1,25 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.dto; /** - * This holds api application consumer id and secret. + * This holds the consumer application information that return from the register application endpoint */ public class APIApplicationKey { private String clientName; @@ -14,7 +32,7 @@ public class APIApplicationKey { private String jsonAppAttribute; private String tokenType; - public APIApplicationKey(String clientId, String clientSecret){ + public APIApplicationKey(String clientId, String clientSecret) { this.clientId = clientId; this.clientSecret = clientSecret; } @@ -34,6 +52,7 @@ public class APIApplicationKey { public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } + public String getClientName() { return clientName; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java index f9c9a4db673..061e7e898d1 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.dto; /** diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java index 897146bbcd5..35a247a190b 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java @@ -1,12 +1,38 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.exceptions; -public class APIApplicationServicesException extends Exception{ +public class APIApplicationServicesException extends Exception { - public APIApplicationServicesException() {super();} + public APIApplicationServicesException() { + super(); + } - public APIApplicationServicesException(String message) {super();} + public APIApplicationServicesException(String message) { + super(); + } - public APIApplicationServicesException(String message, Throwable cause){super();} + public APIApplicationServicesException(String message, Throwable cause) { + super(); + } - public APIApplicationServicesException(Throwable cause){super();} + public APIApplicationServicesException(Throwable cause) { + super(); + } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java index 00d4b423fa2..25cebe82fc5 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java @@ -1,22 +1,19 @@ /* + * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * * Copyright (c) 2022, 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. + * 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. */ /** diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java index ce651eeb368..9545a94fb40 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.internal; import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; @@ -8,12 +26,14 @@ public class PublisherRESTAPIDataHolder { private APIApplicationServices apiApplicationServices; - public static PublisherRESTAPIDataHolder getInstance(){ + public static PublisherRESTAPIDataHolder getInstance() { return thisInstance; } + public APIApplicationServices getApiApplicationServices() { return apiApplicationServices; } + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { this.apiApplicationServices = apiApplicationServices; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java index 3817e365a4f..fdf74638c60 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.internal; import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java index 8a7e6d2fbbb..5716ebfcb1b 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java +++ b/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java @@ -1,8 +1,25 @@ +/* + * Copyright (c) 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.devicemgt.apimgt.extension.rest.api.util; /** - * This class represents the data that are required to register - * the oauth application. + * This class represents the scope data. */ public class ScopeUtils { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 0aebefbaa49..5452a4f8bd5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -432,15 +432,15 @@ public class APIPublisherServiceImpl implements APIPublisherService { //Set scope id which related to the scope key JSONArray scopeList = (JSONArray) scopeObject.get("list"); - JSONObject object = null; + JSONObject jsonObject = null; for (int i = 0; i < scopeList.length(); i++) { - JSONObject obj = null; - obj = scopeList.getJSONObject(i); - if (obj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { - object = obj; + JSONObject scopeObj = null; + scopeObj = scopeList.getJSONObject(i); + if (scopeObj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { + jsonObject = scopeObj; } } - scope.setId(object.getString("id")); + scope.setId(jsonObject.getString("id")); if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index 01b1cd810cf..949f16c3e9e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -24,6 +24,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.core.ServerStartupObserver; + import java.util.Stack; public class APIPublisherStartupHandler implements ServerStartupObserver { @@ -34,10 +35,12 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { private static final int MAX_RETRY_COUNT = 5; private static Stack failedAPIsStack = new Stack<>(); private static Stack currentAPIsStack; + private APIPublisherService publisher; @Override public void completingServerStartup() { + } @Override @@ -52,7 +55,6 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { log.debug("Total number of unpublished APIs: " + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); } - publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); int retryCount = 0; while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index 7cdede5bcb6..f41c07967a5 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -299,7 +299,7 @@ public class AnnotationProcessor { // if (scope != null) { // resource.setScope(scope); // } else { -// log.warn("ScopeUtils is not defined for '" + makeContextURLReady(resourceRootContext) + +// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); // scope = new ApiScope(); // scope.setName(DEFAULT_SCOPE_NAME); @@ -537,7 +537,7 @@ public class AnnotationProcessor { if (scope != null) { apiResource.setScope(scope); } else { -// log.warn("ScopeUtils is not defined for '" + makeContextURLReady(resourceRootContext) + +// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); scope = new ApiScope(); scope.setName(DEFAULT_SCOPE_NAME); diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 2c175c1ea1e..c4bfc0d36d5 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,32 +25,6 @@ 5.0.26-SNAPSHOT ../../pom.xml - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.api - - - com.squareup.okhttp3 - okhttp - - - org.json.wso2 - json - - - com.google.code.gson - gson - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - 4.0.0 apimgt-extensions From 07c157e9d6985e989e2dcdd6e8bd44e1b6511678 Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 25 Apr 2023 14:02:19 +0530 Subject: [PATCH 09/17] Fix URL Generation, Make feature, Refactor the module --- .../pom.xml | 58 +++++------------ .../rest/api/APIApplicationServices.java | 14 ++--- .../rest/api/APIApplicationServicesImpl.java | 51 ++++++++------- .../rest/api/PublisherRESTAPIServices.java | 63 +++++++++++-------- .../rest/api/bean/RegistrationProfile.java | 2 +- .../rest/api/constants/Constants.java | 35 ++++++++--- .../rest/api/dto/APIApplicationKey.java | 2 +- .../rest/api/dto/AccessTokenInfo.java | 2 +- .../api/exceptions/APIServicesException.java} | 18 +++--- .../api/exceptions/BadRequestException.java | 2 +- .../internal/PublisherRESTAPIDataHolder.java | 26 ++++++-- .../PublisherRESTAPIServiceComponent.java | 29 +++++++-- .../extension/rest/api/util/ScopeUtils.java | 2 +- .../pom.xml | 8 +-- .../webapp/publisher/APIPublisherService.java | 1 + .../publisher/APIPublisherServiceImpl.java | 35 ++++++----- components/apimgt-extensions/pom.xml | 2 +- .../pom.xml | 7 +++ pom.xml | 2 +- 19 files changed, 209 insertions(+), 150 deletions(-) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api => io.entgra.device.mgt.core.apimgt.extension.rest.api}/pom.xml (71%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/APIApplicationServices.java (64%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/APIApplicationServicesImpl.java (80%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/PublisherRESTAPIServices.java (72%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/bean/RegistrationProfile.java (97%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/constants/Constants.java (57%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/dto/APIApplicationKey.java (97%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/dto/AccessTokenInfo.java (96%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/APIServicesException.java} (63%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/exceptions/BadRequestException.java (93%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java (52%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java (59%) rename components/apimgt-extensions/{io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt => io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core}/apimgt/extension/rest/api/util/ScopeUtils.java (96%) diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml similarity index 71% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 2471b48fed9..7fb3f1726ff 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -27,21 +27,13 @@ 4.0.0 - io.entgra.devicemgt.apimgt.extension.rest.api + io.entgra.device.mgt.core.apimgt.extension.rest.api bundle - Entgra - Device API Management Extension Publisher API - Entgra - Device API Management Extension Publisher API + Entgra - Device Management Extension for APIM REST API + Entgra - Device Management Extension for APIM REST API https://entgra.io - - org.apache.httpcomponents.wso2 - httpcore - - - org.wso2.orbit.org.apache.httpcomponents - httpclient - org.wso2.carbon org.wso2.carbon.logging @@ -90,6 +82,11 @@ com.google.code.gson gson + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + provided + @@ -110,31 +107,23 @@ ${carbon.device.mgt.version} Publisher API Management Bundle - io.entgra.devicemgt.apimgt.extension.rest.api.internal + io.entgra.device.mgt.core.apimgt.extension.rest.api.internal - !io.entgra.devicemgt.apimgt.extension.rest.api.internal, - io.entgra.devicemgt.apimgt.extension.rest.api.* + !io.entgra.device.mgt.core.apimgt.extension.rest.api.internal, + io.entgra.device.mgt.core.apimgt.extension.rest.api.* javax.net.ssl, - org.apache.commons.logging, - org.apache.http;version="${httpclient.version.range}", - org.apache.http.client;version="${httpclient.version.range}", - org.apache.http.client.methods;version="${httpclient.version.range}", - org.apache.http.conn.socket, - org.apache.http.conn.ssl, - org.apache.http.entity, - org.apache.http.impl.client, - org.apache.http.util;version="${httpclient.version.range}", - org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", - org.wso2.carbon.core, - org.apache.commons.ssl, - org.apache.commons.httpclient, + org.wso2.carbon.core;version="4.6", + org.wso2.carbon.core.util;version="4.6", org.wso2.carbon.apimgt.api.model, okhttp3.*, + org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.impl.utils;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.impl.internal;version="${carbon.api.mgt.version.range}", org.json @@ -166,22 +155,7 @@ - - - - - - - - - - - - - - true - \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 similarity index 64% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServices.java rename to 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 index d420bbc6222..51d7d20b17f 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 @@ -16,18 +16,18 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api; +package io.entgra.device.mgt.core.apimgt.extension.rest.api; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; +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 APIApplicationServicesException; + APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; - AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIApplicationServicesException; + AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; - AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIApplicationServicesException; + AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIServicesException; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 similarity index 80% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/APIApplicationServicesImpl.java rename to 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 index d1613f3d74f..bffb97893a6 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 @@ -16,14 +16,14 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api; +package io.entgra.device.mgt.core.apimgt.extension.rest.api; import com.google.gson.Gson; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import org.json.JSONObject; -import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; +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; @@ -33,6 +33,8 @@ import okhttp3.Credentials; import okhttp3.ConnectionPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; @@ -50,22 +52,24 @@ public class APIApplicationServicesImpl implements APIApplicationServices { private static final Gson gson = new Gson(); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String msg = null; - // private ApiApplicationConfigurations ApplicationConfig = null; + APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). + getAPIManagerConfigurationService().getAPIManagerConfiguration(); @Override public APIApplicationKey createAndRetrieveApplicationCredentials() - throws APIApplicationServicesException { + throws APIServicesException { + + String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); + String owner = config.getFirstProperty(Constants.SERVER_USER); JSONObject jsonObject = new JSONObject(); jsonObject.put("callbackUrl", Constants.EMPTY_STRING); jsonObject.put("clientName", Constants.CLIENT_NAME); jsonObject.put("grantType", Constants.GRANT_TYPE); - jsonObject.put("owner", Constants.OWNER); + jsonObject.put("owner", owner); jsonObject.put("saasApp", true); RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); - String applicationEndpoint = "https://localhost:9443/client-registration/v0.17/register"; - Request request = new Request.Builder() .url(applicationEndpoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) @@ -76,26 +80,29 @@ public class APIApplicationServicesImpl implements APIApplicationServices { return gson.fromJson(response.body().string(), APIApplicationKey.class); } catch (IOException e) { msg = "Error occurred while processing the response"; - log.error(msg); - throw new APIApplicationServicesException(msg); + log.error(msg, e); + throw new APIServicesException(e); } } @Override public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) - throws APIApplicationServicesException { + throws APIServicesException { + + String userName = config.getFirstProperty(Constants.SERVER_USER); + String userPassword = config.getFirstProperty(Constants.SERVER_PASSWORD); + JSONObject params = new JSONObject(); params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); - //ToDo: Remove hardcoded value - params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin"); - params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin"); + params.put(Constants.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 APIApplicationServicesException { + throws APIServicesException { JSONObject params = new JSONObject(); params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); @@ -105,11 +112,11 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret) - throws APIApplicationServicesException { + throws APIServicesException { - RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); - String tokenEndPoint = "https://localhost:9443/oauth2/token"; + 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)) @@ -121,8 +128,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices { return gson.fromJson(response.body().string(), AccessTokenInfo.class); } catch (IOException e) { msg = "Error occurred while processing the response"; - log.error(msg); - throw new APIApplicationServicesException(msg); + log.error(msg, e); + throw new APIServicesException(e); } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 similarity index 72% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/PublisherRESTAPIServices.java rename to 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 7148286aa31..5fedcca952d 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/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 @@ -16,14 +16,14 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api; +package io.entgra.device.mgt.core.apimgt.extension.rest.api; -import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.BadRequestException; -import io.entgra.devicemgt.apimgt.extension.rest.api.util.ScopeUtils; +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.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -39,26 +39,31 @@ import org.wso2.carbon.apimgt.api.model.Scope; import java.io.IOException; -import static io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl.getOkHttpClient; +import static io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl.getOkHttpClient; public class PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); private static final OkHttpClient client = getOkHttpClient(); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final String host = System.getProperty(Constants.IOT_CORE_HOST); + private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIApplicationServicesException, BadRequestException { + throws APIServicesException, BadRequestException { + - String getScopesUrl = "https://localhost:9443/api/am/publisher/v2/scopes?limit=1000"; + String getAllScopesUrl = "https://" + "://" + host + ":" + port + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() - .url(getScopesUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .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 (response.code() == HttpStatus.SC_OK) { + if (HttpStatus.SC_OK == response.code()) { JSONObject jsonObject = new JSONObject(response.body().string()); return jsonObject; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { @@ -68,22 +73,24 @@ public class PublisherRESTAPIServices { //TODO: max attempt count return getScopes(apiApplicationKey, refreshedAccessToken); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - log.info(response); - throw new BadRequestException(response.toString()); + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); } else { return null; } } catch (IOException e) { String msg = "Error occurred while processing the response"; - throw new APIApplicationServicesException(msg); + log.error(msg, e); + throw new APIServicesException(e); } } public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIApplicationServicesException, BadRequestException { + throws APIServicesException, BadRequestException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); - String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + keyValue; + String getScopeUrl = "https://" + "://" + host + ":" + port + Constants.GET_SCOPE + keyValue; Request request = new Request.Builder() .url(getScopeUrl) @@ -101,21 +108,23 @@ public class PublisherRESTAPIServices { //TODO: max attempt count return isSharedScopeNameExists(apiApplicationKey, refreshedAccessToken, key); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - log.info(response); - throw new BadRequestException(response.toString()); + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); } else { return false; } } catch (IOException e) { String msg = "Error occurred while processing the response"; - throw new APIApplicationServicesException(msg); + log.error(msg, e); + throw new APIServicesException(e); } } public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIApplicationServicesException, BadRequestException { + throws APIServicesException, BadRequestException { - String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + scope.getId(); + String updateScopeUrl = "https://" + "://" + host + ":" + port + Constants.GET_SCOPE + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -142,14 +151,16 @@ public class PublisherRESTAPIServices { //TODO: max attempt count return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - log.info(response); - throw new BadRequestException(response.toString()); + String msg = "Bad Request, Invalid scope object"; + log.error(msg); + throw new BadRequestException(msg); } else { return false; } } catch (IOException e) { String msg = "Error occurred while processing the response"; - throw new APIApplicationServicesException(msg); + log.error(msg, e); + throw new APIServicesException(e); } } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.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/RegistrationProfile.java similarity index 97% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.java rename to 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/RegistrationProfile.java index 97033b6d5cb..455c4704d1a 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/bean/RegistrationProfile.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/RegistrationProfile.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.bean; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean; /** * This class represents the data that are required to register diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.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/constants/Constants.java similarity index 57% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java index 73b4a3a842d..11b056298af 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/constants/Constants.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/constants/Constants.java @@ -1,4 +1,22 @@ -package io.entgra.devicemgt.apimgt.extension.rest.api.constants; +/* + * Copyright (c) 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.constants; public final class Constants { @@ -7,7 +25,8 @@ public final class Constants { public static final String EMPTY_STRING = ""; public static final String CLIENT_NAME = "rest_api_publisher_code"; - public static final String OWNER = "admin"; + public static final String SERVER_USER = "WorkflowConfigurations.ServerUser"; + public static final String SERVER_PASSWORD = "ServerPassword"; public static final String GRANT_TYPE = "client_credentials password refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; public static final String OAUTH_EXPIRES_IN = "expires_in"; @@ -16,14 +35,10 @@ public final class Constants { public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String SCOPE_PARAM_NAME = "scope"; public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage"; - + public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; + public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; public static final int ADAPTER_CONF_DEFAULT_KEEP_ALIVE = 60000; - - public static final String DEFAULT_CALLBACK = ""; - public static final String DEFAULT_PASSWORD = ""; - public static final String TOKEN_SCOPE = "production"; - public static final String APPLICATION_NAME_PREFIX = "OutputAdapter_"; public static final String CLIENT_ID = "clientId"; public static final String CLIENT_SECRET = "clientSecret"; @@ -38,6 +53,10 @@ public final class Constants { public static final String PASSWORD_GRANT_TYPE_SCOPES = "scopes"; public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token"; public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; + public static final String IOT_CORE_HOST = "iot.core.host"; + public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; + public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; + public static final String GET_SCOPE = "/api/am/publisher/v2/scopes/"; } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.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/dto/APIApplicationKey.java similarity index 97% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIApplicationKey.java index cbadf626b26..a4b4660bb8c 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/APIApplicationKey.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/dto/APIApplicationKey.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.dto; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto; /** * This holds the consumer application information that return from the register application endpoint diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.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/dto/AccessTokenInfo.java similarity index 96% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/AccessTokenInfo.java index 061e7e898d1..95bc2b34ba4 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/dto/AccessTokenInfo.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/dto/AccessTokenInfo.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.dto; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto; /** * This holds the token information that return from the token endpoint. diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.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/APIServicesException.java similarity index 63% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.java rename to 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/APIServicesException.java index 35a247a190b..3b9c4cfc7d2 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/APIApplicationServicesException.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/APIServicesException.java @@ -16,23 +16,23 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.exceptions; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions; -public class APIApplicationServicesException extends Exception { +public class APIServicesException extends Exception { - public APIApplicationServicesException() { + public APIServicesException() { super(); } - public APIApplicationServicesException(String message) { - super(); + public APIServicesException(String message) { + super(message); } - public APIApplicationServicesException(String message, Throwable cause) { - super(); + public APIServicesException(String message, Throwable cause) { + super(message); } - public APIApplicationServicesException(Throwable cause) { - super(); + public APIServicesException(Throwable cause) { + super(cause); } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.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/BadRequestException.java similarity index 93% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.java rename to 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/BadRequestException.java index 25cebe82fc5..6aa9be1130c 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/exceptions/BadRequestException.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/BadRequestException.java @@ -19,7 +19,7 @@ /** * Custom exception class for handling bad request exceptions. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.exceptions; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions; public class BadRequestException extends Exception { diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.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/PublisherRESTAPIDataHolder.java similarity index 52% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java rename to 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/PublisherRESTAPIDataHolder.java index 9545a94fb40..18398af9d54 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.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/PublisherRESTAPIDataHolder.java @@ -16,17 +16,22 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.internal; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; public class PublisherRESTAPIDataHolder { - private static final PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); - private APIApplicationServices apiApplicationServices; + private APIManagerConfigurationService apiManagerConfigurationService; + + private static PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); + + private PublisherRESTAPIDataHolder() { + } - public static PublisherRESTAPIDataHolder getInstance() { + static PublisherRESTAPIDataHolder getInstance() { return thisInstance; } @@ -38,4 +43,15 @@ public class PublisherRESTAPIDataHolder { this.apiApplicationServices = apiApplicationServices; } + public void setAPIManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { + this.apiManagerConfigurationService = apiManagerConfigurationService; + } + + public APIManagerConfigurationService getAPIManagerConfigurationService() { + if (apiManagerConfigurationService == null) { + throw new IllegalStateException("API Manager Configuration service is not initialized properly"); + } + return apiManagerConfigurationService; + } + } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.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/PublisherRESTAPIServiceComponent.java similarity index 59% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java rename to 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/PublisherRESTAPIServiceComponent.java index fdf74638c60..989a5477299 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.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/PublisherRESTAPIServiceComponent.java @@ -16,18 +16,25 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.internal; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; /** - * @scr.component name="io.entgra.devicemgt.apimgt.extension.rest.api.internal.PublisherRESTAPIServiceComponent" + * @scr.component name="internal.io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServiceComponent" * immediate="true" + * @scr.reference name="user.apimanagerconfigurationservice.default" + * interface="org.wso2.carbon.apimgt.impl.APIManagerConfigurationService" + * cardinality="1..1" + * policy="dynamic" + * bind="setAPIManagerConfigurationService" + * unbind="unsetAPIManagerConfigurationService" */ public class PublisherRESTAPIServiceComponent { @@ -55,4 +62,18 @@ public class PublisherRESTAPIServiceComponent { protected void deactivate(ComponentContext componentContext) { //do nothing } + + protected void setAPIManagerConfigurationService(APIManagerConfigurationService apiManagerConfigurationService) { + if (log.isDebugEnabled()) { + log.debug("Setting API Manager Configuration Service"); + } + PublisherRESTAPIDataHolder.getInstance().setAPIManagerConfiguration(apiManagerConfigurationService); + } + + protected void unsetAPIManagerConfigurationService(APIManagerConfigurationService apiManagerConfigurationService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting API Manager Configuration Service"); + } + PublisherRESTAPIDataHolder.getInstance().setAPIManagerConfiguration(null); + } } diff --git a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.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/ScopeUtils.java similarity index 96% rename from components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.java rename to 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/ScopeUtils.java index 5716ebfcb1b..18944c945c6 100644 --- a/components/apimgt-extensions/io.entgra.devicemgt.apimgt.extension.rest.api/src/main/java/io/entgra/devicemgt/apimgt/extension/rest/api/util/ScopeUtils.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/ScopeUtils.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.devicemgt.apimgt.extension.rest.api.util; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.util; /** * This class represents the scope data. diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index d1bc922c545..21c7df3235b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -124,7 +124,7 @@ org.wso2.carbon.devicemgt - io.entgra.devicemgt.apimgt.extension.rest.api + io.entgra.device.mgt.core.apimgt.extension.rest.api provided @@ -174,9 +174,9 @@ org.scannotation;version="1.0", org.scannotation.archiveiterator;version="1.0", org.w3c.dom, - io.entgra.devicemgt.apimgt.extension.rest.api, - io.entgra.devicemgt.apimgt.extension.rest.api.dto, - io.entgra.devicemgt.apimgt.extension.rest.api.exceptions, + io.entgra.device.mgt.core.apimgt.extension.rest.api, + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto, + io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions, org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java index fd111a46de9..a7299501bdd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; + import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; /** diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 5452a4f8bd5..ef429bbf508 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,13 +18,13 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; -import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices; -import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl; -import io.entgra.devicemgt.apimgt.extension.rest.api.PublisherRESTAPIServices; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException; -import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.BadRequestException; +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.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; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -373,7 +373,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (APIApplicationServicesException e) { + } catch (APIServicesException e) { String errorMsg = "Error while generating application"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); @@ -436,7 +436,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (int i = 0; i < scopeList.length(); i++) { JSONObject scopeObj = null; scopeObj = scopeList.getJSONObject(i); - if (scopeObj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { + if (scopeObj.getString("name").equals(scopeMapping[2] != null ? + StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { jsonObject = scopeObj; } } @@ -454,20 +455,22 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } catch (IOException | DirectoryIteratorException ex) { log.error("failed to read scopes from file.", ex); - } catch (APIApplicationServicesException | BadRequestException e) { - String errorMsg = "Error while Calling APIs"; + } catch (APIServicesException | BadRequestException e) { + String errorMsg = "Error while calling APIs"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); } } } - catch (APIApplicationServicesException e) { - log.error(e); - throw new RuntimeException(e); + catch (APIServicesException e) { + String errorMsg = "Error while processing Publisher REST API response"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); } catch (BadRequestException e) { - log.error(e); - throw new RuntimeException(e); + String errorMsg = "Error while calling Publisher REST APIs"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index c4bfc0d36d5..c2586135daf 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -40,7 +40,7 @@ org.wso2.carbon.apimgt.keymgt.extension org.wso2.carbon.apimgt.keymgt.extension.api io.entgra.device.mgt.core.apimgt.analytics.extension - io.entgra.devicemgt.apimgt.extension.rest.api + io.entgra.device.mgt.core.apimgt.extension.rest.api diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml index b6344f6e454..de2739b1995 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml @@ -51,6 +51,10 @@ io.swagger swagger-annotations + + org.wso2.carbon.devicemgt + io.entgra.device.mgt.core.apimgt.extension.rest.api + @@ -143,6 +147,9 @@ io.swagger:swagger-annotations:${swagger.version} + + org.wso2.carbon.devicemgt:io.entgra.device.mgt.core.apimgt.extension.rest.api:${carbon.device.mgt.version} + org.wso2.carbon.core.server:${carbon.kernel.version} diff --git a/pom.xml b/pom.xml index e52350555b1..e9686004167 100644 --- a/pom.xml +++ b/pom.xml @@ -240,7 +240,7 @@ org.wso2.carbon.devicemgt - io.entgra.devicemgt.apimgt.extension.rest.api + io.entgra.device.mgt.core.apimgt.extension.rest.api ${carbon.device.mgt.version} From 50fbb5120a5c17fa4492dac99e6ccc2443652ae2 Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 25 Apr 2023 15:11:10 +0530 Subject: [PATCH 10/17] Minor fixes --- .../pom.xml | 9 +++++++++ .../rest/api/APIApplicationServicesImpl.java | 7 ++++--- .../rest/api/PublisherRESTAPIServices.java | 18 +++++++++--------- .../rest/api/constants/Constants.java | 2 +- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 7fb3f1726ff..17dbdbf8661 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -34,6 +34,14 @@ https://entgra.io + + org.apache.httpcomponents.wso2 + httpcore + + + org.wso2.orbit.org.apache.httpcomponents + httpclient + org.wso2.carbon org.wso2.carbon.logging @@ -119,6 +127,7 @@ org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.core;version="4.6", org.wso2.carbon.core.util;version="4.6", + org.apache.commons.ssl, org.wso2.carbon.apimgt.api.model, okhttp3.*, org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", 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 index bffb97893a6..d3ffe4b4d41 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/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 @@ -60,19 +60,20 @@ public class APIApplicationServicesImpl implements APIApplicationServices { throws APIServicesException { String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); - String owner = config.getFirstProperty(Constants.SERVER_USER); + String serverUser = config.getFirstProperty(Constants.SERVER_USER); + String serverPassword = config.getFirstProperty(Constants.SERVER_PASSWORD); 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", owner); + 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("admin", "admin")) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(serverUser, serverPassword)) .post(requestBody) .build(); try { 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 5fedcca952d..8ca7fb61722 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 @@ -45,15 +45,13 @@ public class PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); private static final OkHttpClient client = getOkHttpClient(); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - private static final String host = System.getProperty(Constants.IOT_CORE_HOST); private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException { - - String getAllScopesUrl = "https://" + "://" + host + ":" + port + Constants.GET_ALL_SCOPES; + String getAllScopesUrl = "https://" + host + ":" + port + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() .url(getAllScopesUrl) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -90,16 +88,17 @@ public class PublisherRESTAPIServices { throws APIServicesException, BadRequestException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); - String getScopeUrl = "https://" + "://" + host + ":" + port + Constants.GET_SCOPE + keyValue; + String getScopeUrl = "https://" + host + ":" + port + Constants.GET_SCOPE + keyValue; Request request = new Request.Builder() .url(getScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) .head() .build(); try { Response response = client.newCall(request).execute(); - if (response.code() == HttpStatus.SC_OK) { + if (HttpStatus.SC_OK == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -124,7 +123,7 @@ public class PublisherRESTAPIServices { public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException { - String updateScopeUrl = "https://" + "://" + host + ":" + port + Constants.GET_SCOPE + scope.getId(); + String updateScopeUrl = "https://" + host + ":" + port + Constants.GET_SCOPE + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -136,13 +135,14 @@ public class PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, scopeString); Request request = new Request.Builder() .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, "Bearer " + accessTokenInfo.getAccess_token()) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { Response response = client.newCall(request).execute(); - if (response.code() == HttpStatus.SC_OK) { + if (HttpStatus.SC_OK == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); 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/constants/Constants.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/constants/Constants.java index 11b056298af..bdc557d3e46 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/constants/Constants.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/constants/Constants.java @@ -26,7 +26,7 @@ public final class Constants { public static final String EMPTY_STRING = ""; public static final String CLIENT_NAME = "rest_api_publisher_code"; public static final String SERVER_USER = "WorkflowConfigurations.ServerUser"; - public static final String SERVER_PASSWORD = "ServerPassword"; + public static final String SERVER_PASSWORD = "WorkflowConfigurations.ServerPassword"; public static final String GRANT_TYPE = "client_credentials password refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; public static final String OAUTH_EXPIRES_IN = "expires_in"; From 9ced84a2dff7f5fabe84075cbdb1db7857862d6b Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 25 Apr 2023 17:45:06 +0530 Subject: [PATCH 11/17] Fix scope id issue --- .../apimgt/webapp/publisher/APIPublisherServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index ef429bbf508..a38b3cacf8d 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -432,16 +432,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { //Set scope id which related to the scope key JSONArray scopeList = (JSONArray) scopeObject.get("list"); - JSONObject jsonObject = null; for (int i = 0; i < scopeList.length(); i++) { JSONObject scopeObj = null; scopeObj = scopeList.getJSONObject(i); if (scopeObj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { - jsonObject = scopeObj; + scope.setId(scopeObj.getString("id")); } } - scope.setId(jsonObject.getString("id")); if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); From ba5effbf65303726bfd1b20a0751106403a620d7 Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 25 Apr 2023 18:22:13 +0530 Subject: [PATCH 12/17] Remove unwanted dependencies and minor fixes --- .../pom.xml | 8 -------- .../extension/rest/api/PublisherRESTAPIServices.java | 10 ++++++---- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 17dbdbf8661..7ecbdf7900f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -34,14 +34,6 @@ https://entgra.io - - org.apache.httpcomponents.wso2 - httpcore - - - org.wso2.orbit.org.apache.httpcomponents - httpclient - org.wso2.carbon org.wso2.carbon.logging 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 8ca7fb61722..f7c4430880a 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 @@ -24,7 +24,6 @@ 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.util.ScopeUtils; - import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -67,7 +66,8 @@ public class PublisherRESTAPIServices { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count return getScopes(apiApplicationKey, refreshedAccessToken); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { @@ -103,7 +103,8 @@ public class PublisherRESTAPIServices { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + 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()) { @@ -147,7 +148,8 @@ public class PublisherRESTAPIServices { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + 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()) { From 2ca425819e09851b90df9d7a62e3353682c92d4f Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 25 Apr 2023 23:23:29 +0530 Subject: [PATCH 13/17] Get hardcoded values as constats and fix exception error handling --- .../rest/api/APIApplicationServicesImpl.java | 1 + .../extension/rest/api/PublisherRESTAPIServices.java | 12 ++++++++---- .../extension/rest/api/constants/Constants.java | 5 +++++ .../webapp/publisher/APIPublisherServiceImpl.java | 3 +-- 4 files changed, 15 insertions(+), 6 deletions(-) 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 index d3ffe4b4d41..210a7104558 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/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 @@ -179,6 +179,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { sc.init(null, trustAllCerts, new java.security.SecureRandom()); return sc.getSocketFactory(); } catch (KeyManagementException | NoSuchAlgorithmException e) { + log.error("Error while creating the SSL socket factory due to " + e.getMessage(), e); return null; } 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 f7c4430880a..60d93890b2e 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 @@ -50,7 +50,8 @@ public class PublisherRESTAPIServices { public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException { - String getAllScopesUrl = "https://" + host + ":" + port + Constants.GET_ALL_SCOPES; + String getAllScopesUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() .url(getAllScopesUrl) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -87,8 +88,10 @@ public class PublisherRESTAPIServices { public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) throws APIServicesException, BadRequestException { - String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace("=", ""); - String getScopeUrl = "https://" + host + ":" + port + Constants.GET_SCOPE + keyValue; + String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, + Constants.EMPTY_STRING); + String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + Constants.GET_SCOPE + keyValue; Request request = new Request.Builder() .url(getScopeUrl) @@ -124,7 +127,8 @@ public class PublisherRESTAPIServices { public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException { - String updateScopeUrl = "https://" + host + ":" + port + Constants.GET_SCOPE + scope.getId(); + String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); 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/constants/Constants.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/constants/Constants.java index bdc557d3e46..e4dd49b3818 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/constants/Constants.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/constants/Constants.java @@ -53,6 +53,11 @@ public final class Constants { public static final String PASSWORD_GRANT_TYPE_SCOPES = "scopes"; public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token"; public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; + public static final String HTTPS_PROTOCOL = "https"; + public static final String HTTP_PROTOCOL = "http"; + public static final String SCHEME_SEPARATOR = "://"; + public static final String COLON = ":"; + public static final String QUERY_KEY_VALUE_SEPARATOR = "="; public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index a38b3cacf8d..fb4509858d2 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -433,8 +433,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { //Set scope id which related to the scope key JSONArray scopeList = (JSONArray) scopeObject.get("list"); for (int i = 0; i < scopeList.length(); i++) { - JSONObject scopeObj = null; - scopeObj = scopeList.getJSONObject(i); + JSONObject scopeObj = scopeList.getJSONObject(i); if (scopeObj.getString("name").equals(scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) { scope.setId(scopeObj.getString("id")); From eb11036b6ccf7549fd220b03a1579ce64eacb2ee Mon Sep 17 00:00:00 2001 From: pasindu Date: Wed, 26 Apr 2023 10:02:40 +0530 Subject: [PATCH 14/17] Change version snd remove unwanted dependencies --- .../pom.xml | 43 ++++++++----------- .../rest/api/APIApplicationServicesImpl.java | 2 +- 2 files changed, 18 insertions(+), 27 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 7ecbdf7900f..2dca4947dba 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions org.wso2.carbon.devicemgt - 5.0.25-SNAPSHOT + 5.0.26-SNAPSHOT ../pom.xml @@ -37,43 +37,29 @@ org.wso2.carbon org.wso2.carbon.logging + provided org.wso2.carbon org.wso2.carbon.utils - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services + provided org.wso2.carbon org.wso2.carbon.core + provided - com.googlecode.json-simple.wso2 - json-simple - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.api - - - com.squareup.okhttp3 - okhttp - - - io.github.openfeign - feign-okhttp + org.eclipse.osgi + org.eclipse.osgi + provided - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.api + org.eclipse.osgi + org.eclipse.osgi.services + provided + org.json.wso2 json @@ -81,12 +67,18 @@ com.google.code.gson gson + provided org.wso2.carbon.apimgt org.wso2.carbon.apimgt.impl provided + + com.squareup.okhttp3 + okhttp + compile + @@ -114,7 +106,6 @@ io.entgra.device.mgt.core.apimgt.extension.rest.api.* - javax.net.ssl, org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.core;version="4.6", 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 index 210a7104558..0fc1f4792ea 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/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 @@ -19,8 +19,8 @@ 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.dto.APIApplicationKey; import org.json.JSONObject; +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; From 455917f21e0ea3d73411f7b38b9e14ad3006b662 Mon Sep 17 00:00:00 2001 From: pasindu Date: Wed, 26 Apr 2023 20:35:56 +0530 Subject: [PATCH 15/17] Implement method for Https ssl trustmanager and improve exception --- .../rest/api/APIApplicationServicesImpl.java | 54 +---- .../rest/api/PublisherRESTAPIServices.java | 21 +- .../UnexpectedResponseException.java | 31 +++ .../rest/api/util/HttpsTrustManagerUtils.java | 229 ++++++++++++++++++ .../publisher/APIPublisherServiceImpl.java | 7 +- 5 files changed, 280 insertions(+), 62 deletions(-) create mode 100644 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/UnexpectedResponseException.java create mode 100644 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/HttpsTrustManagerUtils.java 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 index 0fc1f4792ea..abf383b501b 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/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 @@ -19,6 +19,7 @@ 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.util.HttpsTrustManagerUtils; import org.json.JSONObject; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; @@ -48,7 +49,7 @@ import java.util.concurrent.TimeUnit; public class APIApplicationServicesImpl implements APIApplicationServices { private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); - private static final OkHttpClient client = getOkHttpClient(); + 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; @@ -133,55 +134,4 @@ public class APIApplicationServicesImpl implements APIApplicationServices { throw new APIServicesException(e); } } - - protected static OkHttpClient getOkHttpClient() { - X509TrustManager trustAllCerts = new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[0]; - } - - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - }; - OkHttpClient okHttpClient = new OkHttpClient.Builder() - .connectTimeout(300, TimeUnit.SECONDS) - .writeTimeout(300, TimeUnit.SECONDS) - .readTimeout(300, TimeUnit.SECONDS) - .connectionPool(new ConnectionPool(500, 500, TimeUnit.SECONDS)) - .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) - .hostnameVerifier((hostname, sslSession) -> true).build(); - return okHttpClient; - } - - private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { - try { - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - } - }; - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - return sc.getSocketFactory(); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - log.error("Error while creating the SSL socket factory due to " + e.getMessage(), e); - return null; - } - - } } 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 60d93890b2e..c74b227289b 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 @@ -23,6 +23,8 @@ 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; 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -38,17 +40,15 @@ import org.wso2.carbon.apimgt.api.model.Scope; import java.io.IOException; -import static io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl.getOkHttpClient; - public class PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.class); - private static final OkHttpClient client = getOkHttpClient(); + 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 String host = System.getProperty(Constants.IOT_CORE_HOST); private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException { + throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllScopesUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + port + Constants.GET_ALL_SCOPES; @@ -76,7 +76,8 @@ public class PublisherRESTAPIServices { log.error(msg); throw new BadRequestException(msg); } else { - return null; + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); } } catch (IOException e) { String msg = "Error occurred while processing the response"; @@ -86,7 +87,7 @@ public class PublisherRESTAPIServices { } public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException { + throws APIServicesException, BadRequestException, UnexpectedResponseException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, Constants.EMPTY_STRING); @@ -115,7 +116,8 @@ public class PublisherRESTAPIServices { log.error(msg); throw new BadRequestException(msg); } else { - return false; + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); } } catch (IOException e) { String msg = "Error occurred while processing the response"; @@ -125,7 +127,7 @@ public class PublisherRESTAPIServices { } public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException { + throws APIServicesException, BadRequestException, UnexpectedResponseException { String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); @@ -161,7 +163,8 @@ public class PublisherRESTAPIServices { log.error(msg); throw new BadRequestException(msg); } else { - return false; + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); } } catch (IOException e) { String msg = "Error occurred while processing the response"; 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/UnexpectedResponseException.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/UnexpectedResponseException.java new file mode 100644 index 00000000000..898caba26e8 --- /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/UnexpectedResponseException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 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. + */ + +/** + * Custom exception class for handling unexpected server response exceptions. + */ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions; + +public class UnexpectedResponseException extends Exception { + + private static final long serialVersionUID = -2387103750774855056L; + + public UnexpectedResponseException(String errorMessage) { + super(errorMessage); + } +} 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/HttpsTrustManagerUtils.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/HttpsTrustManagerUtils.java new file mode 100644 index 00000000000..8b47d77a343 --- /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/HttpsTrustManagerUtils.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 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.util; + +import okhttp3.ConnectionPool; +import okhttp3.OkHttpClient; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.ServerConfiguration; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import javax.net.ssl.SSLSession; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.HostnameVerifier; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.URI; + +import java.security.*; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class HttpsTrustManagerUtils { + + private static final Log log = LogFactory.getLog(HttpsTrustManagerUtils.class); + private static final String KEY_STORE_TYPE = "JKS"; + /** + * Default truststore type of the client + */ + private static final String TRUST_STORE_TYPE = "JKS"; + /** + * Default keymanager type of the client + */ + private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type + /** + * Default trustmanager type of the client + */ + private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type + private static final String SSLV3 = "SSLv3"; + private static final String DEFAULT_HOST = "localhost"; + private static final String DEFAULT_HOST_IP = "127.0.0.1"; + private static final int TIMEOUT = 100; + + public static OkHttpClient getSSLClient() { + + boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2" + + ".ignoreHostnameVerification")); + OkHttpClient okHttpClient; + final String proxyHost = System.getProperty("http.proxyHost"); + final String proxyPort = System.getProperty("http.proxyPort"); + final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts"); + + final ProxySelector proxySelector = new ProxySelector() { + @Override + public List select(URI uri) { + List proxyList = new ArrayList<>(); + String host = uri.getHost(); + + if (!StringUtils.isEmpty(host)) { + if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST) || StringUtils + .isEmpty(nonProxyHostsValue) || StringUtils.contains(nonProxyHostsValue, host) || + StringUtils.isEmpty(proxyHost) || StringUtils.isEmpty(proxyPort)) { + proxyList.add(Proxy.NO_PROXY); + } else { + proxyList.add(new Proxy(Proxy.Type.HTTP, + new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)))); + } + } else { + log.error("Host is null. Host could not be empty or null"); + } + return proxyList; + } + + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + + X509TrustManager trustAllCerts = new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[0]; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + }; + + if (isIgnoreHostnameVerification) { + okHttpClient = new OkHttpClient.Builder() + .connectTimeout(TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(TIMEOUT, TimeUnit.SECONDS) + .readTimeout(TIMEOUT, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(TIMEOUT, TIMEOUT, TimeUnit.SECONDS)) + .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) + .hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }).proxySelector(proxySelector).build(); + return okHttpClient; + } else { + SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory(); + okHttpClient = new OkHttpClient.Builder() + .connectTimeout(TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(TIMEOUT, TimeUnit.SECONDS) + .readTimeout(TIMEOUT, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(TIMEOUT, TIMEOUT, TimeUnit.SECONDS)) + .sslSocketFactory(trustedSSLSocketFactory) + .proxySelector(proxySelector).build(); + return okHttpClient; + } + } + + private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { + try { + TrustManager[] trustAllCerts = new TrustManager[]{ + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new SecureRandom()); + return sc.getSocketFactory(); + } catch (KeyManagementException | NoSuchAlgorithmException e) { + log.error("Error while creating the SSL socket factory due to " + e.getMessage(), e); + return null; + } + } + + private static SSLSocketFactory getTrustedSSLSocketFactory() { + try { + String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); + String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); + String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Password"); + String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( + "Security.TrustStore.Location"); + KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword, KEY_STORE_TYPE); + KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword); + + return initSSLConnection(keyStore, keyStorePassword, trustStore); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException + | CertificateException | IOException | UnrecoverableKeyException e) { + log.error("Error while creating the SSL socket factory due to " + e.getMessage(), e); + return null; + } + } + + private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) + throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException { + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); + keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); + trustManagerFactory.init(trustStore); + + // Create and initialize SSLContext for HTTPS communication + SSLContext sslContext = SSLContext.getInstance(SSLV3); + sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + SSLContext.setDefault(sslContext); + return sslContext.getSocketFactory(); + } + + private static KeyStore loadKeyStore(String keyStorePath, String ksPassword, String type) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + InputStream fileInputStream = null; + try { + char[] keypassChar = ksPassword.toCharArray(); + KeyStore keyStore = KeyStore.getInstance(type); + fileInputStream = new FileInputStream(keyStorePath); + keyStore.load(fileInputStream, keypassChar); + return keyStore; + } finally { + if (fileInputStream != null) { + fileInputStream.close(); + } + } + } + + private static KeyStore loadTrustStore(String trustStorePath, String tsPassword) + throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { + return loadKeyStore(trustStorePath, tsPassword, TRUST_STORE_TYPE); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index fb4509858d2..e4a63f456a0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -25,6 +25,7 @@ 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; 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.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -468,7 +469,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { String errorMsg = "Error while calling Publisher REST APIs"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); - } finally { + } catch (UnexpectedResponseException e) { + String errorMsg = "Unexpected response from the server"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); + }finally { PrivilegedCarbonContext.endTenantFlow(); } } From 6b6b303d87420e3bc4dd1f3ec0d00ea3b9107109 Mon Sep 17 00:00:00 2001 From: pasindu Date: Wed, 26 Apr 2023 23:20:21 +0530 Subject: [PATCH 16/17] Create interface for Publlisher rest api services --- .../rest/api/APIApplicationServicesImpl.java | 11 +- .../rest/api/PublisherRESTAPIServices.java | 150 +-------------- .../api/PublisherRESTAPIServicesImpl.java | 174 ++++++++++++++++++ .../publisher/APIPublisherServiceImpl.java | 3 +- 4 files changed, 184 insertions(+), 154 deletions(-) create mode 100644 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 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 index abf383b501b..68faf24b80a 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/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 @@ -19,8 +19,8 @@ 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.util.HttpsTrustManagerUtils; 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; @@ -31,20 +31,11 @@ import okhttp3.Request; import okhttp3.Response; import okhttp3.RequestBody; import okhttp3.Credentials; -import okhttp3.ConnectionPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import java.io.IOException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.concurrent.TimeUnit; public class APIApplicationServicesImpl implements APIApplicationServices { 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 c74b227289b..2ea0a51f344 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,158 +18,22 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; -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.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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.RequestBody; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.ssl.Base64; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.Scope; -import java.io.IOException; +public interface PublisherRESTAPIServices { -public class PublisherRESTAPIServices { - private static final Log log = LogFactory.getLog(PublisherRESTAPIServices.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 String host = System.getProperty(Constants.IOT_CORE_HOST); - private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException; - public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) + throws APIServicesException, BadRequestException, UnexpectedResponseException; - String getAllScopesUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON - + port + 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()) { - JSONObject jsonObject = new JSONObject(response.body().string()); - return jsonObject; - } 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(); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - - String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, - Constants.EMPTY_STRING); - String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON - + port + Constants.GET_SCOPE + keyValue; - - 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 { - String msg = "Response : " + response.code() + response.body(); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - - String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); - - ScopeUtils scopeUtil = new ScopeUtils(); - scopeUtil.setKey(scope.getKey()); - scopeUtil.setName(scope.getName()); - scopeUtil.setDescription(scope.getDescription()); - scopeUtil.setRoles(scope.getRoles()); - String scopeString = scopeUtil.toJSON(); - - RequestBody requestBody = RequestBody.create(JSON, scopeString); - 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(); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; - log.error(msg, e); - throw new APIServicesException(e); - } - } + boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + 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 new file mode 100644 index 00000000000..9a5bf73a84b --- /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/PublisherRESTAPIServicesImpl.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 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.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.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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; +import okhttp3.*; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.ssl.Base64; +import org.json.JSONObject; +import org.wso2.carbon.apimgt.api.model.Scope; + +import java.io.IOException; + +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 String host = System.getProperty(Constants.IOT_CORE_HOST); + private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + + @Override + public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + 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()) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } 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(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(e); + } + } + + @Override + public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, + Constants.EMPTY_STRING); + String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + Constants.GET_SCOPE + keyValue; + + 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 { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(e); + } + } + + @Override + public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); + + ScopeUtils scopeUtil = new ScopeUtils(); + scopeUtil.setKey(scope.getKey()); + scopeUtil.setName(scope.getName()); + scopeUtil.setDescription(scope.getDescription()); + scopeUtil.setRoles(scope.getRoles()); + String scopeString = scopeUtil.toJSON(); + + RequestBody requestBody = RequestBody.create(JSON, scopeString); + 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(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(e); + } + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index e4a63f456a0..0725998e7f2 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -21,6 +21,7 @@ package org.wso2.carbon.apimgt.webapp.publisher; 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 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; @@ -384,7 +385,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (String tenantDomain : tenants) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); try { From bb325f7c46b2f9076255b916eff5ee451655516e Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 27 Apr 2023 09:32:04 +0530 Subject: [PATCH 17/17] Remove wild card imports --- .../extension/rest/api/PublisherRESTAPIServicesImpl.java | 6 +++++- .../extension/rest/api/util/HttpsTrustManagerUtils.java | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) 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 9a5bf73a84b..819b91210d4 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 @@ -26,7 +26,11 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequest 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; -import okhttp3.*; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.RequestBody; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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/HttpsTrustManagerUtils.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/HttpsTrustManagerUtils.java index 8b47d77a343..b55857af378 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/util/HttpsTrustManagerUtils.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/HttpsTrustManagerUtils.java @@ -43,7 +43,12 @@ import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; -import java.security.*; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.SecureRandom; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List;