Search in sources :

Example 1 with ServiceCatalogImpl

use of org.wso2.carbon.apimgt.impl.ServiceCatalogImpl in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method createNewAPIVersion.

@Override
public Response createNewAPIVersion(String newVersion, String apiId, Boolean defaultVersion, String serviceVersion, MessageContext messageContext) throws APIManagementException {
    URI newVersionedApiUri;
    APIDTO newVersionedApi = new APIDTO();
    ServiceEntry service = new ServiceEntry();
    try {
        APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifierFromTable == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
        if (existingAPI == null) {
            throw new APIMgtResourceNotFoundException("API not found for id " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        if (newVersion.equals(existingAPI.getId().getVersion())) {
            throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName(), ExceptionCodes.from(API_VERSION_ALREADY_EXISTS, newVersion, existingAPI.getId().getApiName()));
        }
        if (StringUtils.isNotEmpty(serviceVersion)) {
            String serviceName = existingAPI.getServiceInfo("name");
            ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
            service = serviceCatalog.getServiceByNameAndVersion(serviceName, serviceVersion, tenantId);
            if (service == null) {
                throw new APIManagementException("No matching service version found", ExceptionCodes.SERVICE_VERSION_NOT_FOUND);
            }
        }
        if (StringUtils.isNotEmpty(serviceVersion) && !serviceVersion.equals(existingAPI.getServiceInfo("version"))) {
            APIDTO apidto = createAPIDTO(existingAPI, newVersion);
            if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
                newVersionedApi = importOpenAPIDefinition(service.getEndpointDef(), null, null, apidto, null, service, organization);
            } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
                newVersionedApi = importAsyncAPISpecification(service.getEndpointDef(), null, apidto, null, service, organization);
            }
        } else {
            API versionedAPI = apiProvider.createNewAPIVersion(apiId, newVersion, defaultVersion, organization);
            newVersionedApi = APIMappingUtil.fromAPItoDTO(versionedAPI);
        }
        // This URI used to set the location header of the POST response
        newVersionedApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + newVersionedApi.getId());
        return Response.created(newVersionedApiUri).entity(newVersionedApi).build();
    } catch (APIManagementException e) {
        if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while copying API : " + apiId, e, log);
        } else {
            throw e;
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location of " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) URISyntaxException(java.net.URISyntaxException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) URI(java.net.URI) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl)

Example 2 with ServiceCatalogImpl

use of org.wso2.carbon.apimgt.impl.ServiceCatalogImpl in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importServiceFromCatalog.

@Override
public Response importServiceFromCatalog(String serviceKey, APIDTO apiDto, MessageContext messageContext) {
    if (StringUtils.isEmpty(serviceKey)) {
        RestApiUtil.handleBadRequest("Required parameter serviceKey is missing", log);
    }
    try {
        ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
        String username = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getTenantId(username);
        ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
        if (service == null) {
            RestApiUtil.handleResourceNotFoundError("Service", serviceKey, log);
        }
        APIDTO createdApiDTO = null;
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
            createdApiDTO = importOpenAPIDefinition(service.getEndpointDef(), null, null, apiDto, null, service, organization);
        } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
            createdApiDTO = importAsyncAPISpecification(service.getEndpointDef(), null, apiDto, null, service, organization);
        } else if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            apiDto.setProvider(RestApiCommonUtil.getLoggedInUsername());
            apiDto.setType(APIDTO.TypeEnum.fromValue("SOAP"));
            API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDto, RestApiCommonUtil.getLoggedInUserProvider(), username, organization);
            apiToAdd.setServiceInfo("key", service.getKey());
            apiToAdd.setServiceInfo("md5", service.getMd5());
            apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
            API api = importSOAPAPI(service.getEndpointDef(), null, null, apiToAdd, organization, service);
            createdApiDTO = APIMappingUtil.fromAPItoDTO(api);
        }
        if (createdApiDTO != null) {
            URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
            return Response.created(createdApiUri).entity(createdApiDTO).build();
        } else {
            RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot create API " + "using the service type " + service.getDefinitionType().name(), log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError("Service", serviceKey, e, log);
        } else {
            String errorMessage = "Error while creating API using Service with Id : " + serviceKey + " from Service Catalog";
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + apiDto.getName() + "-" + apiDto.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) URISyntaxException(java.net.URISyntaxException) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) URI(java.net.URI)

