diff --git a/manifest.yml b/manifest.yml index 5639293..31932cb 100644 --- a/manifest.yml +++ b/manifest.yml @@ -3,5 +3,5 @@ applications: - name: axway-apim-service-broker memory: 1G random-route: true - path: target/apim-service-broker-1.1.7.jar + path: target/apim-service-broker-1.1.8.jar \ No newline at end of file diff --git a/pom.xml b/pom.xml index 33cd230..7869f40 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.axway.apim apim-service-broker - 1.1.7 + 1.1.8 jar axway-apim-service-broker Axway APIM Service Broker diff --git a/src/main/java/com/axway/apim/servicebroker/AxwayServiceBrokerApplication.java b/src/main/java/com/axway/apim/servicebroker/AxwayServiceBrokerApplication.java index 09e3906..16e61d8 100644 --- a/src/main/java/com/axway/apim/servicebroker/AxwayServiceBrokerApplication.java +++ b/src/main/java/com/axway/apim/servicebroker/AxwayServiceBrokerApplication.java @@ -1,12 +1,17 @@ package com.axway.apim.servicebroker; +import com.axway.apim.servicebroker.service.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AxwayServiceBrokerApplication { + private static final Logger logger = LoggerFactory.getLogger(AxwayServiceBrokerApplication.class); - public static void main(String[] args) { - SpringApplication.run(AxwayServiceBrokerApplication.class, args); - } + public static void main(String[] args) { + logger.info("Version : {}", Constants.VERSION); + SpringApplication.run(AxwayServiceBrokerApplication.class, args); + } } diff --git a/src/main/java/com/axway/apim/servicebroker/model/APIOrganization.java b/src/main/java/com/axway/apim/servicebroker/model/APIOrganization.java index 8fa5bda..9f6eca4 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/APIOrganization.java +++ b/src/main/java/com/axway/apim/servicebroker/model/APIOrganization.java @@ -13,12 +13,9 @@ public class APIOrganization { private String phone; private boolean enabled = true; private boolean development = true; - //custom attribute private String service_instance_id; - - - + public String getId() { return id; } @@ -73,6 +70,4 @@ public String getService_instance_id() { public void setService_instance_id(String service_instance_id) { this.service_instance_id = service_instance_id; } - - } diff --git a/src/main/java/com/axway/apim/servicebroker/model/APIOrganizationAccess.java b/src/main/java/com/axway/apim/servicebroker/model/APIOrganizationAccess.java index b38be72..f5970a1 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/APIOrganizationAccess.java +++ b/src/main/java/com/axway/apim/servicebroker/model/APIOrganizationAccess.java @@ -5,21 +5,22 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class APIOrganizationAccess { - private String id; - private String apiId; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getApiId() { - return apiId; - } - public void setApiId(String apiId) { - this.apiId = apiId; - } - - + private String id; + private String apiId; + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getApiId() { + return apiId; + } + + public void setApiId(String apiId) { + this.apiId = apiId; + } } diff --git a/src/main/java/com/axway/apim/servicebroker/model/APISecurity.java b/src/main/java/com/axway/apim/servicebroker/model/APISecurity.java index 5ed1394..37421fa 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/APISecurity.java +++ b/src/main/java/com/axway/apim/servicebroker/model/APISecurity.java @@ -7,8 +7,7 @@ public class APISecurity { private String name = "Pass Through"; private String type = "passThrough"; private int order = 1; - - + private Properties properties; public APISecurity(){ @@ -17,8 +16,7 @@ public APISecurity(){ properties.setProperty("removeCredentialsOnSuccess", "true"); } - - + public String getName() { return name; } @@ -50,6 +48,4 @@ public Properties getProperties() { public void setProperties(Properties properties) { this.properties = properties; } - - } diff --git a/src/main/java/com/axway/apim/servicebroker/model/APIUser.java b/src/main/java/com/axway/apim/servicebroker/model/APIUser.java index b3c2d2d..1074f63 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/APIUser.java +++ b/src/main/java/com/axway/apim/servicebroker/model/APIUser.java @@ -18,9 +18,7 @@ public class APIUser { private long createdOn; //(integer, optional): Epoch/Unix time stamp when the organization was created , private String state = "approved"; //(string, optional): The current state of the account, one of: approved, pending , private String type = "internal"; //(string, optional): Indicates the type of user. Possible values: internal, external , - - - + public String getId() { return id; } @@ -75,7 +73,6 @@ public String getRole() { public void setRole(String role) { this.role = role; } - public boolean isEnabled() { return enabled; } @@ -100,6 +97,4 @@ public String getType() { public void setType(String type) { this.type = type; } - - } diff --git a/src/main/java/com/axway/apim/servicebroker/model/FrondendAPI.java b/src/main/java/com/axway/apim/servicebroker/model/FrontendAPI.java similarity index 96% rename from src/main/java/com/axway/apim/servicebroker/model/FrondendAPI.java rename to src/main/java/com/axway/apim/servicebroker/model/FrontendAPI.java index a8edb47..9efdd13 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/FrondendAPI.java +++ b/src/main/java/com/axway/apim/servicebroker/model/FrontendAPI.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) -public class FrondendAPI { +public class FrontendAPI { private String id; private String apiId; diff --git a/src/main/java/com/axway/apim/servicebroker/model/Type.java b/src/main/java/com/axway/apim/servicebroker/model/Type.java index 997109b..9bb6709 100644 --- a/src/main/java/com/axway/apim/servicebroker/model/Type.java +++ b/src/main/java/com/axway/apim/servicebroker/model/Type.java @@ -2,5 +2,4 @@ public enum Type { SWAGGER, WSDL - } diff --git a/src/main/java/com/axway/apim/servicebroker/service/AxwayAPIClient.java b/src/main/java/com/axway/apim/servicebroker/service/AxwayAPIClient.java index 0b65eb2..9e1dd1f 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/AxwayAPIClient.java +++ b/src/main/java/com/axway/apim/servicebroker/service/AxwayAPIClient.java @@ -1,224 +1,213 @@ package com.axway.apim.servicebroker.service; -import java.io.IOException; -import java.net.URI; -import java.util.List; - +import com.axway.apim.servicebroker.model.APIOrganizationAccess; +import com.axway.apim.servicebroker.model.APISecurity; +import com.axway.apim.servicebroker.model.FrontendAPI; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; +import org.springframework.http.*; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; -import com.axway.apim.servicebroker.model.APIOrganizationAccess; -import com.axway.apim.servicebroker.model.APISecurity; -import com.axway.apim.servicebroker.model.FrondendAPI; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.net.URI; +import java.util.List; public class AxwayAPIClient implements Constants { - private static final Logger logger = LoggerFactory.getLogger(AxwayAPIClient.class.getName()); - - @Autowired - // @Qualifier("getRestTemplate") - private RestTemplate restTemplate; - - @Autowired - private String url; - - @Autowired - private ObjectMapper mapper; - - public List listAPIs(String orgId) { - // https://phx-107.demo.axway.com:8075/api/portal/v1.3/organizations/14df2c8b-c28c-4062-ba8b-31449524a611/apis/ - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations/").path(orgId) - .path("/apis").build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); - ResponseEntity> frondendAPIs = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference>() { - }); - - return frondendAPIs.getBody(); - } - - public FrondendAPI getAPI(String apiId) { - - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(apiId).build() - .toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); - ResponseEntity apiEntity = restTemplate.exchange(requestEntity, - new ParameterizedTypeReference() { - }); - return apiEntity.getBody(); - } - - // public String listAPIsByState(String state) { - // - // HttpEntity httpEntity = new HttpEntity(authHeader); - // - // URI uri = - // UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/") - // .queryParam("field", "name").queryParam("op", "eq").queryParam("value", - // state).build().toUri(); - // - // ResponseEntity apiEntity = restTemplate.exchange(uri, - // HttpMethod.GET, httpEntity, String.class); - // String responseBody = apiEntity.getBody(); - // return responseBody; - // } - - /** - * To read unpublish, publish and pending APIs. - * - * @return - */ - public String listAPIs() { - // Get the API based on the name and apply the filters like unpublished - // and bindingId - // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies?field=name&op=eq&value=pcftest2 - - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies").build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); - // .queryParam("field", "name").queryParam("op", - // "eq").queryParam("value", apiName); - ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); - String responseBody = apiEntity.getBody(); - return responseBody; - } - - public void unpublishAPI(String frondEndApiId) { - // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies/5a0ce063-06df-485e-8b68-07fb19242422/unpublish - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(frondEndApiId) - .path("/unpublish").build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.POST, uri); - ResponseEntity frondendAPIs = restTemplate.exchange(requestEntity, String.class); - logger.info("API unpublished Response code {}", frondendAPIs.getStatusCodeValue()); - - } - - public void deleteFrondendAPI(String frondEndApiId) { - // delete Front End - // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies/c7c4a1d1-ce56-4bd3-be0b-dae0f9cf0f80 - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(frondEndApiId) - .build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.DELETE, uri); - logger.info("Deleting FrontEnd API"); - ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); - logger.info("Delete Front end API Response Code : {} ", apiEntity.getStatusCodeValue()); - - } - - public void deleteBackendAPI(String backendId) { - // Delete back end - // https://${APIManagerHost}:${APIManagerPort}/api/portal/v1.3/apirepo/${BackEndAPIID} - logger.info("Deleting BackeEnd API"); - URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/apirepo/").path(backendId).build() - .toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.DELETE, uri); - ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); - logger.info("Delete Back end API Response Code : {}", apiEntity.getStatusCodeValue()); - - } - - public String createBackend(String apiName, String orgId, String type, String swaggerURI) { - - URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/apirepo/importFromUrl").build().toUri(); - logger.info("Backend Creation URL : {}", uri.toString()); - MultiValueMap postParameters = new LinkedMultiValueMap<>(); - // Add query parameter - postParameters.add("organizationId", orgId); - if (apiName != null) { - postParameters.add("name", apiName); - } - - postParameters.add("type", type); - postParameters.add("url", swaggerURI); - - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - HttpEntity> request = new HttpEntity>( - postParameters, headers); - ResponseEntity strResponse = restTemplate.exchange(uri, HttpMethod.POST, request, String.class); - logger.info("Create Backend API Response code: {}", strResponse.getStatusCodeValue()); - return strResponse.getBody(); - } - - // public String updateBackend(String userId, String response) { - // JsonNode jsonNode ; - // try { - // jsonNode = mapper.readTree(response); - // } catch (JsonProcessingException e) { - // throw new ServiceBrokerException("Internal Error"); - // } catch (IOException e) { - // throw new ServiceBrokerException("Internal Error"); - // } - // String id = jsonNode.findPath("id").asText(); - // ((ObjectNode) jsonNode).put("createdBy" , userId); - // URI uri = UriComponentsBuilder.fromUriString(url + - // "/api/portal/v1.3/apirepo/" + id).build().toUri(); - // HttpEntity jsonEntity = new HttpEntity(jsonNode, - // authHeader); - // ResponseEntity securityUpdate = restTemplate.exchange(uri, - // HttpMethod.PUT, jsonEntity, String.class); - // logger.info("Update Backend Response Code : {}", - // securityUpdate.getStatusCodeValue()); - // return id; - // } - - public String createFrontend(String backendAPIId, String orgId, String userId) { - String json = "{\"apiId\":\"" + backendAPIId + "\",\"organizationId\":\"" + orgId + "\"}"; - JsonNode jsonNode; - try { - jsonNode = mapper.readTree(json); - } catch (IOException e) { - throw new ServiceBrokerException("Internal Error"); - } - URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/proxies/").build().toUri(); - RequestEntity jsonEntity = new RequestEntity(jsonNode, HttpMethod.POST, uri); - ResponseEntity virualizedAPIResponse = restTemplate.exchange(jsonEntity, String.class); - String frontEndAPIResponse = virualizedAPIResponse.getBody(); - return frontEndAPIResponse; - } - - public void applySecurity(String frontEndAPIResponse, String bindingId, String vhost, String userId) - throws ServiceBrokerException { - JsonNode jsonNode; - try { - jsonNode = mapper.readTree(frontEndAPIResponse); - } catch (JsonProcessingException e) { - throw new ServiceBrokerException("Internal Error"); - } catch (IOException e) { - throw new ServiceBrokerException("Internal Error"); - } - - ArrayNode devices = (ArrayNode) ((ArrayNode) jsonNode.findPath("securityProfiles")).get(0).get("devices"); - - String virtualAPIId = jsonNode.findPath("id").asText(); - ((ObjectNode) jsonNode).put(CF_BINDING_ID, bindingId); - ((ObjectNode) jsonNode).put(VHOST, vhost); - //((ObjectNode) jsonNode).put("path", "/" + bindingId); - // ((ObjectNode) jsonNode).put("createdBy" , userId); - - logger.debug("Security Device {}", devices.getClass().getName()); - devices.addPOJO(new APISecurity()); - URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/proxies/" + virtualAPIId).build().toUri(); - RequestEntity jsonEntity = new RequestEntity(jsonNode, HttpMethod.PUT, uri); - ResponseEntity securityUpdate = restTemplate.exchange(jsonEntity, String.class); - logger.info("Apply Security Response Code : {}", securityUpdate.getStatusCodeValue()); - } + private static final Logger logger = LoggerFactory.getLogger(AxwayAPIClient.class.getName()); + + @Autowired + // @Qualifier("getRestTemplate") + private RestTemplate restTemplate; + + @Autowired + private String url; + + @Autowired + private ObjectMapper mapper; + + public List listAPIs(String orgId) { + // https://phx-107.demo.axway.com:8075/api/portal/v1.3/organizations/14df2c8b-c28c-4062-ba8b-31449524a611/apis/ + URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations/").path(orgId) + .path("/apis").build().toUri(); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); + ResponseEntity> frontendAPIs = restTemplate.exchange(requestEntity, + new ParameterizedTypeReference>() { + }); + + return frontendAPIs.getBody(); + } + + public FrontendAPI getAPI(String apiId) { + + URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(apiId).build() + .toUri(); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); + ResponseEntity apiEntity = restTemplate.exchange(requestEntity, + new ParameterizedTypeReference() { + }); + return apiEntity.getBody(); + } + + // public String listAPIsByState(String state) { + // + // HttpEntity httpEntity = new HttpEntity(authHeader); + // + // URI uri = + // UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/") + // .queryParam("field", "name").queryParam("op", "eq").queryParam("value", + // state).build().toUri(); + // + // ResponseEntity apiEntity = restTemplate.exchange(uri, + // HttpMethod.GET, httpEntity, String.class); + // String responseBody = apiEntity.getBody(); + // return responseBody; + // } + + /** + * To read unpublish, publish and pending APIs. + * + * @return json response + */ + public String listAPIs() { + // Get the API based on the name and apply the filters like unpublished + // and bindingId + // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies?field=name&op=eq&value=pcftest2 + + URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies").build().toUri(); + RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + // .queryParam("field", "name").queryParam("op", + // "eq").queryParam("value", apiName); + ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); + return apiEntity.getBody(); + } + +// public void unpublishAPI(String frondEndApiId) { +// // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies/5a0ce063-06df-485e-8b68-07fb19242422/unpublish +// URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(frondEndApiId) +// .path("/unpublish").build().toUri(); +// RequestEntity requestEntity = new RequestEntity(HttpMethod.POST, uri); +// ResponseEntity frondendAPIs = restTemplate.exchange(requestEntity, String.class); +// logger.info("API unpublished Response code {}", frondendAPIs.getStatusCodeValue()); +// +// } + + public void deleteFrontendAPI(String frondEndApiId) { + // delete Front End + // https://phx-107.demo.axway.com:8075/api/portal/v1.3/proxies/c7c4a1d1-ce56-4bd3-be0b-dae0f9cf0f80 + URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/proxies/").path(frondEndApiId) + .build().toUri(); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.DELETE, uri); + logger.info("Deleting FrontEnd API"); + ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); + logger.info("Delete Front end API Response Code : {} ", apiEntity.getStatusCodeValue()); + + } + + public void deleteBackendAPI(String backendId) { + // Delete back end + // https://${APIManagerHost}:${APIManagerPort}/api/portal/v1.3/apirepo/${BackEndAPIID} + logger.info("Deleting BackEnd API"); + URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/apirepo/").path(backendId).build() + .toUri(); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.DELETE, uri); + ResponseEntity apiEntity = restTemplate.exchange(requestEntity, String.class); + logger.info("Delete Back end API Response Code : {}", apiEntity.getStatusCodeValue()); + + } + + public String createBackend(String apiName, String orgId, String type, String swaggerURI) { + + URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/apirepo/importFromUrl").build().toUri(); + logger.info("Backend Creation URL : {}", uri.toString()); + MultiValueMap postParameters = new LinkedMultiValueMap<>(); + // Add query parameter + postParameters.add("organizationId", orgId); + if (apiName != null) { + postParameters.add("name", apiName); + } + + postParameters.add("type", type); + postParameters.add("url", swaggerURI); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + HttpEntity> request = new HttpEntity<>( + postParameters, headers); + ResponseEntity strResponse = restTemplate.exchange(uri, HttpMethod.POST, request, String.class); + logger.info("Create Backend API Response code: {}", strResponse.getStatusCodeValue()); + return strResponse.getBody(); + } + + // public String updateBackend(String userId, String response) { + // JsonNode jsonNode ; + // try { + // jsonNode = mapper.readTree(response); + // } catch (JsonProcessingException e) { + // throw new ServiceBrokerException("Internal Error"); + // } catch (IOException e) { + // throw new ServiceBrokerException("Internal Error"); + // } + // String id = jsonNode.findPath("id").asText(); + // ((ObjectNode) jsonNode).put("createdBy" , userId); + // URI uri = UriComponentsBuilder.fromUriString(url + + // "/api/portal/v1.3/apirepo/" + id).build().toUri(); + // HttpEntity jsonEntity = new HttpEntity(jsonNode, + // authHeader); + // ResponseEntity securityUpdate = restTemplate.exchange(uri, + // HttpMethod.PUT, jsonEntity, String.class); + // logger.info("Update Backend Response Code : {}", + // securityUpdate.getStatusCodeValue()); + // return id; + // } + + public String createFrontend(String backendAPIId, String orgId, String userId) { + String json = "{\"apiId\":\"" + backendAPIId + "\",\"organizationId\":\"" + orgId + "\"}"; + JsonNode jsonNode; + try { + jsonNode = mapper.readTree(json); + } catch (IOException e) { + throw new ServiceBrokerException("Internal Error"); + } + URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/proxies/").build().toUri(); + RequestEntity jsonEntity = new RequestEntity<>(jsonNode, HttpMethod.POST, uri); + ResponseEntity virtualizedAPIResponse = restTemplate.exchange(jsonEntity, String.class); + return virtualizedAPIResponse.getBody(); + } + + public void applySecurity(String frontEndAPIResponse, String bindingId, String vhost, String userId) + throws ServiceBrokerException { + JsonNode jsonNode; + try { + jsonNode = mapper.readTree(frontEndAPIResponse); + } catch (JsonProcessingException e) { + throw new ServiceBrokerException("Internal Error"); + } catch (IOException e) { + throw new ServiceBrokerException("Internal Error"); + } + ArrayNode devices = (ArrayNode) (jsonNode.findPath("securityProfiles")).get(0).get("devices"); + String virtualAPIId = jsonNode.findPath("id").asText(); + ((ObjectNode) jsonNode).put(CF_BINDING_ID, bindingId); + ((ObjectNode) jsonNode).put(VHOST, vhost); + //((ObjectNode) jsonNode).put("path", "/" + bindingId); + // ((ObjectNode) jsonNode).put("createdBy" , userId); + logger.debug("Security Device {}", devices.getClass().getName()); + devices.addPOJO(new APISecurity()); + URI uri = UriComponentsBuilder.fromUriString(url + "/api/portal/v1.3/proxies/" + virtualAPIId).build().toUri(); + RequestEntity jsonEntity = new RequestEntity<>(jsonNode, HttpMethod.PUT, uri); + ResponseEntity securityUpdate = restTemplate.exchange(jsonEntity, String.class); + logger.info("Apply Security Response Code : {}", securityUpdate.getStatusCodeValue()); + } } diff --git a/src/main/java/com/axway/apim/servicebroker/service/AxwayApplicationClient.java b/src/main/java/com/axway/apim/servicebroker/service/AxwayApplicationClient.java index e02cdc3..94fb11b 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/AxwayApplicationClient.java +++ b/src/main/java/com/axway/apim/servicebroker/service/AxwayApplicationClient.java @@ -28,16 +28,14 @@ public class AxwayApplicationClient implements Constants { public List getApplications(String orgId) { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/applications") - .queryParam("field", "orgid").queryParam("op", "eq").queryParam("value", orgId).build().toUri(); + .queryParam("field", "orgid").queryParam("op", "eq").queryParam("value", orgId).build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); logger.info("Calling API : {}", uri.toString()); ResponseEntity> userEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference>() { }); - - List apiUsers = userEntity.getBody(); - return apiUsers; + return userEntity.getBody(); } public void deleteApplications(List applications) { @@ -46,7 +44,7 @@ public void deleteApplications(List applications) { String appId = apiApplication.getId(); URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/applications/").path(appId) .build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.DELETE, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.DELETE, uri); ResponseEntity userEntity = restTemplate.exchange(requestEntity, String.class); logger.info("Delete Application Response Code : {} ", userEntity.getStatusCodeValue()); diff --git a/src/main/java/com/axway/apim/servicebroker/service/AxwayOrganzationClient.java b/src/main/java/com/axway/apim/servicebroker/service/AxwayOrganzationClient.java index c40f0dd..34e1086 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/AxwayOrganzationClient.java +++ b/src/main/java/com/axway/apim/servicebroker/service/AxwayOrganzationClient.java @@ -45,23 +45,22 @@ public String createOrganization(String orgName, String email, String serviceIns URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations").build().toUri(); RequestEntity jsonEntity = new RequestEntity(jsonNode, HttpMethod.POST,uri); ResponseEntity organization = restTemplate.exchange(jsonEntity, String.class); - logger.info("Create Organziation Response code : {}", organization.getStatusCodeValue()); + logger.info("Create Organization Response code : {}", organization.getStatusCodeValue()); try { - String orgId = JsonPath.parse(organization.getBody()).read("$.id", String.class); - return orgId; + return JsonPath.parse(organization.getBody()).read("$.id", String.class); } catch (PathNotFoundException e) { - logger.error("Unable to retreive Organization detail", e); + logger.error("Unable to retrieve Organization detail", e); return null; } } - public void deleteOrganization(String orgId) throws AxwayException { + public void deleteOrganization(String orgId){ URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations/").path(orgId).build() .toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.DELETE,uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.DELETE,uri); ResponseEntity userEntity = restTemplate.exchange(requestEntity, String.class); logger.info("Delete Organization Response Code : {} ", userEntity.getStatusCodeValue()); } @@ -70,15 +69,14 @@ public String getOrganizationId(String orgName) { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations") .queryParam("field", "name").queryParam("op", "eq").queryParam("value", orgName).build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); logger.info("Calling API : {}", uri.toString()); ResponseEntity organizationEntity = restTemplate.exchange(requestEntity, String.class); String responseBody = organizationEntity.getBody(); try { - String orgId = JsonPath.parse(responseBody).read("$.[0].id", String.class); - return orgId; + return JsonPath.parse(responseBody).read("$.[0].id", String.class); } catch (PathNotFoundException e) { - logger.error("Unable to retreive Organization detail", e); + logger.error("Unable to retrieve Organization detail", e); return null; } @@ -89,7 +87,7 @@ public void updateOrganization(APIOrganization apiOrganization) { // https://${APIManagerHost}:${APIManagerPort}/api/portal/v1.3/organizations URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations").build().toUri(); - RequestEntity jsonEntity = new RequestEntity(jsonNode, HttpMethod.PUT, uri); + RequestEntity jsonEntity = new RequestEntity<>(jsonNode, HttpMethod.PUT, uri); ResponseEntity organization = restTemplate.exchange(jsonEntity, String.class); logger.info(" Organziation Response code : {}", organization.getStatusCodeValue()); } @@ -98,7 +96,7 @@ public APIOrganization getOrganization(String orgId) { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations/").path(orgId).build() .toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); logger.info("Calling Get Organization API : {}", uri.toString()); ResponseEntity orgEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference() { @@ -109,7 +107,7 @@ public APIOrganization getOrganization(String orgId) { public List listOrganization() { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/organizations").build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); logger.info("Calling List Organization API : {}", uri.toString()); ResponseEntity> orgEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference>() { diff --git a/src/main/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImpl.java b/src/main/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImpl.java index 0ff03af..7e6a6fa 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImpl.java +++ b/src/main/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImpl.java @@ -1,11 +1,8 @@ package com.axway.apim.servicebroker.service; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; - +import com.axway.apim.servicebroker.exception.AxwayException; +import com.axway.apim.servicebroker.model.*; +import com.jayway.jsonpath.JsonPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -13,198 +10,194 @@ import org.springframework.cloud.servicebroker.exception.ServiceBrokerInvalidParametersException; import org.springframework.stereotype.Service; -import com.axway.apim.servicebroker.exception.AxwayException; -import com.axway.apim.servicebroker.model.APIApplication; -import com.axway.apim.servicebroker.model.APIOrganization; -import com.axway.apim.servicebroker.model.APIOrganizationAccess; -import com.axway.apim.servicebroker.model.APIUser; -import com.axway.apim.servicebroker.model.FrondendAPI; -import com.axway.apim.servicebroker.model.Type; -import com.jayway.jsonpath.JsonPath; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; @Service public class AxwayServiceBrokerImpl implements AxwayServiceBroker, Constants { - private static final Logger logger = LoggerFactory.getLogger(AxwayServiceBrokerImpl.class.getName()); - - @Autowired - private AxwayOrganzationClient axwayOrganzationClient; - - @Autowired - private AxwayUserClient axwayUserClient; - - @Autowired - private AxwayApplicationClient axwayApplicationClient; - - @Autowired - private AxwayAPIClient axwayAPIClient; - - @Override - public void importAPI(Map parameters, String appRouteURL, String bindingId, - String serviceInstanceId, String email) - throws ServiceBrokerInvalidParametersException, ServiceBrokerException { - logger.debug("Creating API Proxy on API manager"); - logger.debug("Parameters {}", parameters); - - if (parameters == null) { - throw new ServiceBrokerInvalidParametersException( - "Custom parameters are required to add API on API Manager"); - } - - String type = (String) parameters.get("type"); - String apiName = (String) parameters.get("apiname"); - // String swaggerURL = "https://" + appRouteURL +"/v2/api-docs"; - String apiURI = (String) parameters.get("uri"); - - // logger.debug("Organziation name {}", orgName); - logger.debug("API Name{}", apiName); - logger.debug("Swagger URI {}", apiURI); - - if (type == null) { - throw new ServiceBrokerInvalidParametersException("Custom parameter type is required"); - } - AtomicReference enumType = new AtomicReference<>(); - - try{ - enumType.set(Type.valueOf(type.toUpperCase())); - }catch (IllegalArgumentException e) { - throw new ServiceBrokerInvalidParametersException("Custom parameter type value can only be swagger or wsdl"); - } - - if (enumType.get().compareTo(Type.SWAGGER) == 0) { - type = "swagger"; - } else if (enumType.get().compareTo(Type.WSDL) == 0) { - type = "wsdl"; - } - - if (apiURI == null) { - throw new ServiceBrokerInvalidParametersException("Custom parameter uri is required"); - } - - if (!apiURI.startsWith("http")) { - apiURI = "https://" + appRouteURL + apiURI; - } - APIUser apiUser = getOrgId(email, serviceInstanceId); - String orgId = apiUser.getOrganizationId(); - String userId = apiUser.getId(); - logger.info("Org id from API Manager : {}" , orgId); - String response = axwayAPIClient.createBackend(apiName, orgId, type, apiURI); - String backendAPIId = JsonPath.parse(response).read("$.id", String.class); - response = axwayAPIClient.createFrontend(backendAPIId, orgId, userId); - axwayAPIClient.applySecurity(response, bindingId, appRouteURL, userId); - - } - - @Override - public boolean deleteAPI(String bindingId, String serviceInstanceId, String email) throws AxwayException { - - logger.info("Deleting API Proxy on API manager"); - String orgId = getOrgId(email, serviceInstanceId).getOrganizationId(); - - // Get the API based on the name and apply the filters like unpublished - String responseBody = axwayAPIClient.listAPIs(); - List> apis = JsonPath.parse(responseBody).read( - "$.*[?(@.organizationId =='" + orgId + "' && @.cfBindingId =='" + bindingId + "' && @.state =='published')]"); - logger.info("Published APIs {} :" ,apis); - - if (!apis.isEmpty()) { - throw new AxwayException("Unbind is not allowed as API is in published state"); - - } else { - apis = JsonPath.parse(responseBody).read( - "$.*[?(@.organizationId =='" + orgId + "' && @.cfBindingId =='" + bindingId + "' && @.state =='unpublished')]"); - logger.info("unpublished APIs {} :" ,apis); - if (!apis.isEmpty()) { - Map apiDefinition = apis.get(0); - String frondEndApiId = (String) apiDefinition.get("id"); - String backendId = (String) apiDefinition.get("apiId"); - axwayAPIClient.deleteFrondendAPI(frondEndApiId); - axwayAPIClient.deleteBackendAPI(backendId); - } else { - return false; - } - } - return true; - } - - @Override - public boolean createOrgAndUser(String orgName, String email, String serviceInstanceId) throws AxwayException { - - String orgId = axwayOrganzationClient.getOrganizationId(orgName); - APIUser apiUser = axwayUserClient.getUser(email); - if (apiUser != null && orgId != null) { - return false; - } - - // Check whether the user is already associated with some other organization - if( apiUser.getOrganizationId() != null){ - throw new AxwayException("A user with the supplied login name already exists"); - } - - orgId = axwayOrganzationClient.createOrganization(orgName, email, serviceInstanceId); - String userId = axwayUserClient.createUser(orgId, email); - axwayUserClient.resetPassword(userId); - return true; - } - - @Override - public boolean deleteOrgAppAndUser(String email, String serviceInstanceId) throws AxwayException { - logger.info("Deleting Subscription"); - - List frondendAPIs = new ArrayList<>(); - String orgId = null; - String userId = null; - List apiOrganizations = axwayOrganzationClient.listOrganization(); - Optional organization = apiOrganizations.stream() - .filter(apiOrganization -> (apiOrganization.getService_instance_id() != null - && apiOrganization.getService_instance_id().equalsIgnoreCase(serviceInstanceId))) - .findAny(); - if (organization.isPresent()) { - orgId = organization.get().getId(); - APIUser apiUser = axwayUserClient.getUserByOrgId(orgId); - userId = apiUser.getId(); - } else { - return false; - } - List apiOrganizationAccesses = axwayAPIClient.listAPIs(orgId); - - for (APIOrganizationAccess apiOrganizationAccess : apiOrganizationAccesses) { - String apiId = apiOrganizationAccess.getApiId(); - FrondendAPI frondendAPI = axwayAPIClient.getAPI(apiId); - if (frondendAPI.getState().equals(PUBLISHED)) { - logger.info("Published APIs are available under the organization"); - throw new AxwayException( - "Can't delete Organization as it has published API, Please unpublish the API from API Manager"); - } - frondendAPIs.add(frondendAPI); - } - - for (FrondendAPI frondendAPI : frondendAPIs) { - String frondEndApiId = frondendAPI.getId(); - String backendId = frondendAPI.getApiId(); - - axwayAPIClient.deleteFrondendAPI(frondEndApiId); - axwayAPIClient.deleteBackendAPI(backendId); - } - List applications = axwayApplicationClient.getApplications(orgId); - axwayApplicationClient.deleteApplications(applications); - axwayUserClient.deleteUser(userId); - axwayOrganzationClient.deleteOrganization(orgId); - return true; - } - - private APIUser getOrgId(String email, String serviceInstanceId) throws ServiceBrokerException { - - APIUser apiUser = axwayUserClient.getUser(email); - if (apiUser == null) { - throw new ServiceBrokerException("Access Denied : User is not exists on API Manager"); - } - String orgId = apiUser.getOrganizationId(); - logger.info("Org id :{}", orgId); - APIOrganization apiOrganization = axwayOrganzationClient.getOrganization(orgId); - if (!serviceInstanceId.equals(apiOrganization.getService_instance_id())) { - throw new ServiceBrokerException("Internal Error : Service instance id mismatch"); - } - return apiUser; - } + private static final Logger logger = LoggerFactory.getLogger(AxwayServiceBrokerImpl.class.getName()); + + @Autowired + private AxwayOrganzationClient axwayOrganzationClient; + + @Autowired + private AxwayUserClient axwayUserClient; + + @Autowired + private AxwayApplicationClient axwayApplicationClient; + + @Autowired + private AxwayAPIClient axwayAPIClient; + + @Override + public void importAPI(Map parameters, String appRouteURL, String bindingId, + String serviceInstanceId, String email) + throws ServiceBrokerInvalidParametersException, ServiceBrokerException { + logger.debug("Creating API Proxy on API manager"); + logger.debug("Parameters {}", parameters); + + if (parameters == null) { + throw new ServiceBrokerInvalidParametersException( + "Custom parameters are required to add API on API Manager"); + } + + String type = (String) parameters.get("type"); + String apiName = (String) parameters.get("apiname"); + // String swaggerURL = "https://" + appRouteURL +"/v2/api-docs"; + String apiURI = (String) parameters.get("uri"); + + // logger.debug("Organziation name {}", orgName); + logger.debug("API Name{}", apiName); + logger.debug("Swagger URI {}", apiURI); + + if (type == null) { + throw new ServiceBrokerInvalidParametersException("Custom parameter type is required"); + } + AtomicReference enumType = new AtomicReference<>(); + + try { + enumType.set(Type.valueOf(type.toUpperCase())); + } catch (IllegalArgumentException e) { + throw new ServiceBrokerInvalidParametersException("Custom parameter type value can only be swagger or wsdl"); + } + + if (enumType.get().compareTo(Type.SWAGGER) == 0) { + type = "swagger"; + } else if (enumType.get().compareTo(Type.WSDL) == 0) { + type = "wsdl"; + } + + if (apiURI == null) { + throw new ServiceBrokerInvalidParametersException("Custom parameter uri is required"); + } + + if (!apiURI.startsWith("http")) { + apiURI = "https://" + appRouteURL + apiURI; + } + APIUser apiUser = getOrgId(email, serviceInstanceId); + String orgId = apiUser.getOrganizationId(); + String userId = apiUser.getId(); + logger.info("Org id from API Manager : {}", orgId); + String response = axwayAPIClient.createBackend(apiName, orgId, type, apiURI); + String backendAPIId = JsonPath.parse(response).read("$.id", String.class); + response = axwayAPIClient.createFrontend(backendAPIId, orgId, userId); + axwayAPIClient.applySecurity(response, bindingId, appRouteURL, userId); + + } + + @Override + public boolean deleteAPI(String bindingId, String serviceInstanceId, String email) throws AxwayException { + + logger.info("Deleting API Proxy on API manager"); + String orgId = getOrgId(email, serviceInstanceId).getOrganizationId(); + + // Get the API based on the name and apply the filters like unpublished + String responseBody = axwayAPIClient.listAPIs(); + List> apis = JsonPath.parse(responseBody).read( + "$.*[?(@.organizationId =='" + orgId + "' && @.cfBindingId =='" + bindingId + "' && @.state =='published')]"); + logger.info("Published APIs {} :", apis); + + if (!apis.isEmpty()) { + throw new AxwayException("Unbind is not allowed as API is in published state"); + + } else { + apis = JsonPath.parse(responseBody).read( + "$.*[?(@.organizationId =='" + orgId + "' && @.cfBindingId =='" + bindingId + "' && @.state =='unpublished')]"); + logger.info("unpublished APIs {} :", apis); + if (!apis.isEmpty()) { + Map apiDefinition = apis.get(0); + String frondEndApiId = (String) apiDefinition.get("id"); + String backendId = (String) apiDefinition.get("apiId"); + axwayAPIClient.deleteFrontendAPI(frondEndApiId); + axwayAPIClient.deleteBackendAPI(backendId); + } else { + return false; + } + } + return true; + } + + @Override + public boolean createOrgAndUser(String orgName, String email, String serviceInstanceId) throws AxwayException { + + String orgId = axwayOrganzationClient.getOrganizationId(orgName); + APIUser apiUser = axwayUserClient.getUser(email); + if (apiUser != null && orgId != null) { + return false; + } + + // Check whether the user is already associated with some other organization + if (apiUser != null && apiUser.getOrganizationId() != null) { + throw new AxwayException("A user with the supplied login name already exists"); + } + + orgId = axwayOrganzationClient.createOrganization(orgName, email, serviceInstanceId); + String userId = axwayUserClient.createUser(orgId, email); + axwayUserClient.resetPassword(userId); + return true; + } + + @Override + public boolean deleteOrgAppAndUser(String email, String serviceInstanceId) throws AxwayException { + logger.info("Deleting Subscription"); + + List frontendAPIs = new ArrayList<>(); + String orgId; + String userId; + List apiOrganizations = axwayOrganzationClient.listOrganization(); + Optional organization = apiOrganizations.stream() + .filter(apiOrganization -> (apiOrganization.getService_instance_id() != null + && apiOrganization.getService_instance_id().equalsIgnoreCase(serviceInstanceId))) + .findAny(); + if (organization.isPresent()) { + orgId = organization.get().getId(); + APIUser apiUser = axwayUserClient.getUserByOrgId(orgId); + userId = apiUser.getId(); + } else { + return false; + } + List apiOrganizationAccesses = axwayAPIClient.listAPIs(orgId); + + for (APIOrganizationAccess apiOrganizationAccess : apiOrganizationAccesses) { + String apiId = apiOrganizationAccess.getApiId(); + FrontendAPI frontendAPI = axwayAPIClient.getAPI(apiId); + if (frontendAPI.getState().equals(PUBLISHED)) { + logger.info("Published APIs are available under the organization"); + throw new AxwayException( + "Can't delete Organization as it has published API, Please unpublish the API from API Manager"); + } + frontendAPIs.add(frontendAPI); + } + + for (FrontendAPI frontendAPI : frontendAPIs) { + String frondEndApiId = frontendAPI.getId(); + String backendId = frontendAPI.getApiId(); + axwayAPIClient.deleteFrontendAPI(frondEndApiId); + axwayAPIClient.deleteBackendAPI(backendId); + } + List applications = axwayApplicationClient.getApplications(orgId); + axwayApplicationClient.deleteApplications(applications); + axwayUserClient.deleteUser(userId); + axwayOrganzationClient.deleteOrganization(orgId); + return true; + } + + private APIUser getOrgId(String email, String serviceInstanceId) throws ServiceBrokerException { + + APIUser apiUser = axwayUserClient.getUser(email); + if (apiUser == null) { + throw new ServiceBrokerException("Access Denied : User is not exists on API Manager"); + } + String orgId = apiUser.getOrganizationId(); + logger.info("Org id :{}", orgId); + APIOrganization apiOrganization = axwayOrganzationClient.getOrganization(orgId); + if (!serviceInstanceId.equals(apiOrganization.getService_instance_id())) { + throw new ServiceBrokerException("Internal Error : Service instance id mismatch"); + } + return apiUser; + } } diff --git a/src/main/java/com/axway/apim/servicebroker/service/AxwayUserClient.java b/src/main/java/com/axway/apim/servicebroker/service/AxwayUserClient.java index 3987787..badd1c8 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/AxwayUserClient.java +++ b/src/main/java/com/axway/apim/servicebroker/service/AxwayUserClient.java @@ -48,14 +48,14 @@ public APIUser getUser(String username) { private APIUser getUser(URI uri){ logger.info("Calling API : {}", uri.toString()); - RequestEntity requestEntity = new RequestEntity(HttpMethod.GET, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.GET, uri); ResponseEntity> userEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference>() { }); List apiUsers = userEntity.getBody(); int statusCode = userEntity.getStatusCodeValue(); - logger.info("Response Code for get User : {}", userEntity.getStatusCodeValue()); + logger.info("Response Code for get User : {}", statusCode); if (apiUsers.isEmpty()) { return null; } @@ -78,7 +78,7 @@ public String createUser(String organizationId, String email) throws AxwayExcept JsonNode jsonNode = mapper.convertValue(apiUser, JsonNode.class); // https://${APIManagerHost}:${APIManagerPort}/api/portal/v1.3/organizations URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/users").build().toUri(); - RequestEntity requestEntity = new RequestEntity(jsonNode, HttpMethod.POST, uri); + RequestEntity requestEntity = new RequestEntity<>(jsonNode, HttpMethod.POST, uri); ResponseEntity user = restTemplate.exchange(requestEntity, String.class); int httpStatusCode = user.getStatusCodeValue(); logger.info("Create User Response code : {}", httpStatusCode); @@ -86,24 +86,21 @@ public String createUser(String organizationId, String email) throws AxwayExcept throw new AxwayException("A user with the supplied login name already exists"); } - String userId = JsonPath.parse(user.getBody()).read("$.id", String.class); - return userId; - + return JsonPath.parse(user.getBody()).read("$.id", String.class); } public void resetPassword(String userId) { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/users/").path(userId) .path("/resetpassword").build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.PUT, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.PUT, uri); restTemplate.exchange(uri, HttpMethod.PUT, requestEntity, String.class); - } - public void deleteUser(String id) throws AxwayException { + public void deleteUser(String id) { URI uri = UriComponentsBuilder.fromUriString(url).path(API_BASEPATH).path("/users/").path(id).build().toUri(); - RequestEntity requestEntity = new RequestEntity(HttpMethod.DELETE, uri); + RequestEntity requestEntity = new RequestEntity<>(HttpMethod.DELETE, uri); ResponseEntity userEntity = restTemplate.exchange(requestEntity, String.class); logger.info("Delete User Response Code : {} ", userEntity.getStatusCodeValue()); } diff --git a/src/main/java/com/axway/apim/servicebroker/service/Constants.java b/src/main/java/com/axway/apim/servicebroker/service/Constants.java index 21e5849..156e15d 100644 --- a/src/main/java/com/axway/apim/servicebroker/service/Constants.java +++ b/src/main/java/com/axway/apim/servicebroker/service/Constants.java @@ -1,11 +1,11 @@ package com.axway.apim.servicebroker.service; public interface Constants { - - public String API_BASEPATH = "/api/portal/v1.3/"; - public String DOT = "."; - public String PUBLISHED = "published"; - public String CF_BINDING_ID= "cfBindingId"; - public String VHOST = "vhost"; + String VERSION = "1.1.8"; + String API_BASEPATH = "/api/portal/v1.3/"; + String DOT = "."; + String PUBLISHED = "published"; + String CF_BINDING_ID= "cfBindingId"; + String VHOST = "vhost"; } diff --git a/src/main/java/com/axway/apim/servicebroker/service/VersionController.java b/src/main/java/com/axway/apim/servicebroker/service/VersionController.java new file mode 100644 index 0000000..dc2674d --- /dev/null +++ b/src/main/java/com/axway/apim/servicebroker/service/VersionController.java @@ -0,0 +1,14 @@ +package com.axway.apim.servicebroker.service; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class VersionController implements Constants { + + @RequestMapping(value = "/version" , method = RequestMethod.GET, produces = { "application/json" }) + public String getVersion() { + return "{\"version\" :" + Constants.VERSION + "}"; + } +} diff --git a/src/main/java/com/axway/apim/servicebroker/util/Util.java b/src/main/java/com/axway/apim/servicebroker/util/Util.java index ef4bbfc..a5caf3c 100644 --- a/src/main/java/com/axway/apim/servicebroker/util/Util.java +++ b/src/main/java/com/axway/apim/servicebroker/util/Util.java @@ -3,26 +3,23 @@ import org.apache.commons.validator.routines.EmailValidator; import org.springframework.cloud.servicebroker.exception.ServiceBrokerInvalidParametersException; -public class Util { - - - - public void isValidEmail(String email) throws ServiceBrokerInvalidParametersException{ - - if(!EmailValidator.getInstance().isValid(email)){ - throw new ServiceBrokerInvalidParametersException("Username should be a valid email address"); - } - } - - public String getNameFromEmail(String email){ - - if(EmailValidator.getInstance().isValid(email)){ - return email.split("@")[0]; - } - - return null; - - } - - +public class Util { + + + public void isValidEmail(String email) throws ServiceBrokerInvalidParametersException { + + if (!EmailValidator.getInstance().isValid(email)) { + throw new ServiceBrokerInvalidParametersException("Username should be a valid email address"); + } + } + + public String getNameFromEmail(String email) { + + if (EmailValidator.getInstance().isValid(email)) { + return email.split("@")[0]; + } + return null; + } + + } diff --git a/src/test/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImplTest.java b/src/test/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImplTest.java index 53db287..56b9905 100644 --- a/src/test/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImplTest.java +++ b/src/test/java/com/axway/apim/servicebroker/service/AxwayServiceBrokerImplTest.java @@ -1,12 +1,6 @@ package com.axway.apim.servicebroker.service; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - +import com.axway.apim.servicebroker.exception.AxwayException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,65 +10,69 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import com.axway.apim.servicebroker.exception.AxwayException; -import com.axway.apim.servicebroker.service.AxwayServiceBroker; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; @SpringBootTest @RunWith(SpringRunner.class) @AutoConfigureWireMock(port = 8081) -@TestPropertySource(properties = { "axway_apimanager_url=http://localhost:8081" }) +@TestPropertySource(properties = {"axway_apimanager_url=http://localhost:8081"}) public class AxwayServiceBrokerImplTest { - - private String email = "anna@axway.com"; - private String serviceInstanceId = "ED01F448-40C7-4A9D-93D0-51E7D4E93CA1"; - - @Autowired - private AxwayServiceBroker axwayServiceBroker; - @Test - public void shouldImportAPI() { - - Map parameters = new HashMap<>(); - - parameters.put("type", "swagger"); - parameters.put("apiname", "pcftest"); - parameters.put("uri","http://petstore.swagger.io/v2/swagger.json"); - - - axwayServiceBroker.importAPI(parameters,null,"123", serviceInstanceId, email); - - } - - @Test - public void importAPIWithoutParamaters() { - - - try { - axwayServiceBroker.importAPI(null,null,"123", serviceInstanceId, email); - fail("importAPIWithoutParamaters failed"); - } catch (ServiceBrokerInvalidParametersException e) { - assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameters are required to add API on API Manager"); - } - - } - - @Test - public void importAPIWithoutType() { - - Map parameters = new HashMap<>(); - - parameters.put("apiname", "pcftest"); - parameters.put("uri","http://petstore.swagger.io/v2/swagger.json"); - - - try { - axwayServiceBroker.importAPI(parameters,null,"123", serviceInstanceId, email); - fail("importAPIWithoutType failed"); - } catch (ServiceBrokerInvalidParametersException e) { - assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameter type is required"); - } - - } + private String email = "anna@axway.com"; + private String serviceInstanceId = "ED01F448-40C7-4A9D-93D0-51E7D4E93CA1"; + + @Autowired + private AxwayServiceBroker axwayServiceBroker; + + @Test + public void shouldImportAPI() { + + Map parameters = new HashMap<>(); + + parameters.put("type", "swagger"); + parameters.put("apiname", "pcftest"); + parameters.put("uri", "http://petstore.swagger.io/v2/swagger.json"); + + + axwayServiceBroker.importAPI(parameters, null, "123", serviceInstanceId, email); + + } + + @Test + public void importAPIWithoutParamaters() { + + + try { + axwayServiceBroker.importAPI(null, null, "123", serviceInstanceId, email); + fail("importAPIWithoutParamaters failed"); + } catch (ServiceBrokerInvalidParametersException e) { + assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameters are required to add API on API Manager"); + } + + } + + @Test + public void importAPIWithoutType() { + + Map parameters = new HashMap<>(); + + parameters.put("apiname", "pcftest"); + parameters.put("uri", "http://petstore.swagger.io/v2/swagger.json"); + + + try { + axwayServiceBroker.importAPI(parameters, null, "123", serviceInstanceId, email); + fail("importAPIWithoutType failed"); + } catch (ServiceBrokerInvalidParametersException e) { + assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameter type is required"); + } + + } /*@Test public void importAPIWithoutAPIName() { @@ -93,65 +91,78 @@ public void importAPIWithoutAPIName() { } }*/ - - - @Test - public void importAPIWithoutSwaggerURL() { - - Map parameters = new HashMap<>(); - - parameters.put("apiname", "pcftest"); - parameters.put("type", "swagger"); - - - try { - axwayServiceBroker.importAPI(parameters,null,"123", serviceInstanceId, email); - fail("importAPIWithoutSwaggerURL failed"); - } catch (ServiceBrokerInvalidParametersException e) { - assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameter uri is required"); - } - - } - - - @Test - public void apiNotAvailableToDelete() { - - - try { - boolean status = axwayServiceBroker.deleteAPI("000000-0d6c-4ae4-9880-8c28f1c9bf48", serviceInstanceId, email); - assertThat(status); - } catch (IOException e) { - fail("apiNotAvailableToDelete failed"); - } - - } - - @Test - public void doNotDeletePubllishedAPI() { - - - - try { - axwayServiceBroker.deleteAPI("78a38296-bded-44a9-9329-f2cd0a92e962", serviceInstanceId, email); - fail("apiNotAvailableToDelete failed"); - } catch (IOException e) { - assertThat(e).isInstanceOf(AxwayException.class).hasMessage("Unbind is not allowed as API is in published state"); - } - - } - - @Test - public void shouldDeleteAPI() { - - try { - axwayServiceBroker.deleteAPI("4be7e206-0d6c-4ae4-9880-8c28f1c9bf48", serviceInstanceId, email); - } catch (IOException e) { - fail("Test failed"); - } + @Test + public void importAPIWithoutSwaggerURL() { + + Map parameters = new HashMap<>(); + + parameters.put("apiname", "pcftest"); + parameters.put("type", "swagger"); + + + try { + axwayServiceBroker.importAPI(parameters, null, "123", serviceInstanceId, email); + fail("importAPIWithoutSwaggerURL failed"); + } catch (ServiceBrokerInvalidParametersException e) { + assertThat(e).isInstanceOf(ServiceBrokerInvalidParametersException.class).hasMessage("Custom parameter uri is required"); + } + + } + + + @Test + public void apiNotAvailableToDelete() { + try { + boolean status = axwayServiceBroker.deleteAPI("000000-0d6c-4ae4-9880-8c28f1c9bf48", serviceInstanceId, email); + assertThat(status); + } catch (IOException e) { + fail("apiNotAvailableToDelete failed"); + } + + } + + @Test + public void doNotDeletePublishedAPI() { + try { + axwayServiceBroker.deleteAPI("78a38296-bded-44a9-9329-f2cd0a92e962", serviceInstanceId, email); + fail("apiNotAvailableToDelete failed"); + } catch (IOException e) { + assertThat(e).isInstanceOf(AxwayException.class).hasMessage("Unbind is not allowed as API is in published state"); + } + + } + + + @Test + public void shouldDeleteAPI() { + + + try { + axwayServiceBroker.deleteAPI("4be7e206-0d6c-4ae4-9880-8c28f1c9bf48", serviceInstanceId, email); + } catch (IOException e) { + fail("Test failed"); + } + + } + + @Test + public void createOrgAppAndUser(){ + try { + axwayServiceBroker.createOrgAndUser("Axway", email, serviceInstanceId ); + } catch (AxwayException e) { + fail("Test failed"); + } + } - } + @Test + public void deleteOrgAppAndUser(){ + try { + axwayServiceBroker.deleteOrgAppAndUser(email, serviceInstanceId ); + } catch (AxwayException e) { + fail("Test failed"); + } + } } diff --git a/src/test/resources/__files/frontendAPI_response.json b/src/test/resources/__files/frontendAPI_response.json new file mode 100644 index 0000000..78a3258 --- /dev/null +++ b/src/test/resources/__files/frontendAPI_response.json @@ -0,0 +1,126 @@ +{ + "id": "066f113d-1f80-4e29-b210-c54d72dc", + "organizationId": "9aef95ec-8167-46ab-8270-19cf1582c03f", + "apiId": "8530b775-66bb-4ec9-80c1-0178dc2f7974", + "name": "Test", + "version": "1.0", + "apiRoutingKey": null, + "vhost": null, + "path": "/healthcheck", + "descriptionType": "original", + "descriptionManual": null, + "descriptionMarkdown": null, + "descriptionUrl": null, + "summary": null, + "retired": false, + "expired": false, + "image": "/api/portal/v1.3/discovery/swagger/apis/066f113d-1f80-4e29-b210-c54d72dc/image", + "retirementDate": 0, + "deprecated": false, + "state": "unpublished", + "createdOn": 1555099058170, + "createdBy": "f7289d70-c71b-4c6b-a2bb-9461f93b91aa", + "corsProfiles": [ + { + "name": "_default", + "isDefault": true, + "origins": [ + "*" + ], + "allowedHeaders": [], + "exposedHeaders": [ + "X-CorrelationID" + ], + "supportCredentials": false, + "maxAgeSeconds": 0 + }, + { + "name": "New CORS Profile", + "isDefault": false, + "origins": [ + "*" + ], + "allowedHeaders": [ + "origin", + "authorization", + "accept", + "content-type", + "x-requested-with" + ], + "exposedHeaders": [], + "supportCredentials": true, + "maxAgeSeconds": 0 + } + ], + "securityProfiles": [ + { + "name": "_default", + "isDefault": true, + "devices": [ + { + "name": "OAuth", + "type": "oauth", + "order": 1, + "properties": { + "tokenStore": "", + "accessTokenLocation": "HEADER", + "authorizationHeaderPrefix": "Bearer", + "accessTokenLocationQueryString": "", + "scopesMustMatch": "Any", + "scopes": "resource.WRITE, resource.READ", + "removeCredentialsOnSuccess": "true", + "implicitGrantEnabled": "true", + "implicitGrantLoginEndpointUrl": "https://localhost:8089/api/oauth/authorize", + "implicitGrantLoginTokenName": "access_token", + "authCodeGrantTypeEnabled": "true", + "authCodeGrantTypeRequestEndpointUrl": "https://localhost:8089/api/oauth/authorize", + "authCodeGrantTypeRequestClientIdName": "client_id", + "authCodeGrantTypeRequestSecretName": "client_secret", + "authCodeGrantTypeTokenEndpointUrl": "https://localhost:8089/api/oauth/token", + "authCodeGrantTypeTokenEndpointTokenName": "access_code" + } + } + ] + } + ], + "authenticationProfiles": [ + { + "name": "_default", + "isDefault": true, + "parameters": { + "username": "rathna", + "password": "rathna" + }, + "type": "http_basic" + } + ], + "inboundProfiles": { + "_default": { + "securityProfile": "_default", + "corsProfile": "_default", + "monitorAPI": true, + "monitorSubject": "authentication.subject.id" + } + }, + "outboundProfiles": { + "_default": { + "authenticationProfile": "_default", + "routeType": "proxy", + "requestPolicy": null, + "responsePolicy": null, + "routePolicy": null, + "faultHandlerPolicy": null, + "apiId": "8530b775-66bb-4ec9-80c1-0178dc2f7974", + "apiMethodId": null, + "parameters": [] + } + }, + "serviceProfiles": { + "_default": { + "apiId": "8530b775-66bb-4ec9-80c1-0178dc2f7974", + "basePath": "http://localhost:8080" + } + }, + "caCerts": [], + "tags": {} +} \ No newline at end of file diff --git a/src/test/resources/__files/listApplicationByOrgId_response.json b/src/test/resources/__files/listApplicationByOrgId_response.json index 336f89e..71e4107 100644 --- a/src/test/resources/__files/listApplicationByOrgId_response.json +++ b/src/test/resources/__files/listApplicationByOrgId_response.json @@ -14,5 +14,19 @@ "enabled": true, "image": "/api/portal/v1.3/applications/cebcfb86-ba41-487e-94ff-bec3285acd7d/image", "state": "approved" + }, + { + "id": "678cd41f-9ba3-4451-a09a-48df36207616", + "name": "Oauth Test", + "description": null, + "organizationId": "9aef95ec-8167-46ab-8270-19cf1582c03f", + "phone": null, + "email": null, + "createdBy": "f7289d70-c71b-4c6b-a2bb-9461f93b91aa", + "managedBy": [], + "createdOn": 1557428068824, + "enabled": true, + "image": null, + "state": "approved" } -] +] \ No newline at end of file diff --git a/src/test/resources/__files/listUsersByOrgId_response.json b/src/test/resources/__files/listUsersByOrgId_response.json new file mode 100644 index 0000000..fcca479 --- /dev/null +++ b/src/test/resources/__files/listUsersByOrgId_response.json @@ -0,0 +1,20 @@ +[ + { + "id": "3a63f068-3045-473f-91df-745856e70867", + "organizationId": "9aef95ec-8167-46ab-8270-19cf1582c03f", + "name": "rathna1", + "description": null, + "loginName": "rathna1", + "email": "rathna1@gmail.com", + "phone": "21323434", + "mobile": null, + "role": "oadmin", + "image": null, + "enabled": true, + "createdOn": 1548450891490, + "state": "approved", + "type": "internal", + "authAttrs": null, + "dn": "cn=rathna1,o=Axway,ou=organizations,ou=APIPortal" + } +] \ No newline at end of file diff --git a/src/test/resources/mappings/delete_application.json b/src/test/resources/mappings/delete_application.json new file mode 100644 index 0000000..18f07c2 --- /dev/null +++ b/src/test/resources/mappings/delete_application.json @@ -0,0 +1,9 @@ +{ + "request": { + "method": "DELETE", + "urlPathPattern": "/api/portal/v1.3/applications/[0-9a-z-]+" + }, + "response": { + "status": 204 + } +} \ No newline at end of file diff --git a/src/test/resources/mappings/delete_organization.json b/src/test/resources/mappings/delete_organization.json new file mode 100644 index 0000000..286250f --- /dev/null +++ b/src/test/resources/mappings/delete_organization.json @@ -0,0 +1,9 @@ +{ + "request": { + "method": "DELETE", + "urlPathPattern": "/api/portal/v1.3/organizations/[0-9a-z-]+" + }, + "response": { + "status": 204 + } +} \ No newline at end of file diff --git a/src/test/resources/mappings/delete_user.json b/src/test/resources/mappings/delete_user.json new file mode 100644 index 0000000..5084e29 --- /dev/null +++ b/src/test/resources/mappings/delete_user.json @@ -0,0 +1,9 @@ +{ + "request": { + "method": "DELETE", + "urlPathPattern": "/api/portal/v1.3/users/[0-9a-z-]+" + }, + "response": { + "status": 204 + } +} \ No newline at end of file diff --git a/src/test/resources/mappings/getFrontendAPI.json b/src/test/resources/mappings/getFrontendAPI.json new file mode 100644 index 0000000..9b7db4f --- /dev/null +++ b/src/test/resources/mappings/getFrontendAPI.json @@ -0,0 +1,13 @@ +{ + "request": { + "method": "GET", + "urlPathPattern": "/api/portal/v1.3/proxies/[0-9a-z-]+" + }, + "response": { + "status": 200, + "bodyFileName": "frontendAPI_response.json", + "headers": { + "Content-Type": "application/json" + } + } +} \ No newline at end of file diff --git a/src/test/resources/mappings/listUsersByOrgId.json b/src/test/resources/mappings/listUsersByOrgId.json new file mode 100644 index 0000000..3be7beb --- /dev/null +++ b/src/test/resources/mappings/listUsersByOrgId.json @@ -0,0 +1,13 @@ +{ + "request": { + "method": "GET", + "url": "/api/portal/v1.3/users?field=orgid&op=eq&value=9aef95ec-8167-46ab-8270-19cf1582c03f" + }, + "response": { + "status": 200, + "bodyFileName": "listUsersByOrgId_response.json", + "headers": { + "Content-Type": "application/json" + } + } +} \ No newline at end of file diff --git a/src/test/resources/mappings/list_organization.json b/src/test/resources/mappings/list_organization.json new file mode 100644 index 0000000..4d78baa --- /dev/null +++ b/src/test/resources/mappings/list_organization.json @@ -0,0 +1,13 @@ +{ + "request": { + "method": "GET", + "url": "/api/portal/v1.3/organizations" + }, + "response": { + "status": 200, + "bodyFileName": "organization_response.json", + "headers": { + "Content-Type": "application/json" + } + } +} \ No newline at end of file