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);
}
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);
}
}
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());
}
}
}
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);
}
}
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;
}
Aggregations