Use apache http client

billing-fix-9713
Pasindu Rupasinghe 2 years ago
parent ac834d0359
commit a9bb2fcb93

@ -58,6 +58,22 @@
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies>
<build>
@ -77,7 +93,11 @@
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Publisher API Management Bundle</Bundle-Description>
<Private-Package>
io.entgra.devicemgt.apimgt.extension.publisher.api.internal
</Private-Package>
<Export-Package>
!io.entgra.devicemgt.apimgt.extension.publisher.api.internal,
io.entgra.devicemgt.apimgt.extension.publisher.api.*
</Export-Package>
<Import-Package>
@ -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.*
</Import-Package>
</instructions>
</configuration>

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

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

@ -1,6 +0,0 @@
package io.entgra.devicemgt.apimgt.extension.publisher.api;
public interface PublisherAPIService {
void registerApplication();
}

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

@ -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<NameValuePair> params = new ArrayList<>();
// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE));
// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin"));
// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin"));
// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES));
// try {
// URL url = new URL("https://localhost:9443/oauth2/token");
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpPost request = new HttpPost(url.toString());
//
// request.addHeader("Authorization", "Basic " + PublisherRESTAPIServices.getBase64Encode(cid, cS));
// request.addHeader("Content-Type", "application/x-www-form-urlencoded");
// request.setEntity(new UrlEncodedFormEntity(params));
// HttpResponse httpResponse = httpclient.execute(request);
// response = PublisherRESTAPIUtil.getResponseString(httpResponse);
// JSONParser jsonParser = new JSONParser();
// JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
// token = (String) jsonObject.get(Constants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME);
// if (token != null && !token.isEmpty()){
// accessTokenInfo.setRefreshToken(token);
// accessTokenInfo.setRefreshToken((String) jsonObject.get(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME));
// accessTokenInfo.setExpiresIn((Long) jsonObject.get(Constants.OAUTH_EXPIRES_IN));
// accessTokenInfo.setTokenType((String) jsonObject.get(Constants.OAUTH_TOKEN_TYPE));
// accessTokenInfo.setScope((String) jsonObject.get(Constants.OAUTH_TOKEN_SCOPE));
// }
// System.out.println(accessTokenInfo);
//
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException |
// KeyManagementException| ParseException e) {
// throw new RuntimeException(e);
// }
//
// String key = "perm:sms-handler:view-configuration";
// String value = new String(Base64.encodeBase64((key).getBytes())).replace("=", "");
//
//
// String getScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + value;
// try {
// URL url = new URL(getScopeUrl);
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpHead request = new HttpHead(url.toString());
//
// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
// HttpResponse httpResponse = httpclient.execute(request);
//
// String code = String.valueOf(httpResponse.getStatusLine().getStatusCode());
// System.out.println(code);
//
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
// throw new RuntimeException(e);
// }
//
// String updateScopeUrl = "https://localhost:9443/api/am/publisher/v2/scopes/" + "27fce6f1-6741-4ad5-b700-a56427fd3dbb";
// try {
// URL url = new URL(updateScopeUrl);
// HttpClient httpclient = PublisherRESTAPIUtil.getHttpClient(url.getProtocol());
// HttpPut request = new HttpPut(url.toString());
//
// request.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
// request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
//
//
// String jsonString = "{\"name\": \"" + "name" + "\",\"displayName\": \"" + "displayname" +
// "\", \"description\": \"" + "description" + "\"," + "\"bindings\": [" +
// "\"Internal/devicemgt-user\"]}";
// StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
// request.setEntity(entity);
//
// HttpResponse httpResponse = httpclient.execute(request);
// int code = httpResponse.getStatusLine().getStatusCode();
// System.out.println(code);
// } catch (IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
// throw new RuntimeException(e);
// }
// publisherRESTAPIServices = new PublisherRESTAPIServices();
// publisherRESTAPIServices.isSharedScopeNameExists("perm:sms-handler:view-configuration");
}
}

@ -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<NameValuePair> params = new ArrayList<>();
// params.add(new BasicNameValuePair(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE));
// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_USERNAME, "admin"));
// params.add(new BasicNameValuePair(Constants.PASSWORD_GRANT_TYPE_PASSWORD, "admin"));
// params.add(new BasicNameValuePair(Constants.SCOPE_PARAM_NAME, Constants.SCOPES));
// return getToken(params, consumerKey, consumerSecret);
// }
//
// public AccessTokenInfo getToken(List<NameValuePair> 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()));
// }
}

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

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

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

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

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

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

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

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

@ -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,

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

@ -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<APIConfig> failedAPIsStack = new Stack<>();
private static Stack<APIConfig> 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);
}

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

@ -42,6 +42,34 @@
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
</dependencies>
<modelVersion>4.0.0</modelVersion>

Loading…
Cancel
Save