Implement get scopesID API call and rename the module

master
Pasindu Rupasinghe 2 years ago
parent e920df6da3
commit aab94d8fdd

@ -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);
}
}
}

@ -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;
}
}

@ -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;
// }
}

@ -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());
}
}
}
}
}

@ -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;
}
}

@ -27,7 +27,7 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId> <artifactId>io.entgra.devicemgt.apimgt.extension.rest.api</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>Entgra - Device API Management Extension Publisher API</name> <name>Entgra - Device API Management Extension Publisher API</name>
<description>Entgra - Device API Management Extension Publisher API</description> <description>Entgra - Device API Management Extension Publisher API</description>
@ -86,6 +86,10 @@
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -106,11 +110,11 @@
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version> <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Publisher API Management Bundle</Bundle-Description> <Bundle-Description>Publisher API Management Bundle</Bundle-Description>
<Private-Package> <Private-Package>
io.entgra.devicemgt.apimgt.extension.publisher.api.internal io.entgra.devicemgt.apimgt.extension.rest.api.internal
</Private-Package> </Private-Package>
<Export-Package> <Export-Package>
!io.entgra.devicemgt.apimgt.extension.publisher.api.internal, !io.entgra.devicemgt.apimgt.extension.rest.api.internal,
io.entgra.devicemgt.apimgt.extension.publisher.api.* io.entgra.devicemgt.apimgt.extension.rest.api.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
javax.net.ssl, javax.net.ssl,

@ -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.rest.api.dto.APIApplicationKey;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException;
public interface APIApplicationServices { public interface APIApplicationServices {

@ -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 com.google.gson.Gson;
import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey;
import org.json.JSONObject; import org.json.JSONObject;
import io.entgra.devicemgt.apimgt.extension.publisher.api.constants.Constants; import io.entgra.devicemgt.apimgt.extension.rest.api.constants.Constants;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; import okhttp3.MediaType;
import okhttp3.*; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -17,6 +23,7 @@ import javax.net.ssl.X509TrustManager;
import java.io.IOException; import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
public class APIApplicationServicesImpl implements APIApplicationServices { public class APIApplicationServicesImpl implements APIApplicationServices {
@ -33,16 +40,16 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("callbackUrl", Constants.EMPTY_STRING); jsonObject.put("callbackUrl", Constants.EMPTY_STRING);
jsonObject.put("clientName",Constants.CLIENT_NAME); jsonObject.put("clientName", Constants.CLIENT_NAME);
jsonObject.put("grantType",Constants.GRANT_TYPE); jsonObject.put("grantType", Constants.GRANT_TYPE);
jsonObject.put("owner",Constants.OWNER); jsonObject.put("owner", Constants.OWNER);
jsonObject.put("saasApp",true); jsonObject.put("saasApp", true);
RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); 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() Request request = new Request.Builder()
.url(keyManagerEndpoint) .url(applicationEndpoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin")) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic("admin", "admin"))
.post(requestBody) .post(requestBody)
.build(); .build();
@ -58,13 +65,13 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
@Override @Override
public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret)
throws APIApplicationServicesException { throws APIApplicationServicesException {
JSONObject params = new JSONObject(); 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 //ToDo: Remove hardcoded value
params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME,"admin"); params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin");
params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD,"admin"); params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin");
params.put(Constants.SCOPE_PARAM_NAME,Constants.SCOPES); params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES);
return getToken(params, consumerKey, consumerSecret); return getToken(params, consumerKey, consumerSecret);
} }
@ -73,18 +80,17 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
throws APIApplicationServicesException { throws APIApplicationServicesException {
JSONObject params = new JSONObject(); 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 //ToDo: Remove hardcoded value
params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken); 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); return getToken(params, consumerKey, consumerSecret);
} }
public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret) public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret)
throws APIApplicationServicesException{ throws APIApplicationServicesException {
RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON);
//application/x-www-form-urlencoded
String tokenEndPoint = "https://localhost:9443/oauth2/token"; String tokenEndPoint = "https://localhost:9443/oauth2/token";
Request request = new Request.Builder() Request request = new Request.Builder()
@ -117,9 +123,14 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
java.security.cert.X509Certificate[] certs, String authType) { 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) .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
.hostnameVerifier((hostname, sslSession) -> true).build(); .hostnameVerifier((hostname, sslSession) -> true).build();
return okHttpClient;
} }
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
@ -129,9 +140,11 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null; return null;
} }
public void checkClientTrusted( public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) { java.security.cert.X509Certificate[] certs, String authType) {
} }
public void checkServerTrusted( public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) { java.security.cert.X509Certificate[] certs, String authType) {
} }

@ -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);
}
}
}

@ -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 * This class represents the data that are required to register

@ -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. * This holds api application consumer id and secret.

@ -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;
}
}

