Search in sources :

Example 81 with Provider

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

the class ExportUtils method setAdvertiseOnlySpecificPropertiesToDTO.

/**
 * Set the properties specific to advertise only APIs
 *
 * @param apiDto               API DTO to export
 * @param originalDevPortalUrl Original DevPortal URL (redirect URL) for the original Store
 *                             (This is used for advertise only APIs).
 */
private static void setAdvertiseOnlySpecificPropertiesToDTO(APIDTO apiDto, String originalDevPortalUrl) {
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(Boolean.TRUE);
    // Change owner to original provider as the provider will be overriding after importing
    advertiseInfoDTO.setApiOwner(apiDto.getProvider());
    advertiseInfoDTO.setOriginalDevPortalUrl(originalDevPortalUrl);
    apiDto.setAdvertiseInfo(advertiseInfoDTO);
    apiDto.setMediationPolicies(null);
}
Also used : AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO)

Example 82 with Provider

use of org.wso2.carbon.apimgt.api.model.Provider 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 83 with Provider

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

the class ExportUtils method addMultipleAPISpecificSequencesToArchive.

/**
 * Retrieve multiple API specific sequences for API export, and store it in the archive
 * directory.
 *
 * @param archivePath File path to export the sequences
 * @param api         API
 * @param apiProvider API Provider
 * @throws APIManagementException   If an error occurs while retrieving sequences and writing those
 * @throws APIImportExportException If an error occurs while creating the directory to export sequences
 */
private static void addMultipleAPISpecificSequencesToArchive(String archivePath, API api, APIProvider apiProvider) throws APIManagementException, APIImportExportException {
    String seqArchivePath = archivePath.concat(File.separator + ImportExportConstants.SEQUENCES_RESOURCE);
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    if (!CommonUtil.checkFileExistence(seqArchivePath)) {
        CommonUtil.createDirectory(seqArchivePath);
    }
    // Getting list of API specific custom mediation policies
    List<Mediation> apiSpecificMediationList = apiProvider.getAllApiSpecificMediationPolicies(api.getUuid(), tenantDomain);
    if (!apiSpecificMediationList.isEmpty()) {
        for (Mediation mediation : apiSpecificMediationList) {
            Mediation mediationResource = apiProvider.getApiSpecificMediationPolicyByPolicyId(api.getUuid(), mediation.getUuid(), tenantDomain);
            String individualSequenceExportPath = seqArchivePath + File.separator + mediation.getType().toLowerCase() + ImportExportConstants.SEQUENCE_LOCATION_POSTFIX + File.separator + ImportExportConstants.CUSTOM_TYPE;
            if (!CommonUtil.checkFileExistence(individualSequenceExportPath)) {
                CommonUtil.createDirectory(individualSequenceExportPath);
            }
            writeSequenceToArchive(mediationResource.getConfig(), individualSequenceExportPath, mediation.getName());
        }
    }
}
Also used : Mediation(org.wso2.carbon.apimgt.api.model.Mediation)

Example 84 with Provider

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

the class ExportUtils method addThumbnailToArchive.

/**
 * Retrieve thumbnail image for the exporting API or API Product and store it in the archive directory.
 *
 * @param archivePath File path to export the thumbnail image
 * @param identifier  ID of the requesting API or API Product
 * @param apiProvider API Provider
 * @throws APIImportExportException If an error occurs while retrieving image from the registry or
 *                                  storing in the archive directory
 */
