Implement exception handling

apim420
Pasindu Rupasinghe 2 years ago
parent 8e4998ede8
commit f1120baec3

@ -78,6 +78,10 @@
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
</dependencies>
<build>

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

@ -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<NameValuePair> 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<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));
@ -181,8 +238,10 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
return getToken(params, consumerKey, consumerSecret);
}
public AccessTokenInfo getToken(List<NameValuePair> nameValuePairs, String clientId, String clientSecret) {
public AccessTokenInfo getToken(List<NameValuePair> 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);
}
}

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

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

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

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

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

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

Loading…
Cancel
Save