@ -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{ public class APIApplicationServicesException extends Exception{

@ -22,9 +22,7 @@
/** /**
* Custom exception class for handling bad request exceptions. * Custom exception class for handling bad request exceptions.
*/ */
package io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions; package io.entgra.devicemgt.apimgt.extension.rest.api.exceptions;
import okhttp3.Response;
public class BadRequestException extends Exception { public class BadRequestException extends Exception {

@ -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;
}
}

@ -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.rest.api.APIApplicationServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; 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" * immediate="true"
*/ */
public class PublisherRESTAPIServiceComponent { public class PublisherRESTAPIServiceComponent {
@ -23,10 +22,6 @@ public class PublisherRESTAPIServiceComponent {
try { try {
BundleContext bundleContext = componentContext.getBundleContext(); BundleContext bundleContext = componentContext.getBundleContext();
// PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices();
// bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null);
// PublisherRESTAPIDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices);
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null);
PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices);

@ -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;
}
}

@ -124,9 +124,13 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId> <artifactId>io.entgra.devicemgt.apimgt.extension.rest.api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies> </dependencies>
@ -170,9 +174,9 @@
org.scannotation;version="1.0", org.scannotation;version="1.0",
org.scannotation.archiveiterator;version="1.0", org.scannotation.archiveiterator;version="1.0",
org.w3c.dom, org.w3c.dom,
io.entgra.devicemgt.apimgt.extension.publisher.api, io.entgra.devicemgt.apimgt.extension.rest.api,
io.entgra.devicemgt.apimgt.extension.publisher.api.dto, io.entgra.devicemgt.apimgt.extension.rest.api.dto,
io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions, io.entgra.devicemgt.apimgt.extension.rest.api.exceptions,
org.wso2.carbon.apimgt.annotations.api, org.wso2.carbon.apimgt.annotations.api,
org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model, org.wso2.carbon.apimgt.api.model,
@ -195,7 +199,8 @@
org.wso2.carbon.utils;version="4.6", org.wso2.carbon.utils;version="4.6",
org.wso2.carbon.utils.multitenancy;version="4.6", org.wso2.carbon.utils.multitenancy;version="4.6",
org.wso2.carbon.apimgt.impl.definitions, org.wso2.carbon.apimgt.impl.definitions,
org.apache.commons.lang org.apache.commons.lang,
org.json
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
jsr311-api;scope=compile|runtime;inline=false jsr311-api;scope=compile|runtime;inline=false

@ -18,8 +18,6 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher; 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; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
/** /**

@ -18,18 +18,20 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher; package org.wso2.carbon.apimgt.webapp.publisher;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServices; import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.APIApplicationServicesImpl; import io.entgra.devicemgt.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.devicemgt.apimgt.extension.publisher.api.PublisherRESTAPIServices; import io.entgra.devicemgt.apimgt.extension.rest.api.PublisherRESTAPIServices;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.APIApplicationKey; import io.entgra.devicemgt.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.devicemgt.apimgt.extension.publisher.api.dto.AccessTokenInfo; import io.entgra.devicemgt.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.APIApplicationServicesException; import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.APIApplicationServicesException;
import io.entgra.devicemgt.apimgt.extension.publisher.api.exceptions.BadRequestException; import io.entgra.devicemgt.apimgt.extension.rest.api.exceptions.BadRequestException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.api.model.Documentation;
import org.wso2.carbon.apimgt.api.model.DocumentationType; 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.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.FaultGatewaysException;
@ -382,6 +384,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices(); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServices();
JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
try { try {
String fileName = String fileName =
@ -427,8 +430,18 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
scope.setRoles(roleString); scope.setRoles(roleString);
// if (apiProvider.isSharedScopeNameExists(scope.getKey(), tenantDomain)) { //Set scope id which related to the scope key
// apiProvider.updateSharedScope(scope, tenantDomain); 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())) { if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
} else { } else {
@ -449,17 +462,13 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} }
// catch (UserStoreException e) { catch (APIApplicationServicesException e) {
// String msg = "Error occurred while reading tenant admin username"; log.error(e);
// log.error(msg, e); throw new RuntimeException(e);
// throw new APIManagerPublisherException(e); } catch (BadRequestException e) {
// } log.error(e);
// catch (APIManagementException e) { throw new RuntimeException(e);
// String msg = "Error occurred while loading api provider"; } finally {
// log.error(msg, e);
// throw new APIManagerPublisherException(e);
// }
finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
} }

@ -19,12 +19,6 @@
package org.wso2.carbon.apimgt.webapp.publisher; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;

@ -31,17 +31,25 @@
<artifactId>org.wso2.carbon.apimgt.api</artifactId> <artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.json.wso2</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>json</artifactId> <artifactId>okhttp</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>org.json.wso2</groupId>
<artifactId>feign-okhttp</artifactId> <artifactId>json</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
</dependencies> </dependencies>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -58,7 +66,7 @@
<module>org.wso2.carbon.apimgt.keymgt.extension</module> <module>org.wso2.carbon.apimgt.keymgt.extension</module>
<module>org.wso2.carbon.apimgt.keymgt.extension.api</module> <module>org.wso2.carbon.apimgt.keymgt.extension.api</module>
<module>io.entgra.device.mgt.core.apimgt.analytics.extension</module> <module>io.entgra.device.mgt.core.apimgt.analytics.extension</module>
<module>io.entgra.devicemgt.apimgt.extension.publisher.api</module> <module>io.entgra.devicemgt.apimgt.extension.rest.api</module>
</modules> </modules>
<build> <build>

@ -240,7 +240,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.devicemgt.apimgt.extension.publisher.api</artifactId> <artifactId>io.entgra.devicemgt.apimgt.extension.rest.api</artifactId>
<version>${carbon.device.mgt.version}</version> <version>${carbon.device.mgt.version}</version>
</dependency> </dependency>
<dependency> <dependency>

Loading…
Cancel
Save