use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class MappingUtil method toAPI.
/**
* This method converts the API model object from the DTO object.
*
* @param apidto APIDTO object with API data
* @return APIBuilder object
*/
public static API.APIBuilder toAPI(APIDTO apidto) throws JsonProcessingException {
BusinessInformation businessInformation = new BusinessInformation();
API_businessInformationDTO apiBusinessInformationDTO = apidto.getBusinessInformation();
if (apiBusinessInformationDTO != null) {
businessInformation.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
businessInformation.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
businessInformation.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
businessInformation.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
}
API_corsConfigurationDTO apiCorsConfigurationDTO = apidto.getCorsConfiguration();
CorsConfiguration corsConfiguration = new CorsConfiguration();
if (apiCorsConfigurationDTO != null) {
corsConfiguration.setAllowCredentials(apiCorsConfigurationDTO.getAccessControlAllowCredentials());
corsConfiguration.setAllowHeaders(apiCorsConfigurationDTO.getAccessControlAllowHeaders());
corsConfiguration.setAllowMethods(apiCorsConfigurationDTO.getAccessControlAllowMethods());
corsConfiguration.setAllowOrigins(apiCorsConfigurationDTO.getAccessControlAllowOrigins());
corsConfiguration.setEnabled(apiCorsConfigurationDTO.getCorsConfigurationEnabled());
}
List<API_operationsDTO> operationList = apidto.getOperations();
Map<String, UriTemplate> uriTemplateList = new HashMap<>();
for (API_operationsDTO operationsDTO : operationList) {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder();
uriTemplateBuilder.uriTemplate(operationsDTO.getUritemplate());
uriTemplateBuilder.authType(operationsDTO.getAuthType());
uriTemplateBuilder.httpVerb(operationsDTO.getHttpVerb());
uriTemplateBuilder.policy(new APIPolicy(operationsDTO.getPolicy()));
uriTemplateBuilder.scopes(operationsDTO.getScopes());
if (operationsDTO.getEndpoint() != null && !operationsDTO.getEndpoint().isEmpty()) {
uriTemplateBuilder.endpoint(fromEndpointListToMap(operationsDTO.getEndpoint()));
}
if (operationsDTO.getId() != null) {
uriTemplateBuilder.templateId(operationsDTO.getId());
} else {
uriTemplateBuilder.templateId(APIUtils.generateOperationIdFromPath(operationsDTO.getUritemplate(), operationsDTO.getHttpVerb()));
}
uriTemplateList.put(uriTemplateBuilder.getTemplateId(), uriTemplateBuilder.build());
}
Set<Policy> subscriptionPolicies = new HashSet<>();
apidto.getPolicies().forEach(v -> subscriptionPolicies.add(new SubscriptionPolicy(v)));
API.APIBuilder apiBuilder = new API.APIBuilder(apidto.getProvider(), apidto.getName(), apidto.getVersion()).id(apidto.getId()).context(apidto.getContext()).description(apidto.getDescription()).lifeCycleStatus(apidto.getLifeCycleStatus()).endpoint(fromEndpointListToMap(apidto.getEndpoint())).visibleRoles(new HashSet<>(apidto.getVisibleRoles())).policies(subscriptionPolicies).apiPermission(apidto.getPermission()).tags(new HashSet<>(apidto.getTags())).labels(new ArrayList<>(apidto.getLabels())).transport(new HashSet<>(apidto.getTransport())).isResponseCachingEnabled(Boolean.valueOf(apidto.getResponseCaching())).businessInformation(businessInformation).uriTemplates(uriTemplateList).corsConfiguration(corsConfiguration).wsdlUri(apidto.getWsdlUri()).scopes(apidto.getScopes()).securityScheme(mapSecuritySchemeListToInt(apidto.getSecurityScheme()));
if (apidto.getIsDefaultVersion() != null) {
apiBuilder.isDefaultVersion(apidto.getIsDefaultVersion());
}
if (apidto.getVisibility() != null) {
apiBuilder.visibility(API.Visibility.valueOf(apidto.getVisibility().toString()));
}
if (apidto.getCacheTimeout() != null) {
apiBuilder.cacheTimeout(apidto.getCacheTimeout());
}
if (apidto.getApiPolicy() != null) {
Policy policy = new APIPolicy(apidto.getApiPolicy());
apiBuilder.apiPolicy(policy);
}
if (apidto.getHasOwnGateway() != null) {
apiBuilder.hasOwnGateway(apidto.getHasOwnGateway());
}
if (apidto.getThreatProtectionPolicies() != null) {
API_threatProtectionPoliciesDTO threatProtectionPoliciesDTO = apidto.getThreatProtectionPolicies();
List<API_threatProtectionPolicies_listDTO> threatProtectionPolicies_listDTO = threatProtectionPoliciesDTO.getList();
Set<String> policyIdSet = new HashSet<>();
for (API_threatProtectionPolicies_listDTO listDTO : threatProtectionPolicies_listDTO) {
policyIdSet.add(listDTO.getPolicyId());
}
apiBuilder.threatProtectionPolicies(policyIdSet);
}
return apiBuilder;
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class ApiImportExportManager method addAPIDetails.
/**
* Adds the API details
*
* @param apiDetails {@link APIDetails} instance
* @throws APIManagementException if an error occurs while adding API details
*/
public void addAPIDetails(APIDetails apiDetails) throws APIManagementException {
// update everything
String swaggerDefinition = apiDetails.getSwaggerDefinition();
String gatewayConfig = apiDetails.getGatewayConfiguration();
Map<String, Endpoint> endpointTypeToIdMap = apiDetails.getApi().getEndpoint();
Map<String, UriTemplate> uriTemplateMap = apiDetails.getApi().getUriTemplates();
// endpoints
for (Endpoint endpoint : apiDetails.getEndpoints()) {
try {
Endpoint existingEndpoint = apiPublisher.getEndpointByName(endpoint.getName());
String endpointId;
if (existingEndpoint == null) {
// no endpoint by that name, add it
endpointId = apiPublisher.addEndpoint(endpoint);
} else {
endpointId = existingEndpoint.getId();
if (log.isDebugEnabled()) {
log.debug("Endpoint with id " + endpoint.getId() + " already exists, not adding again");
}
// endpoint with same name exists, add to endpointTypeToIdMap
// endpointTypeToIdMap.put(endpoint.getType(), existingEndpoint.getId());
}
endpointTypeToIdMap.forEach((String k, Endpoint v) -> {
if (endpoint.getName().equals(v.getName())) {
Endpoint replacedEndpoint = new Endpoint.Builder(v).id(endpointId).build();
endpointTypeToIdMap.replace(k, replacedEndpoint);
}
});
uriTemplateMap.forEach(((String templateId, UriTemplate uriTemplate) -> {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(uriTemplate);
Map<String, Endpoint> uriEndpointMap = uriTemplateBuilder.getEndpoint();
uriEndpointMap.forEach((String type, Endpoint endpoint1) -> {
if (endpoint.getName().equals(endpoint1.getName())) {
Endpoint replacedEndpoint = new Endpoint.Builder(endpoint1).id(endpointId).build();
uriEndpointMap.replace(type, replacedEndpoint);
}
});
uriTemplateMap.replace(templateId, uriTemplateBuilder.endpoint(uriEndpointMap).build());
}));
} catch (APIManagementException e) {
// skip adding this API; log and continue
log.error("Error while adding the endpoint with id: " + endpoint.getId() + ", type: " + endpoint.getType() + " for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
}
}
API.APIBuilder apiBuilder = new API.APIBuilder(apiDetails.getApi());
apiPublisher.addAPI(apiBuilder.apiDefinition(swaggerDefinition).gatewayConfig(gatewayConfig).endpoint(endpointTypeToIdMap).uriTemplates(uriTemplateMap));
// docs
try {
Set<DocumentInfo> documentInfo = apiDetails.getAllDocumentInformation();
for (DocumentInfo aDocInfo : documentInfo) {
apiPublisher.addDocumentationInfo(apiDetails.getApi().getId(), aDocInfo);
}
for (DocumentContent aDocContent : apiDetails.getDocumentContents()) {
// add documentation
if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.FILE)) {
apiPublisher.uploadDocumentationFile(aDocContent.getDocumentInfo().getId(), aDocContent.getFileContent(), URLConnection.guessContentTypeFromStream(aDocContent.getFileContent()));
} else if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
apiPublisher.addDocumentationContent(aDocContent.getDocumentInfo().getId(), aDocContent.getInlineContent());
}
}
} catch (APIManagementException e) {
// no need to throw, log and continue
log.error("Error while adding Document details for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
} catch (IOException e) {
// no need to throw, log and continue
log.error("Error while retrieving content type of the File documentation of API : " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
}
// add thumbnail
try {
apiPublisher.saveThumbnailImage(apiDetails.getApi().getId(), apiDetails.getThumbnailStream(), "thumbnail");
} catch (APIManagementException e) {
// no need to throw, log and continue
log.error("Error while adding thumbnail for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
}
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class MappingUtilTestCase method convertToResourceListDtoTest.
@Test
public void convertToResourceListDtoTest() {
List<UriTemplate> uriTemplateList = new ArrayList<>();
uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
uriTemplateList.add(SampleTestObjectCreator.createUniqueUriTemplate());
List<UriTemplateDTO> uriTemplateDTOList = MappingUtil.convertToResourceListDto(uriTemplateList);
Assert.assertEquals(uriTemplateDTOList.size(), uriTemplateList.size());
for (int i = 0; i < uriTemplateDTOList.size(); i++) {
Assert.assertEquals(uriTemplateList.get(i).getUriTemplate(), uriTemplateDTOList.get(i).getUriTemplate());
Assert.assertEquals(uriTemplateList.get(i).getAuthType(), uriTemplateDTOList.get(i).getAuthType());
Assert.assertEquals(uriTemplateList.get(i).getHttpVerb(), uriTemplateDTOList.get(i).getHttpVerb());
Assert.assertEquals(uriTemplateList.get(i).getPolicy().getUuid(), uriTemplateDTOList.get(i).getPolicy());
}
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20TestCase method testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity.
@Test
public void testGenerateMergedResourceDefinitionWhileAddingRootLevelSecurity() throws IOException {
APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithoutRootLevelSecurity.yaml"));
UriTemplate uriTemplate1 = new UriTemplate.UriTemplateBuilder().uriTemplate("/apis").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
UriTemplate uriTemplate2 = new UriTemplate.UriTemplateBuilder().uriTemplate("/endpoints").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
Map<String, UriTemplate> hasTemplateMap = new HashMap<>();
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate1.getUriTemplate(), uriTemplate1.getHttpVerb()), uriTemplate1);
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate2.getUriTemplate(), uriTemplate2.getHttpVerb()), uriTemplate2);
API api = new API.APIBuilder("admin", "admin", "1.0.0").uriTemplates(hasTemplateMap).id(UUID.randomUUID().toString()).scopes(Arrays.asList("apim:api_create")).build();
apiDefinitionFromSwagger20.generateMergedResourceDefinition(sampleApi, api);
}
use of org.wso2.carbon.apimgt.api.model.URITemplate in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure.
@Test(description = "Test add api with Api Specific Endpoint", expectedExceptions = { APIManagementException.class })
public void testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure() throws APIManagementException, LifecycleException {
/**
* this test method verify the API Add with correct API object get invoked correctly
*/
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
Endpoint globalEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("testEndpoint").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).build();
Endpoint apiEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("apiEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
Endpoint resourceEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("resourceEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
Map<String, Endpoint> endpointMap = new HashMap();
endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, globalEndpoint);
endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, apiEndpoint);
Map<String, Endpoint> resourceEndpoints = new HashMap();
resourceEndpoints.put(APIMgtConstants.SANDBOX_ENDPOINT, resourceEndpoint);
Map<String, UriTemplate> uriTemplateMap = SampleTestObjectCreator.getMockUriTemplates();
uriTemplateMap.forEach((k, v) -> {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
uriTemplateBuilder.endpoint(resourceEndpoints);
uriTemplateMap.replace(k, uriTemplateBuilder.build());
});
API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().endpoint(endpointMap).uriTemplates(uriTemplateMap);
Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
APIGateway gateway = Mockito.mock(APIGateway.class);
LabelDAO labelDao = Mockito.mock(LabelDAO.class);
APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, null, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
Mockito.when(apiDAO.getEndpoint(globalEndpoint.getId())).thenReturn(globalEndpoint);
Mockito.when(apiDAO.getEndpointByName(apiEndpoint.getName())).thenReturn(null);
Mockito.when(apiDAO.getEndpointByName(resourceEndpoint.getName())).thenThrow(APIMgtDAOException.class);
Mockito.when(apiDAO.isAPINameExists(apiBuilder.getName(), USER)).thenReturn(false);
apiPublisher.addAPI(apiBuilder);
Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(apiEndpoint.getName());
Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(resourceEndpoint.getName());
}
Aggregations