Search in sources :

Example 91 with APIProvider

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

the class ImportUtils method checkAPIProductResourcesValid.

/**
 * This method checks whether the resources in the API Product are valid.
 *
 * @param path          Location of the extracted folder of the API Product
 * @param currentUser   The current logged in user
 * @param apiProvider   API provider
 * @param apiProductDto API Product DTO
 * @param preserveProvider
 * @param organization
 * @throws IOException            If there is an error while reading an API file
 * @throws APIManagementException If failed to get the API Provider of an API,
 *                                or failed when checking the existence of an API
 */
private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider, String organization) throws IOException, APIManagementException {
    // Get dependent APIs in the API Product
    List<ProductAPIDTO> apis = apiProductDto.getApis();
    String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
    File apisDirectory = new File(apisDirectoryPath);
    File[] apisDirectoryListing = apisDirectory.listFiles();
    if (apisDirectoryListing != null) {
        for (File apiDirectory : apisDirectoryListing) {
            String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
            JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser, ImportExportConstants.TYPE_API);
            APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class);
            String apiName = apiDto.getName();
            String apiVersion = apiDto.getVersion();
            String swaggerContent = loadSwaggerFile(apiDirectoryPath);
            APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
            Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent);
            for (ProductAPIDTO apiFromProduct : apis) {
                if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils.equals(apiFromProduct.getVersion(), apiVersion)) {
                    List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources(apiFromProduct.getOperations(), apiUriTemplates);
                    // dependent APIs inside the directory) check whether those are already inside APIM
                    if (!invalidApiOperations.isEmpty()) {
                        // Get the provider of the API if the API is in current user's tenant domain.
                        API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
                        invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates());
                    }
                    // inside the APIM
                    if (!invalidApiOperations.isEmpty()) {
                        throw new APIMgtResourceNotFoundException("Cannot find API resources for some API Product resources.");
                    }
                }
            }
        }
    }
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) JsonElement(com.google.gson.JsonElement) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) File(java.io.File)

Example 92 with APIProvider

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

the class ImportUtils method getValidatedDeploymentsList.

/**
 * This method is used to validate the Gateway environments from the deployment environments file. Gateway
 * environments will be validated with a set of all the labels and environments of the tenant domain. If
 * environment is not found in this set, it will be skipped with an error message in the console. This method is
 * common to both APIs and API Products
 *
 * @param deploymentInfoArray Deployment environment array found in the import artifact
 * @param tenantDomain        Tenant domain
 * @param apiProvider         Provider of the API/ API Product
 * @return a list of API/API Product revision deployments ready to be deployed.
 * @throws APIManagementException If an error occurs when validating the deployments list
 */
private static List<APIRevisionDeployment> getValidatedDeploymentsList(JsonArray deploymentInfoArray, String tenantDomain, APIProvider apiProvider, String organization) throws APIManagementException {
    List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
    if (deploymentInfoArray != null && deploymentInfoArray.size() > 0) {
        Map<String, Environment> gatewayEnvironments = APIUtil.getEnvironments(organization);
        for (int i = 0; i < deploymentInfoArray.size(); i++) {
            JsonObject deploymentJson = deploymentInfoArray.get(i).getAsJsonObject();
            JsonElement deploymentNameElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_NAME);
            if (deploymentNameElement != null) {
                String deploymentName = deploymentNameElement.getAsString();
                Environment gatewayEnvironment = gatewayEnvironments.get(deploymentName);
                if (gatewayEnvironment != null) {
                    JsonElement deploymentVhostElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_VHOST);
                    String deploymentVhost;
                    if (deploymentVhostElement != null) {
                        deploymentVhost = deploymentVhostElement.getAsString();
                    } else {
                        // set the default vhost of the given environment
                        if (gatewayEnvironment.getVhosts().isEmpty()) {
                            throw new APIManagementException("No VHosts defined for the environment: " + deploymentName);
                        }
                        deploymentVhost = gatewayEnvironment.getVhosts().get(0).getHost();
                    }
                    // resolve vhost to null if it is the default vhost of read only environment
                    deploymentVhost = VHostUtils.resolveIfDefaultVhostToNull(deploymentName, deploymentVhost);
                    JsonElement displayOnDevportalElement = deploymentJson.get(ImportExportConstants.DISPLAY_ON_DEVPORTAL_OPTION);
                    boolean displayOnDevportal = displayOnDevportalElement == null || displayOnDevportalElement.getAsBoolean();
                    APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
                    apiRevisionDeployment.setDeployment(deploymentName);
                    apiRevisionDeployment.setVhost(deploymentVhost);
                    apiRevisionDeployment.setDisplayOnDevportal(displayOnDevportal);
                    apiRevisionDeployments.add(apiRevisionDeployment);
                } else {
                    throw new APIManagementException("Label " + deploymentName + " is not a defined gateway environment. Hence " + "skipped without deployment", ExceptionCodes.from(ExceptionCodes.GATEWAY_ENVIRONMENT_NOT_FOUND, String.format("label '%s'", deploymentName)));
                }
            }
        }
    }
    return apiRevisionDeployments;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) JsonObject(com.google.gson.JsonObject) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)

