use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class APIStoreImpl method addCompositeApiFromDefinition.
/**
* {@inheritDoc}
*/
@Override
public String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException {
try {
URL url = new URL(swaggerResourceUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod(APIMgtConstants.HTTP_GET);
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), StandardCharsets.UTF_8);
CompositeAPI.Builder apiBuilder = apiDefinitionFromSwagger20.generateCompositeApiFromSwaggerResource(getUsername(), responseStr);
apiBuilder.apiDefinition(responseStr);
addCompositeApi(apiBuilder);
return apiBuilder.getId();
} else {
throw new APIManagementException("Error while getting swagger resource from url : " + url, ExceptionCodes.API_DEFINITION_MALFORMED);
}
} catch (UnsupportedEncodingException e) {
String msg = "Unsupported encoding exception while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (ProtocolException e) {
String msg = "Protocol exception while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (MalformedURLException e) {
String msg = "Malformed url while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
} catch (IOException e) {
String msg = "Error while getting the swagger resource from url";
log.error(msg, e);
throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
}
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class CertificateMgtUtils method validateCertificate.
/**
* To validate the current certificate and alias.
*
* @param alias Alias of the certificate.
* @param certificate Bas64 endcoded certificated.
* @return response code based on the validation
*/
public ResponseCode validateCertificate(String alias, int tenantId, String certificate) {
File trustStoreFile = new File(trustStoreLocation);
ResponseCode responseCode = ResponseCode.SUCCESS;
ByteArrayInputStream serverCert = null;
try {
synchronized (this) {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
trustStore.load(localTrustStoreStream, trustStorePassword);
}
if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) {
responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE;
}
}
if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) {
byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
serverCert = new ByteArrayInputStream(cert);
if (serverCert.available() == 0) {
responseCode = ResponseCode.CERTIFICATE_NOT_FOUND;
} else {
CertificateFactory cf = CertificateFactory.getInstance(certificateType);
while (serverCert.available() > 0) {
Certificate generatedCertificate = cf.generateCertificate(serverCert);
X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
responseCode = ResponseCode.CERTIFICATE_EXPIRED;
}
}
}
}
} catch (IOException e) {
log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
} catch (CertificateException e) {
log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
} catch (NoSuchAlgorithmException e) {
log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e);
responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
} catch (KeyStoreException e) {
log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e);
responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
} finally {
closeStreams(serverCert);
}
return responseCode;
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class CertificateMgtUtils method updateCertificate.
/**
* Method to update the certificate which matches the given alias.
*
* @param certificate: The base64 encoded certificate string.
* @param alias : Alias of the certificate that should be retrieved.
* @return :
*/
public synchronized ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {
try {
File trustStoreFile = new File(trustStoreLocation);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream localTrustStoreStream = new FileInputStream(trustStoreFile)) {
trustStore.load(localTrustStoreStream, trustStorePassword);
}
if (trustStore.getCertificate(alias) == null) {
log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store.");
return ResponseCode.CERTIFICATE_NOT_FOUND;
}
// Generate the certificate from the input string.
byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
Certificate newCertificate;
try (InputStream certificateStream = new ByteArrayInputStream(cert)) {
if (certificateStream.available() == 0) {
log.error("Certificate is empty for the provided alias " + alias);
return ResponseCode.INTERNAL_SERVER_ERROR;
}
CertificateFactory certificateFactory = CertificateFactory.getInstance(certificateType);
newCertificate = certificateFactory.generateCertificate(certificateStream);
}
X509Certificate x509Certificate = (X509Certificate) newCertificate;
if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
log.error("Could not update the certificate. The certificate expired.");
return ResponseCode.CERTIFICATE_EXPIRED;
}
// If the certificate is not expired, delete the existing certificate and add the new cert.
trustStore.deleteEntry(alias);
// Store the certificate in the trust store.
trustStore.setCertificateEntry(alias, newCertificate);
try (OutputStream fileOutputStream = new FileOutputStream(trustStoreFile)) {
trustStore.store(fileOutputStream, trustStorePassword);
}
} catch (IOException e) {
throw new CertificateManagementException("Error updating certificate.", e);
} catch (CertificateException e) {
throw new CertificateManagementException("Error generating the certificate.", e);
} catch (NoSuchAlgorithmException e) {
throw new CertificateManagementException("Error loading the keystore.", e);
} catch (KeyStoreException e) {
throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
}
return ResponseCode.SUCCESS;
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class OAS3Parser method generateExample.
/**
* This method generates Sample/Mock payloads for Open API Specification (3.0) definitions
*
* @param apiDefinition API Definition
* @return swagger Json
*/
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
log.debug("Errors found when parsing OAS definition");
}
OpenAPI swagger = parseAttemptForV3.getOpenAPI();
// return map
Map<String, Object> returnMap = new HashMap<>();
// List for APIResMedPolicyList
List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
int minResponseCode = 0;
int responseCode = 0;
String path = entry.getKey();
Map<String, Schema> definitions = swagger.getComponents().getSchemas();
// operation map to get verb
Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
List<Operation> operations = swagger.getPaths().get(path).readOperations();
for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
Operation op = operations.get(i);
// initializing apiResourceMediationPolicyObject
APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
// setting path for apiResourceMediationPolicyObject
apiResourceMediationPolicyObject.setPath(path);
ArrayList<Integer> responseCodes = new ArrayList<Integer>();
// for each HTTP method get the verb
StringBuilder genCode = new StringBuilder();
boolean hasJsonPayload = false;
boolean hasXmlPayload = false;
// for setting only one initializing if condition per response code
boolean respCodeInitialized = false;
Object[] operationsArray = operationMap.entrySet().toArray();
if (operationsArray.length > i) {
Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
} else {
throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
}
for (String responseEntry : op.getResponses().keySet()) {
if (!responseEntry.equals("default")) {
responseCode = Integer.parseInt(responseEntry);
responseCodes.add(responseCode);
minResponseCode = Collections.min(responseCodes);
}
Content content = op.getResponses().get(responseEntry).getContent();
if (content != null) {
MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
if (applicationJson != null) {
Schema jsonSchema = applicationJson.getSchema();
if (jsonSchema != null) {
String jsonExample = getJsonExample(jsonSchema, definitions);
genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
respCodeInitialized = true;
hasJsonPayload = true;
}
}
if (applicationXml != null) {
Schema xmlSchema = applicationXml.getSchema();
if (xmlSchema != null) {
String xmlExample = getXmlExample(xmlSchema, definitions);
genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
hasXmlPayload = true;
}
}
} else {
setDefaultGeneratedResponse(genCode, responseEntry);
hasJsonPayload = true;
hasXmlPayload = true;
}
}
// inserts minimum response code and mock payload variables to static script
String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
// gets response section string depending on availability of json/xml payloads
String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
String finalScript = finalGenCode + responseConditions;
apiResourceMediationPolicyObject.setContent(finalScript);
// sets script to each resource in the swagger
op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
}
checkAndSetEmptyScope(swagger);
returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
}
return returnMap;
}
use of org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode in project carbon-apimgt by wso2.
the class APIProviderImpl method updateCertificate.
@Override
public int updateCertificate(String certificateString, String alias) throws APIManagementException {
ResponseCode responseCode = certificateManager.updateCertificate(certificateString, alias);
if (responseCode != null && responseCode.getResponseCode() == ResponseCode.SUCCESS.getResponseCode()) {
CertificateEvent certificateEvent = new CertificateEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.ENDPOINT_CERTIFICATE_UPDATE.toString(), tenantDomain, alias);
APIUtil.sendNotification(certificateEvent, APIConstants.NotifierType.CERTIFICATE.name());
}
return responseCode != null ? responseCode.getResponseCode() : ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode();
}
Aggregations