Search in sources :

Example 41 with Organization

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

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

Example 43 with Organization

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

the class ExportUtils method addAPIMetaInformationToArchive.

/**
 * Retrieve meta information of the API to export and store those in the archive directory.
 * URL template information are stored in swagger.json definition while rest of the required
 * data are in api.json
 *
 * @param archivePath    Folder path to export meta information to export
 * @param apiDtoToReturn API DTO to be exported
 * @param exportFormat   Export format of file
 * @param apiProvider    API Provider
 * @param apiIdentifier  API Identifier
 * @param organization   Organization Identifier
 * @throws APIImportExportException If an error occurs while exporting meta information
 */
public static void addAPIMetaInformationToArchive(String archivePath, APIDTO apiDtoToReturn, ExportFormat exportFormat, APIProvider apiProvider, APIIdentifier apiIdentifier, String organization) throws APIImportExportException {
    CommonUtil.createDirectory(archivePath + File.separator + ImportExportConstants.DEFINITIONS_DIRECTORY);
    try {
        // If a streaming API is exported, it does not contain a swagger file.
        // Therefore swagger export is only required for REST or SOAP based APIs
        String apiType = apiDtoToReturn.getType().toString();
        API api = APIMappingUtil.fromDTOtoAPI(apiDtoToReturn, apiDtoToReturn.getProvider());
        api.setOrganization(organization);
        api.setId(apiIdentifier);
        if (!PublisherCommonUtils.isStreamingAPI(apiDtoToReturn)) {
            // For Graphql APIs, the graphql schema definition should be exported.
            if (StringUtils.equals(apiType, APIConstants.APITransportType.GRAPHQL.toString())) {
                String schemaContent = apiProvider.getGraphqlSchema(apiIdentifier);
                CommonUtil.writeFile(archivePath + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION, schemaContent);
                GraphqlComplexityInfo graphqlComplexityInfo = apiProvider.getComplexityDetails(apiDtoToReturn.getId());
                if (graphqlComplexityInfo.getList().size() != 0) {
                    GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlComplexityInfotoDTO(graphqlComplexityInfo);
                    CommonUtil.writeDtoToFile(archivePath + ImportExportConstants.GRAPHQL_COMPLEXITY_INFO_LOCATION, exportFormat, ImportExportConstants.GRAPHQL_COMPLEXITY, graphQLQueryComplexityInfoDTO);
                }
            }
            // For GraphQL APIs, swagger export is not needed
            if (!APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
                String formattedSwaggerJson = RestApiCommonUtil.retrieveSwaggerDefinition(api, apiProvider);
                CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.SWAGGER_DEFINITION_LOCATION, exportFormat, formattedSwaggerJson);
            }
            if (log.isDebugEnabled()) {
                log.debug("Meta information retrieved successfully for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion());
            }
        } else {
            String asyncApiJson = RestApiCommonUtil.retrieveAsyncAPIDefinition(api, apiProvider);
            // fetching the callback URL from asyncAPI definition.
            JsonParser jsonParser = new JsonParser();
            JsonObject parsedObject = jsonParser.parse(asyncApiJson).getAsJsonObject();
            if (parsedObject.has(ASYNC_DEFAULT_SUBSCRIBER)) {
                String callBackEndpoint = parsedObject.get(ASYNC_DEFAULT_SUBSCRIBER).getAsString();
                if (!StringUtils.isEmpty(callBackEndpoint)) {
                    // add openAPI definition to asyncAPI
                    String formattedSwaggerJson = RestApiCommonUtil.generateOpenAPIForAsync(apiDtoToReturn.getName(), apiDtoToReturn.getVersion(), apiDtoToReturn.getContext(), callBackEndpoint);
                    CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.OPENAPI_FOR_ASYNCAPI_DEFINITION_LOCATION, exportFormat, formattedSwaggerJson);
                    // Adding endpoint config since adapter validates api.json for endpoint urls.
                    HashMap<String, Object> endpointConfig = new HashMap<>();
                    endpointConfig.put(API_ENDPOINT_CONFIG_PROTOCOL_TYPE, "http");
                    endpointConfig.put("failOver", "false");
                    HashMap<String, Object> productionEndpoint = new HashMap<>();
                    productionEndpoint.put("template_not_supported", "false");
                    productionEndpoint.put("url", callBackEndpoint);
                    HashMap<String, Object> sandboxEndpoint = new HashMap<>();
                    sandboxEndpoint.put("template_not_supported", "false");
                    sandboxEndpoint.put("url", callBackEndpoint);
                    endpointConfig.put(API_DATA_PRODUCTION_ENDPOINTS, productionEndpoint);
                    endpointConfig.put(API_DATA_SANDBOX_ENDPOINTS, sandboxEndpoint);
                    apiDtoToReturn.setEndpointConfig(endpointConfig);
                }
            }
            CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.ASYNCAPI_DEFINITION_LOCATION, exportFormat, asyncApiJson);
        }
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonElement apiObj = gson.toJsonTree(apiDtoToReturn);
        JsonObject apiJson = (JsonObject) apiObj;
        apiJson.addProperty("organizationId", organization);
        CommonUtil.writeDtoToFile(archivePath + ImportExportConstants.API_FILE_LOCATION, exportFormat, ImportExportConstants.TYPE_API, apiJson);
    } catch (APIManagementException e) {
        throw new APIImportExportException("Error while retrieving Swagger definition for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion(), e);
    } catch (IOException e) {
        throw new APIImportExportException("Error while retrieving saving as YAML for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion(), e);
    }
}
Also used : GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) IOException(java.io.IOException) GraphQLQueryComplexityInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLQueryComplexityInfoDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) API(org.wso2.carbon.apimgt.api.model.API) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) JsonParser(com.google.gson.JsonParser)