Example 93 with APIProvider

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

the class ApisApiServiceImpl method getWSDLOfAPI.

/**
 * Retrieve the WSDL of an API
 *
 * @param apiId UUID of the API
 * @param ifNoneMatch If-None-Match header value
 * @return the WSDL of the API (can be a file or zip archive)
 * @throws APIManagementException when error occurred while trying to retrieve the WSDL
 */
@Override
public Response getWSDLOfAPI(String apiId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // this will fail if user does not have access to the API or the API does not exist
        // APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId, organization);
        ResourceFile resource = apiProvider.getWSDL(apiId, organization);
        return RestApiUtil.getResponseFromResourceFile(resource.getName(), resource);
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving wsdl of API: " + apiId, e, log);
        } else {
            throw e;
        }
    }
    return null;
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 94 with APIProvider

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

the class ApisApiServiceImpl method editCommentOfAPI.

@Override
public Response editCommentOfAPI(String commentId, String apiId, PatchRequestBodyDTO patchRequestBodyDTO, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    String requestedTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ApiTypeWrapper apiTypeWrapper = apiProvider.getAPIorAPIProductByUUID(apiId, requestedTenantDomain);
        Comment comment = apiProvider.getComment(apiTypeWrapper, commentId, 0, 0);
        if (comment != null) {
            if (comment.getUser().equals(username)) {
                boolean commentEdited = false;
                if (patchRequestBodyDTO.getCategory() != null && !(patchRequestBodyDTO.getCategory().equals(comment.getCategory()))) {
                    comment.setCategory(patchRequestBodyDTO.getCategory());
                    commentEdited = true;
                }
                if (patchRequestBodyDTO.getContent() != null && !(patchRequestBodyDTO.getContent().equals(comment.getText()))) {
                    comment.setText(patchRequestBodyDTO.getContent());
                    commentEdited = true;
                }
                if (commentEdited) {
                    if (apiProvider.editComment(apiTypeWrapper, commentId, comment)) {
                        Comment editedComment = apiProvider.getComment(apiTypeWrapper, commentId, 0, 0);
                        CommentDTO commentDTO = CommentMappingUtil.fromCommentToDTO(editedComment);
                        String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS + "/" + commentId;
                        URI uri = new URI(uriString);
                        return Response.ok(uri).entity(commentDTO).build();
                    }
                } else {
                    return Response.ok().build();
                }
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_COMMENTS, String.valueOf(commentId), log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving comment content location for API " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : Comment(org.wso2.carbon.apimgt.api.model.Comment) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) CommentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.CommentDTO) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 95 with APIProvider

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

the class OperationPoliciesApiServiceImpl method getCommonOperationPolicyContentByPolicyId.

/**
 * Download the operation policy specification and definition for a given common operation policy
 *
 * @param operationPolicyId UUID of the operation policy
 * @param messageContext    message context
 * @return A zip file containing both (if exists) operation policy specification and policy definition
 */
@Override
public Response getCommonOperationPolicyContentByPolicyId(String operationPolicyId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        OperationPolicyData policyData = apiProvider.getCommonOperationPolicyByPolicyId(operationPolicyId, organization, true);
        if (policyData != null) {
            File file = RestApiPublisherUtils.exportOperationPolicyData(policyData);
            return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
        } else {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve an existing common policy with ID: " + operationPolicyId, ExceptionCodes.from(ExceptionCodes.OPERATION_POLICY_NOT_FOUND, operationPolicyId));
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES, operationPolicyId, e, log);
        } else {
            String errorMessage = "Error while getting the content of common operation policy with ID :" + operationPolicyId + " " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (Exception e) {
        RestApiUtil.handleInternalServerError("An error has occurred while getting the content of the common operation " + " policy with ID " + operationPolicyId, e, log);
    }
    return null;
}
Also used : OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) File(java.io.File) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)207 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)198 API (org.wso2.carbon.apimgt.api.model.API)92 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 Test (org.junit.Test)82 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)82 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)73 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)65 IOException (java.io.IOException)40 ArrayList (java.util.ArrayList)36 URISyntaxException (java.net.URISyntaxException)34 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)32 URI (java.net.URI)31 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)31 JSONObject (org.json.simple.JSONObject)29 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)29 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)29 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)28 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)28 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)23