Search in sources :

Example 31 with APIProductIdentifier

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);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 32 with APIProductIdentifier

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;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 33 with APIProductIdentifier

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;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 34 with APIProductIdentifier

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);
    }
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 35 with APIProductIdentifier

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;
}
Also used : QName(javax.xml.namespace.QName) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) ByteArrayInputStream(java.io.ByteArrayInputStream) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO) HashSet(java.util.HashSet)

Aggregations

APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)33 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)22 PreparedStatement (java.sql.PreparedStatement)19 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)19 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)19 Connection (java.sql.Connection)18 ArrayList (java.util.ArrayList)18 ResultSet (java.sql.ResultSet)17 SQLException (java.sql.SQLException)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 API (org.wso2.carbon.apimgt.api.model.API)14 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)14 HashSet (java.util.HashSet)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)13 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)13 Tier (org.wso2.carbon.apimgt.api.model.Tier)12 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)12