use of org.wso2.carbon.apimgt.internal.service.dto.APIDTO 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.internal.service.dto.APIDTO in project carbon-apimgt by wso2.
the class SecurityConfigContextTest method testSecurityConfigContextForAPIProduct.
@Test
public void testSecurityConfigContextForAPIProduct() throws Exception {
APIProduct apiProduct = new APIProduct(new APIProductIdentifier("admin", "TestProduct", "1.0.0"));
apiProduct.setUuid(UUID.randomUUID().toString());
String apiid = UUID.randomUUID().toString();
List<APIProductResource> apiProductResourceList = new ArrayList<>();
APIProductResource apiProductResource = new APIProductResource();
apiProductResource.setApiIdentifier(new APIIdentifier("admin_api1_v1"));
apiProductResource.setApiId(apiid);
Map<String, EndpointSecurity> endpointSecurityMap = new HashMap<>();
EndpointSecurity endpointSecurity = new EndpointSecurity();
endpointSecurity.setType("BASIC");
endpointSecurity.setUsername("admin");
endpointSecurity.setPassword("admin123");
endpointSecurity.setEnabled(true);
endpointSecurityMap.put("production", endpointSecurity);
apiProductResource.setApiId(apiid);
apiProductResource.setEndpointSecurityMap(endpointSecurityMap);
apiProductResourceList.add(apiProductResource);
apiProduct.setProductResources(apiProductResourceList);
ConfigContext configcontext = new APIConfigContext(apiProduct);
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
Map<String, APIDTO> apidtoMap = new HashMap<>();
apidtoMap.put(apiid, new APIDTO().name("api1").version("v1").provider("admin"));
SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, apiProduct, apiManagerConfiguration, apidtoMap);
securityConfigContext.validate();
VelocityContext velocityContext = securityConfigContext.getContext();
Assert.assertNotNull(velocityContext.get("endpoint_security"));
Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = (Map<String, Map<String, EndpointSecurityModel>>) velocityContext.get("endpoint_security");
Map<String, EndpointSecurityModel> endpointSecurityModelMap1 = endpointSecurityModelMap.get(apiProductResource.getApiId());
EndpointSecurityModel production = endpointSecurityModelMap1.get("production");
Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
Assert.assertTrue("Property base64value does not match. ", new String(Base64.encodeBase64("admin:admin123".getBytes())).equalsIgnoreCase(production.getBase64EncodedPassword()));
Assert.assertTrue("Property securevault_alias does not match.", "TestProduct--v1.0.0--api1--vv1--production".equalsIgnoreCase(production.getAlias()));
Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
use of org.wso2.carbon.apimgt.internal.service.dto.APIDTO in project carbon-apimgt by wso2.
the class SecurityConfigContextTest method testSecurityConfigContextForAPIProductWithOAuth.
@Test
public void testSecurityConfigContextForAPIProductWithOAuth() throws Exception {
APIProduct apiProduct = new APIProduct(new APIProductIdentifier("admin", "TestProduct", "1.0.0"));
apiProduct.setUuid(UUID.randomUUID().toString());
String apiid = UUID.randomUUID().toString();
List<APIProductResource> apiProductResourceList = new ArrayList<>();
APIProductResource apiProductResource = new APIProductResource();
apiProductResource.setApiIdentifier(new APIIdentifier("admin_api1_v1"));
apiProductResource.setApiId(apiid);
Map<String, EndpointSecurity> endpointSecurityMap = new HashMap<>();
EndpointSecurity endpointSecurity = new EndpointSecurity();
endpointSecurity.setType("oauth");
endpointSecurity.setClientId("123-456");
endpointSecurity.setClientSecret("admin123");
endpointSecurity.setGrantType("client_credentials");
endpointSecurity.setEnabled(true);
endpointSecurityMap.put("production", endpointSecurity);
apiProductResource.setApiId(apiid);
apiProductResource.setEndpointSecurityMap(endpointSecurityMap);
apiProductResourceList.add(apiProductResource);
apiProduct.setProductResources(apiProductResourceList);
ConfigContext configcontext = new APIConfigContext(apiProduct);
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
Map<String, APIDTO> apidtoMap = new HashMap<>();
apidtoMap.put(apiid, new APIDTO().name("api1").version("v1").provider("admin").id(UUID.randomUUID().toString()));
SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, apiProduct, apiManagerConfiguration, apidtoMap);
securityConfigContext.validate();
VelocityContext velocityContext = securityConfigContext.getContext();
Assert.assertNotNull(velocityContext.get("endpoint_security"));
Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = (Map<String, Map<String, EndpointSecurityModel>>) velocityContext.get("endpoint_security");
Map<String, EndpointSecurityModel> endpointSecurityModelMap1 = endpointSecurityModelMap.get(apiProductResource.getApiId());
EndpointSecurityModel production = endpointSecurityModelMap1.get("production");
Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("oauth"));
Assert.assertTrue("Property username does not match.", "123-456".equals(production.getClientId()));
Assert.assertEquals(production.getClientSecretAlias(), "TestProduct--v1.0.0--api1--vv1--oauth--clientSecret" + "--production");
Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
use of org.wso2.carbon.apimgt.internal.service.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createNewAPIVersion.
@Override
public Response createNewAPIVersion(String newVersion, String apiId, Boolean defaultVersion, String serviceVersion, MessageContext messageContext) throws APIManagementException {
URI newVersionedApiUri;
APIDTO newVersionedApi = new APIDTO();
ServiceEntry service = new ServiceEntry();
try {
APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
if (apiIdentifierFromTable == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
int tenantId = APIUtil.getInternalOrganizationId(organization);
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
if (existingAPI == null) {
throw new APIMgtResourceNotFoundException("API not found for id " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
if (newVersion.equals(existingAPI.getId().getVersion())) {
throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName(), ExceptionCodes.from(API_VERSION_ALREADY_EXISTS, newVersion, existingAPI.getId().getApiName()));
}
if (StringUtils.isNotEmpty(serviceVersion)) {
String serviceName = existingAPI.getServiceInfo("name");
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
service = serviceCatalog.getServiceByNameAndVersion(serviceName, serviceVersion, tenantId);
if (service == null) {
throw new APIManagementException("No matching service version found", ExceptionCodes.SERVICE_VERSION_NOT_FOUND);
}
}
if (StringUtils.isNotEmpty(serviceVersion) && !serviceVersion.equals(existingAPI.getServiceInfo("version"))) {
APIDTO apidto = createAPIDTO(existingAPI, newVersion);
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
newVersionedApi = importOpenAPIDefinition(service.getEndpointDef(), null, null, apidto, null, service, organization);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
newVersionedApi = importAsyncAPISpecification(service.getEndpointDef(), null, apidto, null, service, organization);
}
} else {
API versionedAPI = apiProvider.createNewAPIVersion(apiId, newVersion, defaultVersion, organization);
newVersionedApi = APIMappingUtil.fromAPItoDTO(versionedAPI);
}
// This URI used to set the location header of the POST response
newVersionedApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + newVersionedApi.getId());
return Response.created(newVersionedApiUri).entity(newVersionedApi).build();
} catch (APIManagementException e) {
if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while copying API : " + apiId, e, log);
} else {
throw e;
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location of " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.internal.service.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method deployAPIRevision.
/**
* Deploy a revision
*
* @param apiId UUID of the API
* @param revisionId Revision ID of the API
* @param messageContext message context object
* @return response with 200 status code
*/
@Override
public Response deployAPIRevision(String apiId, String revisionId, List<APIRevisionDeploymentDTO> apIRevisionDeploymentDTOList, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate whether the API is advertise only
APIDTO apiDto = getAPIByID(apiId, apiProvider, organization);
if (apiDto != null && apiDto.getAdvertiseInfo() != null && apiDto.getAdvertiseInfo().isAdvertised()) {
throw new APIManagementException("Deploying API Revisions is not supported for third party APIs: " + apiId);
}
Map<String, Environment> environments = APIUtil.getEnvironments(organization);
List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
for (APIRevisionDeploymentDTO apiRevisionDeploymentDTO : apIRevisionDeploymentDTOList) {
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setRevisionUUID(revisionId);
String environment = apiRevisionDeploymentDTO.getName();
if (environments.get(environment) == null) {
RestApiUtil.handleBadRequest("Gateway environment not found: " + environment, log);
}
apiRevisionDeployment.setDeployment(environment);
apiRevisionDeployment.setVhost(apiRevisionDeploymentDTO.getVhost());
if (StringUtils.isEmpty(apiRevisionDeploymentDTO.getVhost())) {
// vhost is only required when deploying an revision, not required when un-deploying a revision
// since the same scheme 'APIRevisionDeployment' is used for deploy and undeploy, handle it here.
RestApiUtil.handleBadRequest("Required field 'vhost' not found in deployment", log);
}
apiRevisionDeployment.setDisplayOnDevportal(apiRevisionDeploymentDTO.isDisplayOnDevportal());
apiRevisionDeployments.add(apiRevisionDeployment);
}
apiProvider.deployAPIRevision(apiId, revisionId, apiRevisionDeployments, organization);
List<APIRevisionDeployment> apiRevisionDeploymentsResponse = apiProvider.getAPIRevisionsDeploymentList(apiId);
List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOS = new ArrayList<>();
for (APIRevisionDeployment apiRevisionDeployment : apiRevisionDeploymentsResponse) {
apiRevisionDeploymentDTOS.add(APIMappingUtil.fromAPIRevisionDeploymenttoDTO(apiRevisionDeployment));
}
Response.Status status = Response.Status.CREATED;
return Response.status(status).entity(apiRevisionDeploymentDTOS).build();
}
Aggregations