use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class ImportUtils method importDependentAPIs.
/**
* This method imports dependent APIs of the API Product.
*
* @param path Location of the extracted folder of the API Product
* @param currentUser The current logged in user
* @param isDefaultProviderAllowed Decision to keep or replace the provider
* @param apiProvider API provider
* @param overwriteAPIs Whether to overwrite the APIs or not
* @param apiProductDto API Product DTO
* @param tokenScopes Scopes of the token
* @param organization Organization Identifier
* @return Modified API Product DTO with the correct API UUIDs
* @throws IOException If there is an error while reading an API file
* @throws APIImportExportException If there is an error in importing an API
* @throws APIManagementException If failed to get the API Provider of an API, or failed when
* checking the existence of an API
*/
private static APIProductDTO importDependentAPIs(String path, String currentUser, boolean isDefaultProviderAllowed, APIProvider apiProvider, boolean overwriteAPIs, Boolean rotateRevision, APIProductDTO apiProductDto, String[] tokenScopes, String organization) throws IOException, APIManagementException {
JsonObject dependentAPIParamsConfigObject = null;
// Retrieve the dependent APIs param configurations from the params file of the API Product
JsonObject dependentAPIsParams = APIControllerUtil.getDependentAPIsParams(path);
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();
// API in the API directory will be retrieved if available
if (dependentAPIsParams != null) {
dependentAPIParamsConfigObject = APIControllerUtil.getDependentAPIParams(dependentAPIsParams, apiDirectory.getName());
// If the "certificates" directory is specified, copy it inside Deployment directory of the
// dependent API since there may be certificates required for APIs
String deploymentCertificatesDirectoryPath = path + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
if (CommonUtil.checkFileExistence(deploymentCertificatesDirectoryPath)) {
try {
CommonUtil.copyDirectory(deploymentCertificatesDirectoryPath, apiDirectoryPath + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY);
} catch (APIImportExportException e) {
throw new APIManagementException("Error while copying the directory " + deploymentCertificatesDirectoryPath, e);
}
}
}
JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, isDefaultProviderAllowed, currentUser, ImportExportConstants.TYPE_API);
APIDTO apiDtoToImport = new Gson().fromJson(jsonObject, APIDTO.class);
API importedApi = null;
String apiName = apiDtoToImport.getName();
String apiVersion = apiDtoToImport.getVersion();
if (isDefaultProviderAllowed) {
APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiDtoToImport.getProvider()), apiName, apiVersion);
// Checking whether the API exists
if (apiProvider.isAPIAvailable(apiIdentifier, organization)) {
// otherwise do not update the API. (Just skip it)
if (Boolean.TRUE.equals(overwriteAPIs)) {
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
} else {
// If the API is not already imported, import it
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
} else {
// Retrieve the current tenant domain of the logged in user
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser));
// Get the provider of the API if the API is in current user's tenant domain.
String apiProviderInCurrentTenantDomain = APIUtil.getAPIProviderFromAPINameVersionTenant(apiName, apiVersion, currentTenantDomain);
if (StringUtils.isBlank(apiProviderInCurrentTenantDomain)) {
// If there is no API in the current tenant domain (which means the provider name is blank)
// then the API should be imported freshly
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.FALSE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
} else {
// otherwise do not import/update the API. (Just skip it)
if (Boolean.TRUE.equals(overwriteAPIs)) {
importedApi = importApi(apiDirectoryPath, apiDtoToImport, isDefaultProviderAllowed, rotateRevision, Boolean.TRUE, Boolean.TRUE, tokenScopes, dependentAPIParamsConfigObject, organization);
}
}
}
if (importedApi == null) {
// Retrieve the API from the environment (This happens when you have not specified
// the overwrite flag, so that we should retrieve the API from inside)
importedApi = retrieveApiToOverwrite(apiDtoToImport.getName(), apiDtoToImport.getVersion(), MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
}
updateApiUuidInApiProduct(apiProductDto, importedApi);
}
} else {
String msg = "No dependent APIs supplied. Continuing ...";
log.info(msg);
}
return apiProductDto;
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addDocumentationContentForFile.
/**
* Add documentation content of files.
*
* @param inputStream Input Stream
* @param mediaType Media type of the document
* @param filename File name
* @param apiProvider API Provider
* @param apiId API/API Product UUID
* @param documentId Document ID
* @param organization organization of the API
* @throws APIManagementException If an error occurs while adding the documentation file
*/
public static void addDocumentationContentForFile(InputStream inputStream, String mediaType, String filename, APIProvider apiProvider, String apiId, String documentId, String organization) throws APIManagementException {
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, mediaType);
resourceFile.setName(filename);
content.setResourceFile(resourceFile);
content.setSourceType(DocumentationContent.ContentSourceType.FILE);
apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class PublisherCommonUtils method prepareToCreateAPIByDTO.
/**
* Prepares the API Model object to be created using the DTO object.
*
* @param body APIDTO of the API
* @param apiProvider API Provider
* @param username Username
* @param organization Organization Identifier
* @return API object to be created
* @throws APIManagementException Error while creating the API
*/
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
String context = body.getContext();
// Make sure context starts with "/". ex: /pizza
context = context.startsWith("/") ? context : ("/" + context);
if (body.getAccessControlRoles() != null) {
String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
if (body.getAdditionalProperties() != null) {
String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
}
}
if (body.getContext() == null) {
throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
} else if (body.getContext().endsWith("/")) {
throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
}
if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
}
if (body.getAuthorizationHeader() == null) {
body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
}
if (body.getAuthorizationHeader() == null) {
body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
}
if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
}
if (body.getVisibleRoles() != null) {
String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
if (!errorMessage.isEmpty()) {
throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
}
}
// Get all existing versions of api been adding
List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
if (apiVersions.size() > 0) {
// If any previous version exists
for (String version : apiVersions) {
if (version.equalsIgnoreCase(body.getVersion())) {
// If version already exists
if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
} else {
throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
}
}
}
} else {
// If no any previous version exists
if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
}
}
// Check if the user has admin permission before applying a different provider than the current user
String provider = body.getProvider();
if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
if (log.isDebugEnabled()) {
log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
}
provider = username;
} else {
if (!APIUtil.isUserExist(provider)) {
throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
}
} else {
// Set username in case provider is null or empty
provider = username;
}
List<String> tiersFromDTO = body.getPolicies();
// check whether the added API's tiers are all valid
Set<Tier> definedTiers = apiProvider.getTiers();
List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
if (invalidTiers.size() > 0) {
throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
}
APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
}
API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
// only allow CREATED as the stating state for the new api if not status is PROTOTYPED
if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
apiToAdd.setStatus(APIConstants.CREATED);
}
if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
// we are setting the api owner as the logged in user until we support checking admin privileges and
// assigning the owner as a different user
apiToAdd.setApiOwner(provider);
}
if (body.getKeyManagers() instanceof List) {
apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
} else if (body.getKeyManagers() == null) {
apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
} else {
throw new APIManagementException("KeyManagers value need to be an array");
}
// Set default gatewayVendor
if (body.getGatewayVendor() == null) {
apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
}
apiToAdd.setOrganization(organization);
return apiToAdd;
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization 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;
}
use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.
the class APIMappingUtil method getMonetizationInfoDTO.
/**
* This method creates the API monetization information DTO.
*
* @param apiId API apiid
* @param organization identifier of the organization
* @return monetization information DTO
* @throws APIManagementException if failed to construct the DTO
*/
public static APIMonetizationInfoDTO getMonetizationInfoDTO(String apiId, String organization) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
// set the information relatated to monetization to the DTO
apiMonetizationInfoDTO.setEnabled(api.getMonetizationStatus());
Map<String, String> monetizationPropertiesMap = new HashMap<>();
if (api.getMonetizationProperties() != null) {
JSONObject monetizationProperties = api.getMonetizationProperties();
for (Object propertyKey : monetizationProperties.keySet()) {
String key = (String) propertyKey;
monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
}
}
apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
return apiMonetizationInfoDTO;
}
Aggregations