Merge "Rename Onap A1 client"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / dmaap / DmaapMessageHandler.java
index 9b0c809..dc979de 100644 (file)
@@ -2,7 +2,7 @@
  * ========================LICENSE_START=================================
  * O-RAN-SC
  * %%
- * Copyright (C) 2019 Nordix Foundation
+ * Copyright (C) 2020 Nordix Foundation
  * %%
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,13 +22,14 @@ package org.oransc.policyagent.dmaap;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
 
 import java.io.IOException;
+import java.util.Optional;
 
 import org.onap.dmaap.mr.client.MRBatchingPublisher;
 import org.oransc.policyagent.clients.AsyncRestClient;
-import org.oransc.policyagent.configuration.ApplicationConfig;
-import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
+import org.oransc.policyagent.exceptions.ServiceException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.http.HttpStatus;
@@ -39,21 +40,19 @@ public class DmaapMessageHandler {
     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
 
     private static Gson gson = new GsonBuilder() //
-        .serializeNulls() //
         .create(); //
 
     private final MRBatchingPublisher dmaapClient;
     private final AsyncRestClient agentClient;
 
-    public DmaapMessageHandler(MRBatchingPublisher dmaapClient, ApplicationConfig applicationConfig,
-        AsyncRestClient agentClient) {
+    public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
         this.agentClient = agentClient;
         this.dmaapClient = dmaapClient;
     }
 
     public void handleDmaapMsg(String msg) {
         this.createTask(msg) //
-            .subscribe(x -> logger.debug("handleDmaapMsg: " + x), //
+            .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
                 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
                 () -> logger.debug("handleDmaapMsg complete"));
     }
@@ -63,7 +62,7 @@ public class DmaapMessageHandler {
             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
 
             return this.invokePolicyAgent(dmaapRequestMessage) //
-                .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
+                .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
                 .flatMap(response -> sendDmaapResponse(response, dmaapRequestMessage, HttpStatus.OK));
 
         } catch (Exception e) {
@@ -72,35 +71,67 @@ public class DmaapMessageHandler {
         }
     }
 
-    private Mono<String> handleAgentCallError(Throwable t, DmaapRequestMessage dmaapRequestMessage) {
-        logger.debug("Agent call failed: " + t.getMessage());
-        return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
-            .flatMap(s -> Mono.empty());
+    private Mono<String> handleAgentCallError(Throwable t, String origianalMessage,
+        DmaapRequestMessage dmaapRequestMessage) {
+        logger.debug("Agent call failed: {}", t.getMessage());
+        if (t instanceof ServiceException) {
+            String errorMessage = prepareBadOperationErrorMessage(t, origianalMessage);
+            return sendDmaapResponse(errorMessage, dmaapRequestMessage, HttpStatus.NOT_FOUND) //
+                .flatMap(notUsed -> Mono.empty());
+        } else {
+            return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
+                .flatMap(notUsed -> Mono.empty());
+        }
+    }
+
+    private String prepareBadOperationErrorMessage(Throwable t, String origianalMessage) {
+        String badOperation = origianalMessage.substring(origianalMessage.indexOf("operation\":\"") + 12,
+            origianalMessage.indexOf(",\"url\":"));
+        String errorMessage = t.getMessage().replace("null", badOperation);
+        return errorMessage;
     }
 
     private Mono<String> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
+        if (operation == null) {
+            return Mono.error(new ServiceException("Not implemented operation: " + operation));
+        }
         Mono<String> result = null;
         String uri = dmaapRequestMessage.url();
-        if (operation == Operation.DELETE) {
-            result = agentClient.delete(uri);
-        } else if (operation == Operation.GET) {
-            result = agentClient.get(uri);
-        } else if (operation == Operation.PUT) {
-            result = agentClient.put(uri, dmaapRequestMessage.payload());
-        } else if (operation == Operation.POST) {
-            result = agentClient.post(uri, dmaapRequestMessage.payload());
-        } else {
-            return Mono.error(new Exception("Not implemented operation: " + operation));
+        switch (operation) {
+            case DELETE:
+                result = agentClient.delete(uri);
+                break;
+            case GET:
+                result = agentClient.get(uri);
+                break;
+            case PUT:
+                result = agentClient.put(uri, payload(dmaapRequestMessage));
+                break;
+            case POST:
+                result = agentClient.post(uri, payload(dmaapRequestMessage));
+                break;
+            default:
+                // Nothing, can never get here.
         }
         return result;
     }
 
+    private String payload(DmaapRequestMessage message) {
+        Optional<JsonObject> payload = message.payload();
+        if (payload.isPresent()) {
+            return gson.toJson(payload.get());
+        } else {
+            logger.warn("Expected payload in message from DMAAP: {}", message);
+            return "";
+        }
+    }
+
     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
         HttpStatus status) {
         return getDmaapResponseMessage(dmaapRequestMessage, response, status) //
-            .flatMap(body -> sendToDmaap(body)) //
-            .onErrorResume(t -> handleResponseCallError(t, dmaapRequestMessage));
+            .flatMap(this::sendToDmaap) //
+            .onErrorResume(this::handleResponseCallError);
     }
 
     private Mono<String> sendToDmaap(String body) {
@@ -114,8 +145,8 @@ public class DmaapMessageHandler {
         }
     }
 
-    private Mono<String> handleResponseCallError(Throwable t, DmaapRequestMessage dmaapRequestMessage) {
-        logger.debug("Failed to respond: " + t.getMessage());
+    private Mono<String> handleResponseCallError(Throwable t) {
+        logger.debug("Failed to send respons to DMaaP: {}", t.getMessage());
         return Mono.empty();
     }
 
@@ -135,5 +166,4 @@ public class DmaapMessageHandler {
         return Mono.just(str);
 
     }
-
 }