use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class ExportUtils method exportApiProduct.
/**
* Exports an API Product from API Manager for a given API Product. MMeta information, API Product icon,
* documentation, client certificates and dependent APIs are exported.
*
* @param apiProvider API Provider
* @param apiProductIdentifier API Product Identifier
* @param apiProductDtoToReturn API Product DTO
* @param userName Username
* @param exportFormat Format of output documents. Can be YAML or JSON
* @param preserveStatus Preserve API Product status on export
* @param organization Organization Identifier
* @return
* @throws APIManagementException If an error occurs while getting governance registry
*/
public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, APIProductDTO apiProductDtoToReturn, String userName, ExportFormat exportFormat, Boolean preserveStatus, boolean preserveDocs, boolean preserveCredentials, String organization) throws APIManagementException, APIImportExportException {
int tenantId = 0;
// Create temp location for storing API Product data
File exportFolder = CommonUtil.createTempDirectory(apiProductIdentifier);
String exportAPIBasePath = exportFolder.toString();
String archivePath = exportAPIBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion());
tenantId = APIUtil.getTenantId(userName);
CommonUtil.createDirectory(archivePath);
if (preserveDocs) {
addThumbnailToArchive(archivePath, apiProductIdentifier, apiProvider);
addDocumentationToArchive(archivePath, apiProductIdentifier, exportFormat, apiProvider, APIConstants.API_PRODUCT_IDENTIFIER_TYPE);
}
// Set API Product status to created if the status is not preserved
if (!preserveStatus) {
apiProductDtoToReturn.setState(APIProductDTO.StateEnum.CREATED);
}
addGatewayEnvironmentsToArchive(archivePath, apiProductDtoToReturn.getId(), exportFormat, apiProvider);
addAPIProductMetaInformationToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider);
addDependentAPIsToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider, userName, Boolean.TRUE, preserveDocs, preserveCredentials, organization);
// Export mTLS authentication related certificates
if (log.isDebugEnabled()) {
log.debug("Mutual SSL enabled. Exporting client certificates.");
}
addClientCertificatesToArchive(archivePath, apiProductIdentifier, tenantId, apiProvider, exportFormat, organization);
CommonUtil.archiveDirectory(exportAPIBasePath);
FileUtils.deleteQuietly(new File(exportAPIBasePath));
return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier 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.api.model.APIProductIdentifier 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;
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class RestApiPublisherUtils method attachFileToProductDocument.
/**
* Attaches a file to the specified product document
*
* @param productId identifier of the API Product, the document belongs to
* @param documentation Documentation object
* @param inputStream input Stream containing the file
* @param fileDetails file details object as cxf Attachment
* @param organization organization of the API
* @throws APIManagementException if unable to add the file
*/
public static void attachFileToProductDocument(String productId, Documentation documentation, InputStream inputStream, Attachment fileDetails, String organization) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String documentId = documentation.getId();
String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
File docFile = new File(tmpFolder);
boolean folderCreated = docFile.mkdirs();
if (!folderCreated) {
RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
}
InputStream docInputStream = null;
try {
ContentDisposition contentDisposition = fileDetails.getContentDisposition();
String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
if (StringUtils.isBlank(filename)) {
filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
log.warn("Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '" + filename + "'");
}
// APIProductIdentifier productIdentifier = APIMappingUtil
// .getAPIProductIdentifierFromUUID(productId, tenantDomain);
RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
PublisherCommonUtils.addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, productId, documentId, organization);
docFile.deleteOnExit();
} catch (FileNotFoundException e) {
RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
} finally {
IOUtils.closeQuietly(docInputStream);
}
}
use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method retrieveOperationPolicySequenceForProducts.
private static GatewayContentDTO retrieveOperationPolicySequenceForProducts(APIProduct apiProduct, API api, String extractedLocation, String flow) throws APIManagementException {
Set<URITemplate> applicableURITemplates = new HashSet<>();
for (APIProductResource productResource : apiProduct.getProductResources()) {
if (productResource.getApiIdentifier().equals(api.getId())) {
applicableURITemplates.add(productResource.getUriTemplate());
}
}
String policySequence = null;
APIProductIdentifier apiProductIdentifier = apiProduct.getId();
String seqExt = APIUtil.getSequenceExtensionName(apiProductIdentifier.getName(), apiProductIdentifier.getVersion()).concat("--").concat(api.getUuid()).concat(SynapsePolicyAggregator.getSequenceExtensionFlow(flow));
try {
policySequence = SynapsePolicyAggregator.generatePolicySequenceForUriTemplateSet(applicableURITemplates, seqExt, flow, extractedLocation);
} catch (IOException e) {
throw new APIManagementException(e);
}
GatewayContentDTO operationPolicySequenceContentDto = new GatewayContentDTO();
if (StringUtils.isNotEmpty(policySequence)) {
try {
OMElement omElement = APIUtil.buildOMElement(new ByteArrayInputStream(policySequence.getBytes()));
if (omElement != null) {
if (omElement.getAttribute(new QName("name")) != null) {
omElement.getAttribute(new QName("name")).setAttributeValue(seqExt);
}
operationPolicySequenceContentDto.setName(seqExt);
operationPolicySequenceContentDto.setContent(APIUtil.convertOMtoString(omElement));
for (APIProductResource productResource : apiProduct.getProductResources()) {
if (productResource.getApiIdentifier().equals(api.getId())) {
switch(flow) {
case APIConstants.OPERATION_SEQUENCE_TYPE_REQUEST:
productResource.setInSequenceName(seqExt);
break;
case APIConstants.OPERATION_SEQUENCE_TYPE_RESPONSE:
productResource.setOutSequenceName(seqExt);
break;
case APIConstants.OPERATION_SEQUENCE_TYPE_FAULT:
productResource.setFaultSequenceName(seqExt);
break;
}
}
}
return operationPolicySequenceContentDto;
}
} catch (Exception e) {
throw new APIManagementException(e);
}
}
return null;
}
Aggregations