Search in sources :

Example 1 with APIDefinitionFromSwagger20

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

the class APIPublisherImpl method addAPI.

/**
 * Adds a new API to the system
 *
 * @param apiBuilder API model object
 * @return UUID of the added API.
 * @throws APIManagementException if failed to add API
 */
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    API createdAPI;
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    if (StringUtils.isEmpty(apiBuilder.getId())) {
        apiBuilder.id(UUID.randomUUID().toString());
    }
    LocalDateTime localDateTime = LocalDateTime.now();
    apiBuilder.createdTime(localDateTime);
    apiBuilder.lastUpdatedTime(localDateTime);
    apiBuilder.createdBy(getUsername());
    apiBuilder.updatedBy(getUsername());
    if (apiBuilder.getLabels().isEmpty()) {
        List<String> labelSet = new ArrayList<>();
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
        apiBuilder.labels(labelSet);
    }
    Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
    validateEndpoints(apiEndpointMap, false);
    try {
        if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
            LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
            apiBuilder.associateLifecycle(lifecycleState);
            createUriTemplateList(apiBuilder, false);
            List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
            List<TemplateBuilderDTO> resourceList = new ArrayList<>();
            validateApiPolicy(apiBuilder.getApiPolicy());
            validateSubscriptionPolicies(apiBuilder);
            for (UriTemplate uriTemplate : list) {
                TemplateBuilderDTO dto = new TemplateBuilderDTO();
                dto.setTemplateId(uriTemplate.getTemplateId());
                dto.setUriTemplate(uriTemplate.getUriTemplate());
                dto.setHttpVerb(uriTemplate.getHttpVerb());
                Map<String, Endpoint> map = uriTemplate.getEndpoint();
                if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
                    dto.setProductionEndpoint(endpoint);
                }
                if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
                    dto.setSandboxEndpoint(endpoint);
                }
                resourceList.add(dto);
            }
            GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
            APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
            gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
            String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
            if (log.isDebugEnabled()) {
                log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
            }
            apiBuilder.gatewayConfig(gatewayConfig);
            if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
                apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
            }
            if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                Map<String, Integer> roleNamePermissionList;
                roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                apiBuilder.permissionMap(roleNamePermissionList);
            }
            createdAPI = apiBuilder.build();
            APIUtils.validate(createdAPI);
            // Add API to gateway
            gateway.addAPI(createdAPI);
            if (log.isDebugEnabled()) {
                log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
            }
            Set<String> apiRoleList;
            // if the API has role based visibility, add the API with role checking
            if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
                getApiDAO().addAPI(createdAPI);
            } else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
                // get all the roles in the system
                Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                // get the roles needed to be associated with the API
                apiRoleList = createdAPI.getVisibleRoles();
                if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                    getApiDAO().addAPI(createdAPI);
                }
            }
            APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException | ParseException e) {
        String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (APITemplateException e) {
        String message = "Error generating API configuration for API " + apiBuilder.getName();
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
    return apiBuilder.getId();
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) TemplateBuilderDTO(org.wso2.carbon.apimgt.core.template.dto.TemplateBuilderDTO) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 2 with APIDefinitionFromSwagger20

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

the class ApisApiServiceImpl method apisApiIdSwaggerPut.

/**
 * Updates the swagger defnition of an API
 *
 * @param apiId             UUID of API
 * @param apiDefinition     updated swagger defintion
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return Updated swagger definition
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdSwaggerPut(String apiId, String apiDefinition, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdSwaggerGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        KeyMgtConfigurations keyManagerConfiguration = APIMConfigurationService.getInstance().getApimConfigurations().getKeyManagerConfigs();
        Map<String, String> scopes = new APIDefinitionFromSwagger20().getScopesFromSecurityDefinition(apiDefinition);
        for (String scopeName : scopes.keySet()) {
            if (scopeName.contains(keyManagerConfiguration.getProductRestApiScopesKeyWord())) {
                String message = "scope name couldn't have the restricted keyword " + keyManagerConfiguration.getProductRestApiScopesKeyWord();
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(message, 900313L, message);
                return Response.status(Response.Status.PRECONDITION_FAILED).entity(errorDTO).build();
            }
        }
        apiPublisher.saveSwagger20Definition(apiId, apiDefinition);
        String apiSwagger = apiPublisher.getApiSwaggerDefinition(apiId);
        String newFingerprint = apisApiIdSwaggerGetFingerprint(apiId, null, null, request);
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apiSwagger).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while put swagger for API : " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : KeyMgtConfigurations(org.wso2.carbon.apimgt.core.configuration.models.KeyMgtConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) APIDefinitionFromSwagger20(org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher)

Example 3 with APIDefinitionFromSwagger20

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

the class APIPublisherImpl method createNewAPIVersion.

/**
 * Create a new version of the <code>api</code>, with version <code>newVersion</code>
 *
 * @param apiId      The API to be copied
 * @param newVersion The version of the new API
 * @return UUID of the newly created version.
 * @throws APIManagementException If an error occurs while trying to create
 *                                the new version of the API
 */
@Override
public String createNewAPIVersion(String apiId, String newVersion) throws APIManagementException {
    String newVersionedId;
    LifecycleState lifecycleState;
    // validate parameters
    if (StringUtils.isEmpty(newVersion)) {
        String errorMsg = "New API version cannot be empty";
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (StringUtils.isEmpty(apiId)) {
        String errorMsg = "API ID cannot be empty";
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    try {
        API api = getApiDAO().getAPI(apiId);
        if (api.getVersion().equals(newVersion)) {
            String errMsg = "New API version " + newVersion + " cannot be same as the previous version for " + "API " + api.getName();
            log.error(errMsg);
            throw new APIManagementException(errMsg, ExceptionCodes.API_ALREADY_EXISTS);
        }
        API.APIBuilder apiBuilder = new API.APIBuilder(api);
        apiBuilder.id(UUID.randomUUID().toString());
        apiBuilder.version(newVersion);
        apiBuilder.context(api.getContext().replace(api.getVersion(), newVersion));
        lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
        apiBuilder.associateLifecycle(lifecycleState);
        apiBuilder.copiedFromApiId(api.getId());
        if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
            apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
        }
        getApiDAO().addAPI(apiBuilder.build());
        newVersionedId = apiBuilder.getId();
        sendNotification(apiId, apiBuilder.getName(), newVersion);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Couldn't create new API version from " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Couldn't Associate  new API Lifecycle from " + apiId;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    }
    return newVersionedId;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) API(org.wso2.carbon.apimgt.core.models.API)

Example 4 with APIDefinitionFromSwagger20

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

the class APIPublisherImpl method updateAPI.

/**
 * Updates design and implementation of an existing API. This method must not be used to change API status.
 * Implementations should throw an exceptions when such attempts are made. All life cycle state changes
 * should be carried out using the changeAPIStatus method of this interface.
 *
 * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
 * @throws APIManagementException if failed to update API
 */
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    try {
        API originalAPI = getAPIbyUUID(apiBuilder.getId());
        if (originalAPI != null) {
            // Checks whether the logged in user has the "UPDATE" permission for the API
            verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
            apiBuilder.createdTime(originalAPI.getCreatedTime());
            // workflow status is an internal property and shouldn't be allowed to update externally
            apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
            if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
                if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                    apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
                    Map<String, Integer> roleNamePermissionList;
                    roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                    apiBuilder.permissionMap(roleNamePermissionList);
                }
                Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
                validateEndpoints(apiEndpointMap, true);
                validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
                createUriTemplateList(apiBuilder, true);
                validateApiPolicy(apiBuilder.getApiPolicy());
                validateSubscriptionPolicies(apiBuilder);
                String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
                String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
                GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
                APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
                gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
                String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
                API api = apiBuilder.build();
                // Add API to gateway
                gateway.updateAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
                }
                if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
                    if (!checkIfAPIContextExists(api.getContext())) {
                        // if the API has public visibility, update the API without any role checking
                        if (API.Visibility.PUBLIC == api.getVisibility()) {
                            getApiDAO().updateAPI(api.getId(), api);
                        } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                            // get all the roles in the system
                            Set<String> availableRoles = APIUtils.getAllAvailableRoles();
                            // get the roles needed to be associated with the API
                            Set<String> apiRoleList = api.getVisibleRoles();
                            // if the API has role based visibility, update the API with role checking
                            if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
                                getApiDAO().updateAPI(api.getId(), api);
                            }
                        }
                        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                        getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                    } else {
                        throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
                    }
                } else {
                    // if the API has public visibility, update the API without any role checking
                    if (API.Visibility.PUBLIC == api.getVisibility()) {
                        getApiDAO().updateAPI(api.getId(), api);
                    } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                        // get all the roles in the system
                        Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                        // get the roles needed to be associated with the API
                        Set<String> apiRoleList = api.getVisibleRoles();
                        // if the API has role based visibility, update the API with role checking
                        if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                            getApiDAO().updateAPI(api.getId(), api);
                        }
                    }
                    getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                    getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                }
                if (log.isDebugEnabled()) {
                    log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
                    // 'API_M Functions' related code
                    // Create a payload with event specific details
                    Map<String, String> eventPayload = new HashMap<>();
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
                    // This will notify all the EventObservers(Asynchronous)
                    ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                    ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
                }
            } else {
                APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
            }
        } else {
            log.error("Couldn't found API with ID " + apiBuilder.getId());
            throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ParseException(org.json.simple.parser.ParseException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 5 with APIDefinitionFromSwagger20

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

the class APIPublisherImpl method addApiFromDefinition.

/**
 * Create api from Definition
 *
 * @param apiDefinition API definition stream.
 * @return UUID of the added API.
 * @throws APIManagementException If failed to add the API.
 */
@Override
public String addApiFromDefinition(InputStream apiDefinition) throws APIManagementException {
    try {
        String apiDefinitionString = IOUtils.toString(apiDefinition);
        validateScope(apiDefinitionString);
        API.APIBuilder apiBuilder = apiDefinitionFromSwagger20.generateApiFromSwaggerResource(getUsername(), apiDefinitionString);
        Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(apiDefinitionString);
        for (Map.Entry<String, String> scopeEntry : scopes.entrySet()) {
            getKeyManager().registerScope(new Scope(scopeEntry.getKey(), scopeEntry.getValue()));
        }
        apiBuilder.corsConfiguration(new CorsConfiguration());
        apiBuilder.apiDefinition(apiDefinitionString);
        addAPI(apiBuilder);
        return apiBuilder.getId();
    } catch (IOException e) {
        throw new APIManagementException("Couldn't Generate ApiDefinition from file", ExceptionCodes.API_DEFINITION_MALFORMED);
    }
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 HashMap (java.util.HashMap)12 API (org.wso2.carbon.apimgt.core.models.API)12 Test (org.testng.annotations.Test)10 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)9 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)8 Scope (org.wso2.carbon.apimgt.core.models.Scope)7 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)5 IOException (java.io.IOException)4 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)4 GatewayException (org.wso2.carbon.apimgt.core.exception.GatewayException)4 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)4 APIConfigContext (org.wso2.carbon.apimgt.core.template.APIConfigContext)4 LocalDateTime (java.time.LocalDateTime)3 Map (java.util.Map)3 ParseException (org.json.simple.parser.ParseException)3 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)3 APIDefinitionFromSwagger20 (org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20)3 LifecycleException (org.wso2.carbon.lcm.core.exception.LifecycleException)3 FileInputStream (java.io.FileInputStream)2