Search in sources :

Example 31 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization 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 32 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class PublisherCommonUtils method addDocumentationToAPI.

/**
 * Add document DTO.
 *
 * @param documentDto Document DTO
 * @param apiId       API UUID
 * @return Added documentation
 * @param organization  Identifier of an Organization
 * @throws APIManagementException If an error occurs when retrieving API Identifier,
 *                                when checking whether the documentation exists and when adding the documentation
 */
public static Documentation addDocumentationToAPI(DocumentDTO documentDto, String apiId, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    Documentation documentation = DocumentationMappingUtil.fromDTOtoDocumentation(documentDto);
    String documentName = documentDto.getName();
    if (documentDto.getType() == null) {
        throw new APIManagementException("Documentation type cannot be empty", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (documentDto.getType() == DocumentDTO.TypeEnum.OTHER && StringUtils.isBlank(documentDto.getOtherTypeName())) {
        // check otherTypeName for not null if doc type is OTHER
        throw new APIManagementException("otherTypeName cannot be empty if type is OTHER.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    String sourceUrl = documentDto.getSourceUrl();
    if (documentDto.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
        throw new APIManagementException("Invalid document sourceUrl Format", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (apiProvider.isDocumentationExist(apiId, documentName, organization)) {
        throw new APIManagementException("Requested document '" + documentName + "' already exists", ExceptionCodes.DOCUMENT_ALREADY_EXISTS);
    }
    documentation = apiProvider.addDocumentation(apiId, documentation, organization);
    return documentation;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 33 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class PublisherCommonUtils method changeApiOrApiProductLifecycle.

/**
 * Change the lifecycle state of an API or API Product identified by UUID
 *
 * @param action       LC state change action
 * @param apiTypeWrapper API Type Wrapper (API or API Product)
 * @param lcChecklist  LC state change check list
 * @param organization Organization of logged-in user
 * @return APIStateChangeResponse
 * @throws APIManagementException Exception if there is an error when changing the LC state of API or API Product
 */
public static APIStateChangeResponse changeApiOrApiProductLifecycle(String action, ApiTypeWrapper apiTypeWrapper, String lcChecklist, String organization) throws APIManagementException {
    String[] checkListItems = lcChecklist != null ? lcChecklist.split(APIConstants.DELEM_COMMA) : new String[0];
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    Map<String, Object> apiLCData = apiProvider.getAPILifeCycleData(apiTypeWrapper.getUuid(), organization);
    String[] nextAllowedStates = (String[]) apiLCData.get(APIConstants.LC_NEXT_STATES);
    if (!ArrayUtils.contains(nextAllowedStates, action)) {
        throw new APIManagementException("Action '" + action + "' is not allowed. Allowed actions are " + Arrays.toString(nextAllowedStates), ExceptionCodes.from(ExceptionCodes.UNSUPPORTED_LIFECYCLE_ACTION, action));
    }
    // check and set lifecycle check list items including "Deprecate Old Versions" and "Require Re-Subscription".
    Map<String, Boolean> lcMap = new HashMap<>();
    for (String checkListItem : checkListItems) {
        String[] attributeValPair = checkListItem.split(APIConstants.DELEM_COLON);
        if (attributeValPair.length == 2) {
            String checkListItemName = attributeValPair[0].trim();
            boolean checkListItemValue = Boolean.parseBoolean(attributeValPair[1].trim());
            lcMap.put(checkListItemName, checkListItemValue);
        }
    }
    try {
        return apiProvider.changeLifeCycleStatus(organization, apiTypeWrapper, action, lcMap);
    } catch (FaultGatewaysException e) {
        throw new APIManagementException("Error while change the state of artifact with name - " + apiTypeWrapper.getName(), e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) JSONObject(org.json.simple.JSONObject) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 34 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class PublisherCommonUtils method addDocumentationContent.

/**
 * Add documentation content of inline and markdown documents.
 *
 * @param documentation Documentation
 * @param apiProvider   API Provider
 * @param apiId         API/API Product UUID
 * @param documentId    Document ID
 * @param organization  Identifier of the organization
 * @param inlineContent Inline content string
 * @throws APIManagementException If an error occurs while adding the documentation content
 */
public static void addDocumentationContent(Documentation documentation, APIProvider apiProvider, String apiId, String documentId, String organization, String inlineContent) throws APIManagementException {
    DocumentationContent content = new DocumentationContent();
    content.setSourceType(DocumentationContent.ContentSourceType.valueOf(documentation.getSourceType().toString()));
    content.setTextContent(inlineContent);
    apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent)

Example 35 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class CertificateRestApiUtils method preValidateClientCertificate.

/**
 * To pre validate client certificate given for an alias
 *
 * @param alias Alias of the certificate.
 * @param apiIdentifier Identifier of the API.
 * @param organization Identifier of the organization.
 * @return Client certificate
 * @throws APIManagementException API Management Exception.
 */
public static ClientCertificateDTO preValidateClientCertificate(String alias, APIIdentifier apiIdentifier, String organization) throws APIManagementException {
    int tenantId = APIUtil.getInternalOrganizationId(organization);
    if (StringUtils.isEmpty(alias)) {
        throw new APIManagementException("The alias cannot be empty", ExceptionCodes.ALIAS_CANNOT_BE_EMPTY);
    }
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    ClientCertificateDTO clientCertificate = apiProvider.getClientCertificate(tenantId, alias, apiIdentifier, organization);
    if (clientCertificate == null) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Could not find a client certificate in truststore which belongs to " + "tenant : %d and with alias : %s. Hence the operation is terminated.", tenantId, alias));
        }
        String message = "Certificate for alias '" + alias + "' is not found.";
        throw new APIMgtResourceNotFoundException(message);
    }
    return clientCertificate;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)304 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)106 API (org.wso2.carbon.apimgt.api.model.API)100 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)89 ArrayList (java.util.ArrayList)79 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)72 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)65 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)64 IOException (java.io.IOException)61 Registry (org.wso2.carbon.registry.core.Registry)58 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)57 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)56 HashMap (java.util.HashMap)54 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)53 Resource (org.wso2.carbon.registry.core.Resource)51 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)49 JSONObject (org.json.simple.JSONObject)45 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)44 URISyntaxException (java.net.URISyntaxException)42