public static void addThumbnailToArchive(String archivePath, Identifier identifier, APIProvider apiProvider) throws APIImportExportException, APIManagementException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    String localImagePath = archivePath + File.separator + ImportExportConstants.IMAGE_RESOURCE;
    try {
        ResourceFile thumbnailResource = apiProvider.getIcon(identifier.getUUID(), tenantDomain);
        if (thumbnailResource != null) {
            String mediaType = thumbnailResource.getContentType();
            String extension = ImportExportConstants.fileExtensionMapping.get(mediaType);
            if (extension != null) {
                CommonUtil.createDirectory(localImagePath);
                try (InputStream imageDataStream = thumbnailResource.getContent();
                    OutputStream outputStream = new FileOutputStream(localImagePath + File.separator + APIConstants.API_ICON_IMAGE + APIConstants.DOT + extension)) {
                    IOUtils.copy(imageDataStream, outputStream);
                    if (log.isDebugEnabled()) {
                        log.debug("Thumbnail image retrieved successfully for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion());
                    }
                }
            } else {
                // api gets imported without thumbnail
                log.error("Unsupported media type for icon " + mediaType + ". Skipping thumbnail export.");
            }
        } else if (log.isDebugEnabled()) {
            log.debug("Thumbnail URL does not exists in registry for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion() + ". Skipping thumbnail export.");
        }
    } catch (IOException e) {
        // Exception is ignored by logging due to the reason that Thumbnail is not essential for
        // an API to be recreated.
        log.error("I/O error while writing API/API Product Thumbnail to file", e);
    }
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException)

Example 85 with Provider

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

the class RegistrationServiceImpl method createApplication.

/**
 * Create a new client application
 *
 * @param appRequest OAuthAppRequest object with client's payload content
 * @return created Application
 * @throws APIKeyMgtException if failed to create the a new application
 */
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
    String userName;
    OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
    String appName = applicationInfo.getClientName();
    String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
    boolean isTenantFlowStarted = false;
    if (userId == null || userId.isEmpty()) {
        return null;
    }
    userName = MultitenantUtils.getTenantAwareUsername(userId);
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
        }
        // Creating the service provider
        ServiceProvider serviceProvider = new ServiceProvider();
        serviceProvider.setApplicationName(applicationName);
        serviceProvider.setDescription("Service Provider for application " + appName);
        serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
        ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
        serviceProviderProperty.setName(APP_DISPLAY_NAME);
        serviceProviderProperty.setValue(applicationName);
        serviceProviderProperties[0] = serviceProviderProperty;
        ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
        tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
        tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
        serviceProviderProperties[1] = tokenTypeProviderProperty;
        ServiceProviderProperty consentProperty = new ServiceProviderProperty();
        consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
        consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
        consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
        serviceProviderProperties[2] = consentProperty;
        ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
        logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
        logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
        logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
        serviceProviderProperties[3] = logoutConsentProperty;
        serviceProvider.setSpProperties(serviceProviderProperties);
        ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
        appMgtService.createApplication(serviceProvider, tenantDomain, userName);
        // Retrieving the created service provider
        ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
        if (createdServiceProvider == null) {
            throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
        }
        // creating the OAuth app
        OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
        // Set the OAuthApp in InboundAuthenticationConfig
        InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
        InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
        InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
        String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
        inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
        inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
        String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
        if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
            Property property = new Property();
            property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
            property.setValue(oauthConsumerSecret);
            Property[] properties = { property };
            inboundAuthenticationRequestConfig.setProperties(properties);
        }
        inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
        inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
        createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
        // Setting the SaasApplication attribute to created service provider
        createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        createdServiceProvider.setSpProperties(serviceProviderProperties);
        // Updating the service provider with Inbound Authentication Configs and SaasApplication
        appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
        Map<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
        valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
        valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
        return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
    } catch (IdentityApplicationManagementException e) {
        log.error("Error occurred while creating the client application " + appName, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
        }
    }
    return null;
}
Also used : InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) HashMap(java.util.HashMap) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) Property(org.wso2.carbon.identity.application.common.model.Property)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)82 ArrayList (java.util.ArrayList)70 API (org.wso2.carbon.apimgt.api.model.API)64 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)50 Test (org.junit.Test)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)45 HashMap (java.util.HashMap)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)36 IOException (java.io.IOException)35 Resource (org.wso2.carbon.registry.core.Resource)34 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)32 HashSet (java.util.HashSet)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 UserStoreException (org.wso2.carbon.user.api.UserStoreException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)27 ResultSet (java.sql.ResultSet)25 QName (javax.xml.namespace.QName)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25