Example 3 with ServiceCatalogImpl

use of org.wso2.carbon.apimgt.impl.ServiceCatalogImpl in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method reimportServiceFromCatalog.

@Override
public Response reimportServiceFromCatalog(String apiId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String username = RestApiCommonUtil.getLoggedInUsername();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    int tenantId = APIUtil.getTenantId(username);
    try {
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        String serviceKey = apiProvider.retrieveServiceKeyByApiId(originalAPI.getId().getId(), tenantId);
        ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
        ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
        JSONObject serviceInfo = new JSONObject();
        serviceInfo.put("name", service.getName());
        serviceInfo.put("version", service.getVersion());
        serviceInfo.put("key", service.getKey());
        serviceInfo.put("md5", service.getMd5());
        api.setServiceInfo(serviceInfo);
        Map validationResponseMap = new HashMap();
        if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
            validationResponseMap = validateOpenAPIDefinition(null, service.getEndpointDef(), null, null, true, true);
        } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
            validationResponseMap = validateAsyncAPISpecification(null, service.getEndpointDef(), null, true, true);
        } else if (!ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot re-import service to " + "API using the service type " + service.getDefinitionType(), log);
        }
        APIDefinitionValidationResponse validationAPIResponse = null;
        if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, service.getEndpointDef(), api, apiProvider, organization);
        } else {
            validationAPIResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationAPIResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationAPIResponse.getErrorItems(), log);
            }
        }
        String protocol = (validationAPIResponse != null ? validationAPIResponse.getProtocol() : "");
        if (!APIConstants.API_TYPE_WEBSUB.equalsIgnoreCase(protocol)) {
            api.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
        }
        API updatedApi = apiProvider.updateAPI(api, originalAPI);
        if (validationAPIResponse != null) {
            PublisherCommonUtils.updateAPIDefinition(apiId, validationAPIResponse, service, organization);
        }
        return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
    } catch (APIManagementException e) {
        if (ExceptionCodes.MISSING_PROTOCOL_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Missing protocol in the Service Definition", log);
        } else if (ExceptionCodes.UNSUPPORTED_PROTOCOL_SPECIFIED_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Unsupported protocol specified in the Service Definition. Protocol " + "should be either sse or websub or ws", log);
        }
        RestApiUtil.handleInternalServerError("Error while retrieving the service key of the service " + "associated with API with id " + apiId, log);
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 4 with ServiceCatalogImpl

use of org.wso2.carbon.apimgt.impl.ServiceCatalogImpl in project carbon-apimgt by wso2.

the class APIMappingUtil method fromDTOtoAPI.

public static API fromDTOtoAPI(APIDTO dto, String provider) throws APIManagementException {
    String providerEmailDomainReplaced = APIUtil.replaceEmailDomain(provider);
    // The provider name that is coming from the body is not honored for now.
    // Later we can use it by checking admin privileges of the user.
    APIIdentifier apiId = new APIIdentifier(providerEmailDomainReplaced, dto.getName(), dto.getVersion());
    API model = new API(apiId);
    String context = dto.getContext();
    final String originalContext = context;
    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 && !context.contains("/t/" + providerDomain)) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    // This is to support the pluggable version strategy
    // if the context does not contain any {version} segment, we use the default version strategy.
    context = checkAndSetVersionParam(context);
    model.setContextTemplate(context);
    context = updateContextWithVersion(dto.getVersion(), originalContext, context);
    model.setContext(context);
    model.setDescription(dto.getDescription());
    if (dto.getEndpointConfig() != null) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            model.setEndpointConfig(mapper.writeValueAsString(dto.getEndpointConfig()));
        } catch (IOException e) {
            handleException("Error while converting endpointConfig to json", e);
        }
    }
    model.setImplementation(dto.getEndpointImplementationType().toString());
    model.setType(dto.getType().toString());
    if (dto.getLifeCycleStatus() != null) {
        model.setStatus((dto.getLifeCycleStatus() != null) ? dto.getLifeCycleStatus().toUpperCase() : null);
    }
    if (dto.isIsDefaultVersion() != null) {
        model.setAsDefaultVersion(dto.isIsDefaultVersion());
    }
    if (dto.isEnableSchemaValidation() != null) {
        model.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    model.setEnableStore(true);
    if (dto.getAdvertiseInfo() != null) {
        AdvertiseInfoDTO advertiseInfoDTO = dto.getAdvertiseInfo();
        model.setAdvertiseOnly(advertiseInfoDTO.isAdvertised());
        model.setApiExternalProductionEndpoint(advertiseInfoDTO.getApiExternalProductionEndpoint());
        model.setApiExternalSandboxEndpoint(advertiseInfoDTO.getApiExternalSandboxEndpoint());
        model.setRedirectURL(advertiseInfoDTO.getOriginalDevPortalUrl());
        model.setApiOwner(advertiseInfoDTO.getApiOwner());
        model.setAdvertiseOnlyAPIVendor(dto.getAdvertiseInfo().getVendor().value());
    }
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        model.setResponseCache(APIConstants.ENABLED);
    } else {
        model.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        model.setCacheTimeout(dto.getCacheTimeout());
    } else {
        model.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getMediationPolicies() != null) {
        List<MediationPolicyDTO> policies = dto.getMediationPolicies();
        // validate whether provided sequences are available
        for (MediationPolicyDTO policy : policies) {
            if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equalsIgnoreCase(policy.getType())) {
                model.setInSequence(policy.getName());
            } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equalsIgnoreCase(policy.getType())) {
                model.setOutSequence(policy.getName());
            } else {
                model.setFaultSequence(policy.getName());
            }
        }
    }
    if (dto.getSubscriptionAvailability() != null) {
        model.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPI(dto.getSubscriptionAvailability()));
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        model.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    Set<Scope> scopes = getScopes(dto);
    model.setScopes(scopes);
    // URI Templates
    // No default topics for AsyncAPIs. Therefore set URITemplates only for non-AsyncAPIs.
    Set<URITemplate> uriTemplates = getURITemplates(model, dto.getOperations());
    model.setUriTemplates(uriTemplates);
    // wsUriMapping
    if (dto.getType().toString().equals(APIConstants.API_TYPE_WS)) {
        Map<String, String> wsUriMapping = new HashMap<>();
        for (APIOperationsDTO operationsDTO : dto.getOperations()) {
            wsUriMapping.put(operationsDTO.getVerb() + "_" + operationsDTO.getTarget(), operationsDTO.getUriMapping());
        }
        model.setWsUriMapping(wsUriMapping);
    }
    if (dto.getTags() != null) {
        Set<String> apiTags = new HashSet<>(dto.getTags());
        model.addTags(apiTags);
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    model.addAvailableTiers(apiTiers);
    model.setApiLevelPolicy(dto.getApiThrottlingPolicy());
    String transports = StringUtils.join(dto.getTransport(), ',');
    model.setTransports(transports);
    if (dto.getVisibility() != null) {
        model.setVisibility(mapVisibilityFromDTOtoAPI(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        model.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        if (APIUtil.isCrossTenantSubscriptionsEnabled()) {
            String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
            model.setVisibleTenants(visibleTenants);
        }
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        model.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        model.setAccessControlRoles("null");
    } else {
        model.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        model.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                model.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                model.addProperty(property.getName(), property.getValue());
            }
        }
    }
    Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = dto.getAdditionalPropertiesMap();
    if (additionalPropertiesMap != null && !additionalPropertiesMap.isEmpty()) {
        for (Map.Entry<String, APIInfoAdditionalPropertiesMapDTO> entry : additionalPropertiesMap.entrySet()) {
            if (entry.getValue().isDisplay()) {
                model.addProperty(entry.getKey() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, entry.getValue().getValue());
            } else {
                model.addProperty(entry.getKey(), entry.getValue().getValue());
            }
        }
    }
    ObjectMapper objectMapper = new ObjectMapper();
    APIBusinessInformationDTO apiBusinessInformationDTO = objectMapper.convertValue(dto.getBusinessInformation(), APIBusinessInformationDTO.class);
    if (apiBusinessInformationDTO != null) {
        model.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
        model.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
        model.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
        model.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
    }
    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();
    }
    model.setCorsConfiguration(corsConfiguration);
    setMaxTpsFromApiDTOToModel(dto, model);
    model.setAuthorizationHeader(dto.getAuthorizationHeader());
    model.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    if (dto.getType().toString().equals(APIConstants.API_TYPE_WEBSUB)) {
        WebsubSubscriptionConfigurationDTO websubSubscriptionConfigurationDTO = dto.getWebsubSubscriptionConfiguration();
        WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
        if (websubSubscriptionConfigurationDTO != null) {
            websubSubscriptionConfiguration = new WebsubSubscriptionConfiguration(websubSubscriptionConfigurationDTO.isEnable(), websubSubscriptionConfigurationDTO.getSecret(), websubSubscriptionConfigurationDTO.getSigningAlgorithm(), websubSubscriptionConfigurationDTO.getSignatureHeader());
        } else {
            websubSubscriptionConfiguration = getDefaultWebsubSubscriptionConfiguration();
        }
        model.setWebsubSubscriptionConfiguration(websubSubscriptionConfiguration);
    }
    // attach api categories to API model
    setAPICategoriesToModel(dto, model, provider);
    if (dto.getKeyManagers() instanceof List) {
        model.setKeyManagers((List<String>) dto.getKeyManagers());
    } else if (dto.getKeyManagers() == null) {
        model.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    APIServiceInfoDTO serviceInfoDTO = dto.getServiceInfo();
    if (serviceInfoDTO != null) {
        ObjectMapper mapper = new ObjectMapper();
        JSONParser parser = new JSONParser();
        JSONObject serviceInfoJson;
        String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
        try {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            serviceInfoJson = (JSONObject) parser.parse(mapper.writeValueAsString(serviceInfoDTO));
            ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
            ServiceEntry service = serviceCatalog.getServiceByKey(dto.getServiceInfo().getKey(), tenantId);
            // Set the md5 of the service which is already available in the system to the API model
            if (service == null) {
                if (log.isDebugEnabled()) {
                    log.debug("A service with key" + dto.getServiceInfo().getKey() + " referenced in the API " + "information is not available in the service catalog");
                }
            } else {
                serviceInfoJson.put("md5", service.getMd5());
            }
            model.setServiceInfo(serviceInfoJson);
        } catch (JsonProcessingException | ParseException e) {
            String msg = "Error while getting json representation of APIServiceInfo";
            handleException(msg, e);
        } catch (UserStoreException e) {
            String msg = "Error while getting tenantId from the given tenant domain " + tenantDomain;
            handleException(msg, e);
        }
    }
    if (dto.getAudience() != null) {
        model.setAudience(dto.getAudience().toString());
    }
    if (dto.getGatewayVendor() != null) {
        model.setGatewayVendor(dto.getGatewayVendor());
    }
    if (dto.getAsyncTransportProtocols() != null) {
        String asyncTransports = StringUtils.join(dto.getAsyncTransportProtocols(), ',');
        model.setAsyncTransportProtocols(asyncTransports);
    }
    return model;
}
Also used : APIInfoAdditionalPropertiesMapDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesMapDTO) AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO) WebsubSubscriptionConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WebsubSubscriptionConfigurationDTO) HashMap(java.util.HashMap) APIUtil.getDefaultWebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.impl.utils.APIUtil.getDefaultWebsubSubscriptionConfiguration) WebsubSubscriptionConfiguration(org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) MediationPolicyDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.MediationPolicyDTO) APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIBusinessInformationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ArrayList(java.util.ArrayList) List(java.util.List) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) IOException(java.io.IOException) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIServiceInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIServiceInfoDTO) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) JSONParser(org.json.simple.parser.JSONParser) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 API (org.wso2.carbon.apimgt.api.model.API)4 ServiceEntry (org.wso2.carbon.apimgt.api.model.ServiceEntry)4 ServiceCatalogImpl (org.wso2.carbon.apimgt.impl.ServiceCatalogImpl)4 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)3 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 JSONObject (org.json.simple.JSONObject)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1