Example 44 with Organization

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

the class RegistryPersistenceImpl method deleteThumbnail.

@Override
public void deleteThumbnail(Organization org, String apiId) throws ThumbnailPersistenceException {
    Registry registry;
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
        if (apiArtifact == null) {
            throw new ThumbnailPersistenceException("API not found for id " + apiId, ExceptionCodes.API_NOT_FOUND);
        }
        String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        apiProviderName = RegistryPersistenceUtil.replaceEmailDomain(apiProviderName);
        String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        String artifactOldPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProviderName + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion;
        String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProviderName + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion;
        String oldThumbPath = artifactOldPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
        String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
        if (registry.resourceExists(thumbPath)) {
            registry.delete(thumbPath);
        }
        if (registry.resourceExists(oldThumbPath)) {
            registry.delete(oldThumbPath);
        }
    } catch (RegistryException | APIPersistenceException e) {
        String msg = "Error while loading API icon of API " + apiId + " from the registry";
        throw new ThumbnailPersistenceException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 45 with Organization

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

the class RegistryPersistenceImpl method getAsyncDefinition.

@Override
public String getAsyncDefinition(Organization org, String apiId) throws AsyncSpecPersistenceException {
    String apiTenantDomain = org.getName();
    String definition = null;
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(apiTenantDomain);
        Registry registryType = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted;
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registryType, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        if (apiArtifact != null) {
            String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
            String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
            String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
            String apiPath = GovernanceUtils.getArtifactPath(registryType, apiId);
            int prependIndex = apiPath.lastIndexOf("/api");
            String apiSourcePath = apiPath.substring(0, prependIndex);
            String definitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
            if (registryType.resourceExists(definitionPath)) {
                Resource apiDocResource = registryType.get(definitionPath);
                definition = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
                return definition;
            }
        }
    } catch (RegistryException | APIPersistenceException e) {
        String msg = "Failed to get specification of API : " + apiId;
        throw new AsyncSpecPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
    return definition;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

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