From: PatrikBuhr Date: Fri, 7 Feb 2020 11:59:09 +0000 (+0100) Subject: Updates of the policy agent NBI X-Git-Tag: 2.0.0~168^2 X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=commitdiff_plain;h=b40e1b476b25dfdd5ad3ba235ab085d6d4087be3;p=nonrtric.git Updates of the policy agent NBI Minor changes. Removed an unused interface. Change-Id: I30166c27546dc584d8ee4675af3d807e1175282f Issue-ID: NONRTRIC-107 Signed-off-by: PatrikBuhr --- diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java index c01c7c65..20a0c3f5 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/controller/PolicyController.java @@ -81,7 +81,7 @@ public class PolicyController { */ @ApiOperation(value = "Gets the policy types from Near Realtime-RIC") @GetMapping(POLICY_TYPES_METHOD) - @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD}) + @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD }) public ResponseEntity getAllPolicyTypes(HttpServletResponse response) { logger.debug("getAllPolicyTypes"); return this.policyAgentApi.getAllPolicyTypes(); @@ -89,7 +89,7 @@ public class PolicyController { @ApiOperation(value = "Returns the policy instances for the given policy type.") @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME) - @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD}) + @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD }) public ResponseEntity getPolicyInstances(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString) { logger.debug("getPolicyInstances {}", policyTypeIdString); return this.policyAgentApi.getPolicyInstancesForType(policyTypeIdString); @@ -97,41 +97,41 @@ public class PolicyController { @ApiOperation(value = "Returns a policy instance of a type") @GetMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME - + "}") - @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD}) - public ResponseEntity getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString, - @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) { + + "}") + @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD }) + public ResponseEntity getPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString, + @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) { logger.debug("getPolicyInstance {}:{}", policyTypeIdString, policyInstanceId); return this.policyAgentApi.getPolicyInstance(policyInstanceId); } @ApiOperation(value = "Creates the policy instances for the given policy type.") @PutMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" + POLICY_INSTANCE_ID_NAME - + "}") - @Secured({DashboardConstants.ROLE_ADMIN}) + + "}") + @Secured({ DashboardConstants.ROLE_ADMIN }) public ResponseEntity putPolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString, - @RequestParam(name = "ric", required = true) String ric, - @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) { + @RequestParam(name = "ric", required = true) String ric, + @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId, @RequestBody String instance) { logger.debug("putPolicyInstance typeId: {}, instanceId: {}, instance: {}", policyTypeIdString, policyInstanceId, - instance); + instance); return this.policyAgentApi.putPolicy(policyTypeIdString, policyInstanceId, instance, ric); } @ApiOperation(value = "Deletes the policy instances for the given policy type.") @DeleteMapping(POLICY_TYPES_METHOD + "/{" + POLICY_TYPE_ID_NAME + "}/" + POLICIES_NAME + "/{" - + POLICY_INSTANCE_ID_NAME + "}") - @Secured({DashboardConstants.ROLE_ADMIN}) + + POLICY_INSTANCE_ID_NAME + "}") + @Secured({ DashboardConstants.ROLE_ADMIN }) public ResponseEntity deletePolicyInstance(@PathVariable(POLICY_TYPE_ID_NAME) String policyTypeIdString, - @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) { + @PathVariable(POLICY_INSTANCE_ID_NAME) String policyInstanceId) { logger.debug("deletePolicyInstance typeId: {}, instanceId: {}", policyTypeIdString, policyInstanceId); return this.policyAgentApi.deletePolicy(policyInstanceId); } @ApiOperation(value = "Returns the rics supporting the given policy type.") @GetMapping("/rics") - @Secured({DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD}) + @Secured({ DashboardConstants.ROLE_ADMIN, DashboardConstants.ROLE_STANDARD }) public ResponseEntity getRicsSupportingType( - @RequestParam(name = "policyType", required = true) String supportingPolicyType) { + @RequestParam(name = "policyType", required = true) String supportingPolicyType) { logger.debug("getRicsSupportingType {}", supportingPolicyType); return this.policyAgentApi.getRicsSupportingType(supportingPolicyType); diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java index 30cfd2aa..7f26a9f2 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyInfo.java @@ -32,7 +32,7 @@ public interface PolicyInfo { public String ric(); - public String json(); + public Object json(); public String service(); diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java index f0ca285b..035428b7 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/model/PolicyType.java @@ -27,9 +27,9 @@ public class PolicyType { String name; @JsonProperty("schema") - String schema; + Object schema; - public PolicyType(String name, String schema) { + public PolicyType(String name, Object schema) { this.name = name; this.schema = schema; } @@ -42,16 +42,16 @@ public class PolicyType { this.name = name; } - public String getSchema() { + public Object getSchema() { return schema; } - public void setSchema(String schema) { + public void setSchema(Object schema) { this.schema = schema; } @Override public String toString() { - return "[name:" + name + ", schema:" + schema + "]"; + return "[name:" + name + ", schema:" + schema.toString() + "]"; } } diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java index ff254d22..6b7fdd24 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApi.java @@ -27,10 +27,10 @@ public interface PolicyAgentApi { public ResponseEntity getPolicyInstancesForType(String type); - public ResponseEntity getPolicyInstance(String id); + public ResponseEntity getPolicyInstance(String id); - public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, String json, - String ric); + public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, Object json, + String ric); public ResponseEntity deletePolicy(String policyInstanceId); diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java index c0dde9bd..fe9c26cd 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/policyagentapi/PolicyAgentApiImpl.java @@ -58,14 +58,14 @@ public class PolicyAgentApiImpl implements PolicyAgentApi { RestTemplate restTemplate = new RestTemplate(); private static com.google.gson.Gson gson = new GsonBuilder() // - .serializeNulls() // - .create(); // + .serializeNulls() // + .create(); // private final String urlPrefix; @Autowired public PolicyAgentApiImpl( - @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) { + @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) { logger.debug("ctor prefix '{}'", urlPrefix); this.urlPrefix = urlPrefix; } @@ -119,7 +119,8 @@ public class PolicyAgentApiImpl implements PolicyAgentApi { } try { - Type listType = new TypeToken>() {}.getType(); + Type listType = new TypeToken>() { + }.getType(); List rspParsed = gson.fromJson(rsp.getBody(), listType); PolicyInstances result = new PolicyInstances(); for (PolicyInfo p : rspParsed) { @@ -132,22 +133,22 @@ public class PolicyAgentApiImpl implements PolicyAgentApi { } @Override - public ResponseEntity getPolicyInstance(String id) { + public ResponseEntity getPolicyInstance(String id) { String url = baseUrl() + "/policy?instance={id}"; Map uriVariables = Map.of("id", id); - return this.restTemplate.getForEntity(url, String.class, uriVariables); + return this.restTemplate.getForEntity(url, Object.class, uriVariables); } @Override - public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, String json, - String ric) { + public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, Object json, + String ric) { String url = baseUrl() + "/policy?type={type}&instance={instance}&ric={ric}&service={service}"; Map uriVariables = Map.of( // - "type", policyTypeIdString, // - "instance", policyInstanceId, // - "ric", ric, // - "service", "dashboard"); + "type", policyTypeIdString, // + "instance", policyInstanceId, // + "ric", ric, // + "service", "dashboard"); try { this.restTemplate.put(url, createJsonHttpEntity(json), uriVariables); @@ -187,7 +188,8 @@ public class PolicyAgentApiImpl implements PolicyAgentApi { String rsp = this.restTemplate.getForObject(url, String.class, uriVariables); try { - Type listType = new TypeToken>() {}.getType(); + Type listType = new TypeToken>() { + }.getType(); List rspParsed = gson.fromJson(rsp, listType); Collection result = new Vector<>(rspParsed.size()); for (RicInfo ric : rspParsed) { @@ -199,10 +201,10 @@ public class PolicyAgentApiImpl implements PolicyAgentApi { } } - private HttpEntity createJsonHttpEntity(String content) { + private HttpEntity createJsonHttpEntity(Object content) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - return new HttpEntity(content, headers); + return new HttpEntity(content, headers); } } diff --git a/dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PolicyControllerMockConfiguration.java b/dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PolicyControllerMockConfiguration.java index 2268fe06..76ce40c7 100644 --- a/dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PolicyControllerMockConfiguration.java +++ b/dashboard/webapp-backend/src/test/java/org/oransc/ric/portal/dashboard/config/PolicyControllerMockConfiguration.java @@ -70,12 +70,12 @@ public class PolicyControllerMockConfiguration { private final Database database = new Database(); @Override - public ResponseEntity getPolicyInstance(String id) { + public ResponseEntity getPolicyInstance(String id) { return new ResponseEntity<>(database.getInstance(id), HttpStatus.OK); } @Override - public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, String json, + public ResponseEntity putPolicy(String policyTypeIdString, String policyInstanceId, Object json, String ric) { database.putInstance(policyTypeIdString, policyInstanceId, json, ric); return new ResponseEntity<>("Policy was put successfully", HttpStatus.OK); @@ -147,7 +147,7 @@ public class PolicyControllerMockConfiguration { return java.time.Instant.now().toString(); } - void putInstance(String typeId, String instanceId, String instanceData, String ric) { + void putInstance(String typeId, String instanceId, Object instanceData, String ric) { PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC()) .id(instanceId).ric(ric).service("service").type(typeId).build(); instances.put(instanceId, i); @@ -157,7 +157,7 @@ public class PolicyControllerMockConfiguration { instances.remove(instanceId); } - String getInstance(String id) throws RestClientException { + Object getInstance(String id) throws RestClientException { PolicyInfo i = instances.get(id); if (i == null) { throw new RestClientException("Type not found: " + id); diff --git a/policy-agent/docs/api.yaml b/policy-agent/docs/api.yaml index 14162989..1c41d420 100644 --- a/policy-agent/docs/api.yaml +++ b/policy-agent/docs/api.yaml @@ -516,7 +516,7 @@ paths: schema: type: array items: - type: string + type: object '401': description: Unauthorized '403': @@ -705,9 +705,9 @@ paths: produces: - '*/*' parameters: - - name: name + - name: serviceName in: query - description: name + description: serviceName required: true type: string responses: @@ -733,9 +733,9 @@ paths: produces: - '*/*' parameters: - - name: name + - name: serviceName in: query - description: name + description: serviceName required: true type: string responses: @@ -756,7 +756,7 @@ paths: get: tags: - status-controller - summary: Returns status and statistics of the service + summary: Returns status and statistics of this service operationId: getStatusUsingGET produces: - '*/*' @@ -799,7 +799,7 @@ definitions: type: string description: identity of the policy json: - type: string + type: object description: the configuration of the policy lastModified: type: string @@ -841,7 +841,7 @@ definitions: type: integer format: int64 description: keep alive interval for policies owned by the service. 0 means no timeout supervision. Polcies that are not refreshed within this time are removed - name: + serviceName: type: string description: identity of the service title: ServiceRegistrationInfo @@ -852,7 +852,7 @@ definitions: type: integer format: int64 description: policy keep alive timeout - name: + serviceName: type: string description: identity of the service timeSincePingSeconds: diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java index e0971c50..965b42f3 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java @@ -78,7 +78,7 @@ public class PolicyController { @ApiOperation(value = "Returns policy type schema definitions") @ApiResponses( value = { - @ApiResponse(code = 200, message = "Policy schemas", response = String.class, responseContainer = "List")}) + @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List")}) public ResponseEntity getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) { synchronized (this.policyTypes) { if (ricName == null) { @@ -272,7 +272,7 @@ public class PolicyController { for (Policy p : policies) { PolicyInfo policyInfo = new PolicyInfo(); policyInfo.id = p.id(); - policyInfo.json = p.json(); + policyInfo.json = fromJson(p.json()); policyInfo.ric = p.ric().name(); policyInfo.type = p.type().name(); policyInfo.service = p.ownerServiceName(); @@ -285,6 +285,10 @@ public class PolicyController { return gson.toJson(v); } + private Object fromJson(String jsonStr) { + return gson.fromJson(jsonStr, Object.class); + } + private String toPolicyTypeSchemasJson(Collection types) { StringBuilder result = new StringBuilder(); result.append("["); diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java index bd130629..1736c18e 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java @@ -39,7 +39,7 @@ public class PolicyInfo { public String ric; @ApiModelProperty(value = "the configuration of the policy") - public String json; + public Object json; @ApiModelProperty(value = "the name of the service owning the policy") public String service; diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/RicRepositoryController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/RicRepositoryController.java index bb3b735f..38369a84 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/RicRepositoryController.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/RicRepositoryController.java @@ -57,7 +57,7 @@ public class RicRepositoryController { } /** - * Example: http://localhost:8080/rics?managedElementId=kista_1 + * Example: http://localhost:8081/rics?managedElementId=kista_1 */ @GetMapping("/ric") @ApiOperation(value = "Returns the name of a RIC managing one Mananged Element") @@ -80,7 +80,7 @@ public class RicRepositoryController { /** * @return a Json array of all RIC data - * Example: http://localhost:8080/ric + * Example: http://localhost:8081/ric */ @GetMapping("/rics") @ApiOperation(value = "Query NearRT RIC information") diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceController.java index 012d40a9..e68b82c3 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceController.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceController.java @@ -104,9 +104,9 @@ public class ServiceController { @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")}) @DeleteMapping("/services") public ResponseEntity deleteService( // - @RequestParam(name = "name", required = true) String name) { + @RequestParam(name = "serviceName", required = true) String serviceName) { try { - Service service = removeService(name); + Service service = removeService(serviceName); // Remove the policies from the repo and let the consistency monitoring // do the rest. removePolicies(service); @@ -122,9 +122,9 @@ public class ServiceController { @ApiResponse(code = 404, message = "The service is not found, needs re-registration")}) @PostMapping("/services/keepalive") public ResponseEntity keepAliveService( // - @RequestParam(name = "name", required = true) String name) { + @RequestParam(name = "serviceName", required = true) String serviceName) { try { - services.getService(name).ping(); + services.getService(serviceName).ping(); return new ResponseEntity("OK", HttpStatus.OK); } catch (Exception e) { return new ResponseEntity(e.getMessage(), HttpStatus.NOT_FOUND); @@ -149,7 +149,7 @@ public class ServiceController { } private Service toService(ServiceRegistrationInfo s) { - return new Service(s.name, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl); + return new Service(s.serviceName, Duration.ofSeconds(s.keepAliveIntervalSeconds), s.callbackUrl); } } diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceRegistrationInfo.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceRegistrationInfo.java index 145fdb02..907fa1c4 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceRegistrationInfo.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceRegistrationInfo.java @@ -30,7 +30,7 @@ import org.immutables.gson.Gson; public class ServiceRegistrationInfo { @ApiModelProperty(value = "identity of the service") - public String name; + public String serviceName; @ApiModelProperty( value = "keep alive interval for policies owned by the service. 0 means no timeout supervision." @@ -44,7 +44,7 @@ public class ServiceRegistrationInfo { } public ServiceRegistrationInfo(String name, long keepAliveIntervalSeconds, String callbackUrl) { - this.name = name; + this.serviceName = name; this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; this.callbackUrl = callbackUrl; } diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceStatus.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceStatus.java index c30cce15..fc80834c 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceStatus.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/ServiceStatus.java @@ -30,7 +30,7 @@ import org.immutables.gson.Gson; public class ServiceStatus { @ApiModelProperty(value = "identity of the service") - public final String name; + public final String serviceName; @ApiModelProperty(value = "policy keep alive timeout") public final long keepAliveIntervalSeconds; @@ -39,7 +39,7 @@ public class ServiceStatus { public final long timeSincePingSeconds; ServiceStatus(String name, long keepAliveIntervalSeconds, long timeSincePingSeconds) { - this.name = name; + this.serviceName = name; this.keepAliveIntervalSeconds = keepAliveIntervalSeconds; this.timeSincePingSeconds = timeSincePingSeconds; } diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/StatusController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/StatusController.java index 1219a0d8..48d9a579 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/StatusController.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/StatusController.java @@ -34,7 +34,7 @@ import reactor.core.publisher.Mono; public class StatusController { @GetMapping("/status") - @ApiOperation(value = "Returns status and statistics of the service") + @ApiOperation(value = "Returns status and statistics of this service") @ApiResponses( value = { // @ApiResponse(code = 200, message = "Service is living", response = String.class) // diff --git a/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumer.java b/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumer.java index c132fa28..91f9ff22 100644 --- a/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumer.java +++ b/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumer.java @@ -1,4 +1,3 @@ - /*- * ========================LICENSE_START================================= * O-RAN-SC @@ -21,38 +20,102 @@ package org.oransc.policyagent.dmaap; -/** - * The Dmaap consumer which has the base methods to be implemented by any class which implements this interface - * - */ -public interface DmaapMessageConsumer { - - /** - * The init method creates the MRConsumer with the properties passed from the Application Config - * - * @param properties - */ - public void init(); - - /** - * This method process the message and call the respective Controller - * - * @param msg - * @throws Exception - */ - public abstract void processMsg(String msg) throws Exception; - - /** - * To check whether the DMAAP Listner is alive - * - * @return boolean - */ - public boolean isAlive(); - - /** - * It's a infinite loop run every configured seconds to fetch the message from DMAAP. This method can be stop by - * setting the alive flag to false - */ - public void run(); +import com.google.common.collect.Iterables; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.time.Duration; +import java.util.Properties; + +import org.onap.dmaap.mr.client.MRBatchingPublisher; +import org.onap.dmaap.mr.client.MRClientFactory; +import org.onap.dmaap.mr.client.MRConsumer; +import org.onap.dmaap.mr.client.response.MRConsumerResponse; +import org.oransc.policyagent.clients.AsyncRestClient; +import org.oransc.policyagent.configuration.ApplicationConfig; +import org.oransc.policyagent.exceptions.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class DmaapMessageConsumer implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class); + + final Duration TIME_BETWEEN_DMAAP_POLLS = Duration.ofSeconds(10); + private final ApplicationConfig applicationConfig; + + @Value("${server.port}") + private int localServerPort; + + @Autowired + public DmaapMessageConsumer(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + + Thread thread = new Thread(this); + thread.start(); + } + + private boolean isDmaapConfigured() { + Properties consumerCfg = applicationConfig.getDmaapConsumerConfig(); + Properties producerCfg = applicationConfig.getDmaapPublisherConfig(); + return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0); + } + + @Override + public void run() { + while (sleep(TIME_BETWEEN_DMAAP_POLLS) && isDmaapConfigured()) { + try { + Iterable dmaapMsgs = fetchAllMessages(); + if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) { + logger.debug("Fetched all the messages from DMAAP and will start to process the messages"); + for (String msg : dmaapMsgs) { + processMsg(msg); + } + } + } catch (Exception e) { + logger.warn("{}: cannot fetch because of ", this, e.getMessage(), e); + sleep(TIME_BETWEEN_DMAAP_POLLS); + } + } + } + + private Iterable fetchAllMessages() throws ServiceException, FileNotFoundException, IOException { + Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig(); + MRConsumer consumer = MRClientFactory.createConsumer(dmaapConsumerProperties); + MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse(); + if (response == null || !"200".equals(response.getResponseCode())) { + throw new ServiceException("DMaaP NULL response received"); + } else { + logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage()); + return response.getActualMessages(); + } + } + + private void processMsg(String msg) throws Exception { + logger.debug("Message Reveived from DMAAP : {}", msg); + createDmaapMessageHandler().handleDmaapMsg(msg); + } + + private DmaapMessageHandler createDmaapMessageHandler() throws FileNotFoundException, IOException { + String agentBaseUrl = "http://localhost:" + this.localServerPort; + AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl); + Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig(); + MRBatchingPublisher producer = MRClientFactory.createBatchingPublisher(dmaapPublisherProperties); + + return new DmaapMessageHandler(producer, this.applicationConfig, agentClient); + } + private boolean sleep(Duration duration) { + try { + Thread.sleep(duration.toMillis()); + return true; + } catch (Exception e) { + logger.error("Failed to put the thread to sleep", e); + return false; + } + } } diff --git a/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumerImpl.java b/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumerImpl.java deleted file mode 100644 index 4a2605b6..00000000 --- a/policy-agent/src/main/java/org/oransc/policyagent/dmaap/DmaapMessageConsumerImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * O-RAN-SC - * %% - * Copyright (C) 2019 Nordix Foundation - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ========================LICENSE_END=================================== - */ - -package org.oransc.policyagent.dmaap; - -import com.google.common.collect.Iterables; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.time.Duration; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.onap.dmaap.mr.client.MRBatchingPublisher; -import org.onap.dmaap.mr.client.MRClientFactory; -import org.onap.dmaap.mr.client.MRConsumer; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; -import org.oransc.policyagent.clients.AsyncRestClient; -import org.oransc.policyagent.configuration.ApplicationConfig; -import org.oransc.policyagent.exceptions.ServiceException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class DmaapMessageConsumerImpl implements Runnable { - - private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumerImpl.class); - - final Duration ERROR_TIMEOUT = Duration.ofSeconds(30); - final Duration TIME_BETWEEN_DMAAP_POLLS = Duration.ofSeconds(10); - private final ApplicationConfig applicationConfig; - - @Value("${server.port}") - private int localServerPort; - - @Autowired - public DmaapMessageConsumerImpl(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; - - Thread thread = new Thread(this); - thread.start(); - } - - private boolean isDmaapConfigured() { - Properties consumerCfg = applicationConfig.getDmaapConsumerConfig(); - Properties producerCfg = applicationConfig.getDmaapPublisherConfig(); - return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0); - } - - @Override - public void run() { - while (sleep(TIME_BETWEEN_DMAAP_POLLS) && isDmaapConfigured()) { - try { - Iterable dmaapMsgs = fetchAllMessages(); - if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) { - logger.debug("Fetched all the messages from DMAAP and will start to process the messages"); - for (String msg : dmaapMsgs) { - processMsg(msg); - } - } - } catch (Exception e) { - logger.error("{}: cannot fetch because of ", this, e.getMessage(), e); - sleep(ERROR_TIMEOUT); - } - } - } - - private Iterable fetchAllMessages() throws ServiceException, FileNotFoundException, IOException { - Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig(); - MRConsumer consumer = MRClientFactory.createConsumer(dmaapConsumerProperties); - MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse(); - if (response == null || !"200".equals(response.getResponseCode())) { - throw new ServiceException("DMaaP NULL response received"); - } else { - logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage()); - return response.getActualMessages(); - } - } - - private void processMsg(String msg) throws Exception { - logger.debug("Message Reveived from DMAAP : {}", msg); - createDmaapMessageHandler().handleDmaapMsg(msg); - } - - private DmaapMessageHandler createDmaapMessageHandler() throws FileNotFoundException, IOException { - String agentBaseUrl = "http://localhost:" + this.localServerPort; - AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl); - Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig(); - MRBatchingPublisher producer = MRClientFactory.createBatchingPublisher(dmaapPublisherProperties); - - return new DmaapMessageHandler(producer, this.applicationConfig, agentClient); - } - - private boolean sleep(Duration duration) { - CountDownLatch sleep = new CountDownLatch(1); - try { - sleep.await(duration.toMillis(), TimeUnit.MILLISECONDS); - return true; - } catch (Exception e) { - logger.error("msg", e); - return false; - } - } -} diff --git a/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java b/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java index aeeb19af..38de021f 100644 --- a/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java +++ b/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java @@ -349,8 +349,7 @@ public class ApplicationTest { String rsp = this.restTemplate.getForObject(url, String.class); System.out.println("*** " + rsp); assertThat(rsp).contains("type1"); - assertThat(rsp).contains("type2"); - assertThat(rsp).contains("title"); + assertThat(rsp).contains("[{\"title\":\"type2\"}"); List info = parseSchemas(rsp); assertEquals(2, info.size()); @@ -440,7 +439,7 @@ public class ApplicationTest { assertThat(info.size() == 1); ServiceStatus status = info.iterator().next(); assertThat(status.keepAliveIntervalSeconds == 1); - assertThat(status.name.equals("name")); + assertThat(status.serviceName.equals("name")); // GET (all) url = baseUrl() + "/services";