Search in sources :

Example 76 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider in project carbon-apimgt by wso2.

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 77 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider in project carbon-apimgt by wso2.

the class APIMappingUtil method getAPIIdentifierFromApiId.

public static APIIdentifier getAPIIdentifierFromApiId(String apiId) throws APIManagementException {
    // if apiId contains -AT-, that need to be replaced before splitting
    apiId = APIUtil.replaceEmailDomainBack(apiId);
    String[] apiIdDetails = apiId.split(RestApiConstants.API_ID_DELIMITER);
    if (apiIdDetails.length < 3) {
        throw new APIManagementException("Provided API identifier '" + apiId + "' is invalid", ExceptionCodes.from(ExceptionCodes.INVALID_API_IDENTIFIER, apiId));
    }
    // apiId format: provider-apiName-version
    String providerName = null;
    try {
        providerName = URLDecoder.decode(apiIdDetails[0], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String errorMsg = "Couldn't decode value providerName: " + providerName;
        throw new APIManagementException(errorMsg, e);
    }
    String apiName = null;
    try {
        apiName = URLDecoder.decode(apiIdDetails[1], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String errorMsg = "Couldn't decode value apiName : " + apiName;
        throw new APIManagementException(errorMsg, e);
    }
    String version = null;
    try {
        version = URLDecoder.decode(apiIdDetails[2], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        String errorMsg = "Couldn't decode value version : " + version;
        throw new APIManagementException(errorMsg, e);
    }
    String providerNameEmailReplaced = APIUtil.replaceEmailDomain(providerName);
    return new APIIdentifier(providerNameEmailReplaced, apiName, version);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 78 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider in project carbon-apimgt by wso2.

the class APIMappingUtil method setAPICategoriesToModel.

/**
 * Set API categories to API or APIProduct based on the instance type of the DTO object passes.
 *
 * @param dto   APIDTO or APIProductDTO
 * @param model API or APIProduct
 */
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
    List<String> apiCategoryNames = new ArrayList<>();
    if (dto instanceof APIDTO) {
        APIDTO apiDTO = (APIDTO) dto;
        apiCategoryNames = apiDTO.getCategories();
    } else {
        APIProductDTO apiProductDTO = (APIProductDTO) dto;
        apiCategoryNames = apiProductDTO.getCategories();
    }
    List<APICategory> apiCategories = new ArrayList<>();
    for (String categoryName : apiCategoryNames) {
        APICategory category = new APICategory();
        category.setName(categoryName);
        apiCategories.add(category);
    }
    if (model instanceof API) {
        ((API) model).setApiCategories(apiCategories);
    } else {
        ((APIProduct) model).setApiCategories(apiCategories);
    }
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 79 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider in project carbon-apimgt by wso2.

the class ExportUtils method addClientCertificatesToArchive.

/**
 * Retrieve Mutual SSL related certificates and store those in the archive directory.
 *
 * @param archivePath  Folder path to export client certificates
 * @param identifier   Identifier
 * @param tenantId     Tenant id of the user
 * @param provider     Api Provider
 * @param exportFormat Export format of file
 * @param organization Organization
 * @throws APIImportExportException If an error occurs when writing to file or retrieving certificate metadata
 */
public static void addClientCertificatesToArchive(String archivePath, Identifier identifier, int tenantId, APIProvider provider, ExportFormat exportFormat, String organization) throws APIImportExportException {
    List<ClientCertificateDTO> certificateMetadataDTOs;
    try {
        if (identifier instanceof APIProductIdentifier) {
            certificateMetadataDTOs = provider.searchClientCertificates(tenantId, null, (APIProductIdentifier) identifier, organization);
        } else {
            certificateMetadataDTOs = provider.searchClientCertificates(tenantId, null, (APIIdentifier) identifier, organization);
        }
        if (!certificateMetadataDTOs.isEmpty()) {
            String clientCertsDirectoryPath = archivePath + File.separator + ImportExportConstants.CLIENT_CERTIFICATES_DIRECTORY;
            CommonUtil.createDirectory(clientCertsDirectoryPath);
            JsonArray certificateList = getClientCertificateContentAndMetaData(certificateMetadataDTOs, clientCertsDirectoryPath);
            if (certificateList.size() > 0) {
                CommonUtil.writeDtoToFile(clientCertsDirectoryPath + ImportExportConstants.CLIENT_CERTIFICATE_FILE, exportFormat, ImportExportConstants.TYPE_CLIENT_CERTIFICATES, certificateList);
            }
        }
    } catch (IOException e) {
        throw new APIImportExportException("Error while saving as YAML or JSON", e);
    } catch (APIManagementException e) {
        throw new APIImportExportException("Error retrieving certificate meta data. tenantId [" + tenantId + "] api [" + tenantId + "]", e);
    }
}
Also used : JsonArray(com.google.gson.JsonArray) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) IOException(java.io.IOException)

Example 80 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider 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)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)82 ArrayList (java.util.ArrayList)70 API (org.wso2.carbon.apimgt.api.model.API)64 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)50 Test (org.junit.Test)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)45 HashMap (java.util.HashMap)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)36 IOException (java.io.IOException)35 Resource (org.wso2.carbon.registry.core.Resource)34 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)32 HashSet (java.util.HashSet)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 UserStoreException (org.wso2.carbon.user.api.UserStoreException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)27 ResultSet (java.sql.ResultSet)25 QName (javax.xml.namespace.QName)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25