Java 17 Upgrade
[policy/models.git] / models-interactions / model-impl / rest / src / main / java / org / onap / policy / rest / RestManager.java
index bbc30a7..855dc92 100644 (file)
@@ -2,8 +2,8 @@
  * ============LICENSE_START=======================================================
  * rest
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020, 2023 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.rest;
 
-import java.nio.charset.Charset;
+import jakarta.xml.bind.DatatypeConverter;
+import java.nio.charset.StandardCharsets;
 import java.util.Map;
 import java.util.Map.Entry;
-import javax.xml.bind.DatatypeConverter;
-
+import org.apache.commons.lang3.tuple.Pair;
 import org.apache.http.HttpHeaders;
 import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpDelete;
 import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPatch;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
 import org.apache.http.client.methods.HttpRequestBase;
 import org.apache.http.conn.ssl.NoopHostnameVerifier;
 import org.apache.http.entity.StringEntity;
@@ -40,37 +43,56 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class RestManager {
-
     private static final Logger logger = LoggerFactory.getLogger(RestManager.class);
 
-    public class Pair<A, B> {
-        public final A first;
-        public final B second;
+    // Constants for string literals
+    private static final String CONTENT_TYPE = "Content-Type";
 
-        public Pair(A first, B second) {
-            this.first = first;
-            this.second = second;
+    /**
+     * Perform REST PUT.
+     *
+     * @param url the url
+     * @param username the user
+     * @param password the password
+     * @param headers any headers
+     * @param contentType what the content type is
+     * @param body body to send
+     * @return the response status code and the body
+     */
+    public Pair<Integer, String> put(String url, String username, String password, Map<String, String> headers,
+            String contentType, String body) {
+        var put = new HttpPut(url);
+        addHeaders(put, username, password, headers);
+        put.addHeader(CONTENT_TYPE, contentType);
+        try {
+            var input = new StringEntity(body);
+            input.setContentType(contentType);
+            put.setEntity(input);
+        } catch (Exception e) {
+            logger.error("put threw: ", e);
+            return null;
         }
+        return sendRequest(put);
     }
 
     /**
      * Perform REST Post.
      *
-     * @param url         the url
-     * @param username    the user name
-     * @param password    the password
-     * @param headers     any headers
+     * @param url the url
+     * @param username the user
+     * @param password the password
+     * @param headers any headers
      * @param contentType what the content type is
-     * @param body        body to send
+     * @param body body to send
      * @return the response status code and the body
      */
-    public Pair<Integer, String> post(String url, String username, String password,
-                                      Map<String, String> headers, String contentType, String body) {
-        HttpPost post = new HttpPost(url);
+    public Pair<Integer, String> post(String url, String username, String password, Map<String, String> headers,
+            String contentType, String body) {
+        var post = new HttpPost(url);
         addHeaders(post, username, password, headers);
-        post.addHeader("Content-Type", contentType);
+        post.addHeader(CONTENT_TYPE, contentType);
         try {
-            StringEntity input = new StringEntity(body);
+            var input = new StringEntity(body);
             input.setContentType(contentType);
             post.setEntity(input);
         } catch (Exception e) {
@@ -83,38 +105,38 @@ public class RestManager {
     /**
      * Do a REST get.
      *
-     * @param url      URL
-     * @param username user name
+     * @param url URL
+     * @param username user
      * @param password password
-     * @param headers  any headers to add
+     * @param headers any headers to add
      * @return a Pair for the response status and the body
      */
-    public Pair<Integer, String> get(String url, String username, String password,
-                                     Map<String, String> headers) {
-        HttpGet get = new HttpGet(url);
+    public Pair<Integer, String> get(String url, String username, String password, Map<String, String> headers) {
+        var get = new HttpGet(url);
         addHeaders(get, username, password, headers);
         return sendRequest(get);
     }
 
     /**
-     * Perform REST Delete.
+     * Perform REST Delete. <br/>
+     * <i>Note: Many REST endpoints will return a 400 error for delete requests with a non-empty body</i>
      *
-     * @param url         the url
-     * @param username    the user name
-     * @param password    the password
-     * @param headers     any headers
+     * @param url the url
+     * @param username the user
+     * @param password the password
+     * @param headers any headers
      * @param contentType what the content type is
-     * @param body        body (optional) to send
+     * @param body body (optional) to send
      * @return the response status code and the body
      */
     public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers,
-                                        String contentType, String body) {
-        HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
+            String contentType, String body) {
+        var delete = new HttpDeleteWithBody(url);
         addHeaders(delete, username, password, headers);
-        delete.addHeader("Content-Type", contentType);
         if (body != null && !body.isEmpty()) {
+            delete.addHeader(CONTENT_TYPE, contentType);
             try {
-                StringEntity input = new StringEntity(body);
+                var input = new StringEntity(body);
                 input.setContentType(contentType);
                 delete.setEntity(input);
             } catch (Exception e) {
@@ -125,6 +147,48 @@ public class RestManager {
         return sendRequest(delete);
     }
 
+    /**
+     * Perform REST Delete.
+     *
+     * @param url the url
+     * @param username the user
+     * @param password the password
+     * @param headers any headers
+     * @return the response status code and the body
+     */
+    public Pair<Integer, String> delete(String url, String username, String password, Map<String, String> headers) {
+        var delete = new HttpDelete(url);
+        addHeaders(delete, username, password, headers);
+        return sendRequest(delete);
+    }
+
+    /**
+     * Perform REST Patch.
+     *
+     * @param url the url
+     * @param username the user
+     * @param password the password
+     * @param headers any headers
+     * @param body body to send
+     * @return the response status code and the body
+     */
+    public Pair<Integer, String> patch(String url, String username, String password, Map<String, String> headers,
+            String body) {
+        var contentType = "application/merge-patch+json";
+        var patch = new HttpPatch(url);
+        addHeaders(patch, username, password, headers);
+        patch.addHeader(CONTENT_TYPE, contentType);
+        try {
+            var input = new StringEntity(body);
+            input.setContentType(contentType);
+            patch.setEntity(input);
+        } catch (Exception e) {
+            logger.error("patch threw: ", e);
+            return null;
+        }
+        return sendRequest(patch);
+    }
+
     /**
      * Send REST request.
      *
@@ -137,20 +201,15 @@ public class RestManager {
         }
 
         try (CloseableHttpClient client =
-                     HttpClientBuilder
-                             .create()
-                             .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
-                             .build()) {
+                HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build()) {
             HttpResponse response = client.execute(request);
             if (response != null) {
-                String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
-                logger.debug("HTTP Response Status Code: {}",
-                        response.getStatusLine().getStatusCode());
+                var returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+                logger.debug("HTTP Response Status Code: {}", response.getStatusLine().getStatusCode());
                 logger.debug("HTTP Response Body:");
                 logger.debug(returnBody);
 
-                return new Pair<>(response.getStatusLine().getStatusCode(),
-                        returnBody);
+                return Pair.of(response.getStatusLine().getStatusCode(), returnBody);
             } else {
                 logger.error("Response from {} is null", request.getURI());
                 return null;
@@ -164,13 +223,12 @@ public class RestManager {
     /**
      * Add header to the request.
      *
-     * @param request  http request to send
-     * @param username the user name
+     * @param request http request to send
+     * @param username the user
      * @param password the password
-     * @param headers  any headers
+     * @param headers any headers
      */
-    private void addHeaders(HttpRequestBase request, String username, String password, Map<String,
-            String> headers) {
+    private void addHeaders(HttpRequestBase request, String username, String password, Map<String, String> headers) {
         String authHeader = makeAuthHeader(username, password);
         if (headers != null) {
             for (Entry<String, String> entry : headers.entrySet()) {
@@ -188,6 +246,6 @@ public class RestManager {
         }
 
         String auth = username + ":" + (password == null ? "" : password);
-        return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(Charset.forName("ISO-8859-1")));
+        return "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.ISO_8859_1));
     }
 }