use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class CertificateMgtUtilTest method testDeleteNonExistingCertificate.
@Test
public void testDeleteNonExistingCertificate() {
ResponseCode responseCode = certificateMgtUtils.removeCertificateFromTrustStore(ALIAS_NOT_EXIST);
Assert.assertEquals(responseCode, ResponseCode.CERTIFICATE_NOT_FOUND);
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class CertificateManagerImplTest method testRemoveFromPublisher.
@Test
public void testRemoveFromPublisher() throws CertificateManagementException {
PowerMockito.stub(PowerMockito.method(CertificateMgtUtils.class, "removeCertificateFromTrustStore", String.class)).toReturn(ResponseCode.SUCCESS);
Mockito.when(certificateMgtDAO.deleteCertificate(ALIAS, END_POINT, TENANT_ID)).thenReturn(true);
List<CertificateMetadataDTO> certificateMetadataDTOList = new ArrayList<>();
CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
certificateMetadataDTO.setAlias(ALIAS);
certificateMetadataDTO.setEndpoint(END_POINT);
certificateMetadataDTOList.add(certificateMetadataDTO);
Mockito.when(certificateMgtDAO.getCertificates(ALIAS, null, TENANT_ID)).thenReturn(certificateMetadataDTOList);
ResponseCode responseCode = certificateManager.deleteCertificateFromParentNode(ALIAS, END_POINT, TENANT_ID);
Assert.assertEquals(ResponseCode.SUCCESS, responseCode);
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class OAuthClient method getTokenResponse.
/**
* Method to retrieve the token response sent from the backend
* @param response CloseableHttpResponse object
* @return TokenResponse object containing the details retrieved from the backend
* @throws APIManagementException In the event of an unexpected HTTP status code from the backend
* @throws IOException In the event of a problem parsing the response from the backend
*/
private static TokenResponse getTokenResponse(CloseableHttpResponse response) throws APIManagementException, IOException, ParseException {
int responseCode = response.getStatusLine().getStatusCode();
if (!(responseCode == HttpStatus.SC_OK)) {
throw new APIManagementException("Error while accessing the Token URL. " + "Found http status " + response.getStatusLine());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(stringBuilder.toString());
TokenResponse tokenResponse = new TokenResponse();
if (jsonResponse.containsKey("access_token")) {
tokenResponse.setAccessToken((String) jsonResponse.get("access_token"));
if (jsonResponse.containsKey("refresh_token")) {
tokenResponse.setRefreshToken((String) jsonResponse.get("refresh_token"));
}
if (jsonResponse.containsKey("scope")) {
Set<String> scopeSet = Stream.of(jsonResponse.get("scope").toString().trim().split("\\s*,\\s*")).collect(Collectors.toSet());
tokenResponse.setScope(scopeSet);
}
if (jsonResponse.containsKey("token_type")) {
tokenResponse.setTokenType((String) jsonResponse.get("token_type"));
}
if (jsonResponse.containsKey("expires_in")) {
tokenResponse.setExpiresIn(jsonResponse.get("expires_in").toString());
long currentTimeInSeconds = System.currentTimeMillis() / 1000;
long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
tokenResponse.setValidTill(expiryTimeInSeconds);
} else if (null != APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG)) {
tokenResponse.setExpiresIn(APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG));
long currentTimeInSeconds = System.currentTimeMillis() / 1000;
long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
tokenResponse.setValidTill(expiryTimeInSeconds);
}
}
if (log.isDebugEnabled()) {
log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString());
}
if (tokenResponse.getAccessToken() != null) {
return tokenResponse;
} else {
return null;
}
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method deleteAPIClientCertificateByAlias.
@Override
public Response deleteAPIClientCertificateByAlias(String alias, String apiId, MessageContext messageContext) {
String organization = null;
try {
organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
validateAPIExistence(apiId);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API api = apiProvider.getAPIbyUUID(apiId, organization);
api.setOrganization(organization);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(api.getStatus());
ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
int responseCode = apiProvider.deleteClientCertificate(RestApiCommonUtil.getLoggedInUsername(), clientCertificateDTO.getApiIdentifier(), alias);
if (responseCode == ResponseCode.SUCCESS.getResponseCode()) {
// Handle api product case.
if (API_PRODUCT_TYPE.equals(api.getType())) {
APIIdentifier apiIdentifier = api.getId();
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
apiProduct.setOrganization(organization);
apiProvider.updateAPIProduct(apiProduct);
} else {
apiProvider.updateAPI(api);
}
if (log.isDebugEnabled()) {
log.debug(String.format("The client certificate which belongs to tenant : %s represented by the " + "alias : %s is deleted successfully", organization, alias));
}
return Response.ok().entity("The certificate for alias '" + alias + "' deleted successfully.").build();
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("Failed to delete the client certificate which belongs to tenant : %s " + "represented by the alias : %s.", organization, alias));
}
RestApiUtil.handleInternalServerError("Error while deleting the client certificate for alias '" + alias + "'.", log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while deleting the client certificate with alias " + alias + " for the tenant " + organization, e, log);
} catch (FaultGatewaysException e) {
RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method addAPIClientCertificate.
@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
}
if (StringUtils.isBlank(fileName)) {
RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
}
// validate if api exists
validateAPIExistence(apiId);
API api = apiProvider.getAPIbyUUID(apiId, organization);
api.setOrganization(organization);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(api.getStatus());
String userName = RestApiCommonUtil.getLoggedInUsername();
String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
if (log.isDebugEnabled()) {
log.debug(String.format("Add certificate operation response code : %d", responseCode));
}
if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
// Handle api product case.
if (API_PRODUCT_TYPE.equals(api.getType())) {
APIIdentifier apiIdentifier = api.getId();
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
apiProduct.setOrganization(organization);
apiProvider.updateAPIProduct(apiProduct);
} else {
apiProvider.updateAPI(api);
}
ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
certificateDTO.setAlias(alias);
certificateDTO.setApiId(apiId);
certificateDTO.setTier(tier);
URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
return Response.created(createdCertUri).entity(certificateDTO).build();
} else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
} else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
} else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
} catch (IOException e) {
RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
} catch (URISyntaxException e) {
RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
} catch (FaultGatewaysException e) {
RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
}
return null;
}
Aggregations