Register types DMaaP mediator producer

Issue-ID: NONRTRIC-583
Signed-off-by: elinuxhenrik <henrik.b.andersson@est.tech>
Change-Id: I2f8536cb54a1a0e9a44adbd806af3b7ad8e90e61
diff --git a/dmaap-mediator-producer/internal/restclient/HTTPClient.go b/dmaap-mediator-producer/internal/restclient/HTTPClient.go
new file mode 100644
index 0000000..c6eb24c
--- /dev/null
+++ b/dmaap-mediator-producer/internal/restclient/HTTPClient.go
@@ -0,0 +1,103 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2021: 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 restclient
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"net/http"
+)
+
+// HTTPClient interface
+type HTTPClient interface {
+	Get(url string) (*http.Response, error)
+
+	Do(*http.Request) (*http.Response, error)
+}
+
+type RequestError struct {
+	StatusCode int
+	Body       []byte
+}
+
+func (pe RequestError) Error() string {
+	return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
+}
+
+var (
+	Client HTTPClient
+)
+
+func init() {
+	Client = &http.Client{}
+}
+
+func Get(url string) ([]byte, error) {
+	if response, err := Client.Get(url); err == nil {
+		defer response.Body.Close()
+		if responseData, err := io.ReadAll(response.Body); err == nil {
+			if isResponseSuccess(response.StatusCode) {
+				return responseData, nil
+			} else {
+				requestError := RequestError{
+					StatusCode: response.StatusCode,
+					Body:       responseData,
+				}
+				return nil, requestError
+			}
+		} else {
+			return nil, err
+		}
+	} else {
+		return nil, err
+	}
+}
+
+func Put(url string, body []byte) error {
+	if req, reqErr := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(body)); reqErr == nil {
+		req.Header.Set("Content-Type", "application/json; charset=utf-8")
+		if response, respErr := Client.Do(req); respErr == nil {
+			if isResponseSuccess(response.StatusCode) {
+				return nil
+			} else {
+				return getRequestError(response)
+			}
+		} else {
+			return respErr
+		}
+	} else {
+		return reqErr
+	}
+}
+
+func isResponseSuccess(statusCode int) bool {
+	return statusCode >= http.StatusOK && statusCode <= 299
+}
+
+func getRequestError(response *http.Response) RequestError {
+	responseData, _ := io.ReadAll(response.Body)
+	putError := RequestError{
+		StatusCode: response.StatusCode,
+		Body:       responseData,
+	}
+	return putError
+}
diff --git a/dmaap-mediator-producer/internal/restclient/HTTPClient_test.go b/dmaap-mediator-producer/internal/restclient/HTTPClient_test.go
new file mode 100644
index 0000000..3727e6a
--- /dev/null
+++ b/dmaap-mediator-producer/internal/restclient/HTTPClient_test.go
@@ -0,0 +1,164 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2021: 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 restclient
+
+import (
+	"bytes"
+	"errors"
+	"io/ioutil"
+	"net/http"
+	"reflect"
+	"testing"
+
+	"github.com/stretchr/testify/mock"
+	"github.com/stretchr/testify/require"
+	"oransc.org/nonrtric/dmaapmediatorproducer/mocks"
+)
+
+func TestGet(t *testing.T) {
+	clientMock := mocks.HTTPClient{}
+
+	clientMock.On("Get", "http://testOk").Return(&http.Response{
+		StatusCode: http.StatusOK,
+		Body:       ioutil.NopCloser(bytes.NewReader([]byte("Response"))),
+	}, nil)
+
+	clientMock.On("Get", "http://testNotOk").Return(&http.Response{
+		StatusCode: http.StatusBadRequest,
+		Body:       ioutil.NopCloser(bytes.NewReader([]byte("Bad Response"))),
+	}, nil)
+
+	clientMock.On("Get", "http://testError").Return(nil, errors.New("Failed Request"))
+
+	Client = &clientMock
+
+	type args struct {
+		url string
+	}
+	tests := []struct {
+		name        string
+		args        args
+		want        []byte
+		wantErr     bool
+		wantedError error
+	}{
+		{
+			name: "Test Get with OK response",
+			args: args{
+				url: "http://testOk",
+			},
+			want:    []byte("Response"),
+			wantErr: false,
+		},
+		{
+			name: "Test Get with Not OK response",
+			args: args{
+				url: "http://testNotOk",
+			},
+			want:    nil,
+			wantErr: true,
+			wantedError: RequestError{
+				StatusCode: http.StatusBadRequest,
+				Body:       []byte("Bad Response"),
+			},
+		},
+		{
+			name: "Test Get with error",
+			args: args{
+				url: "http://testError",
+			},
+			want:        nil,
+			wantErr:     true,
+			wantedError: errors.New("Failed Request"),
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := Get(tt.args.url)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Get() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Get() = %v, want %v", got, tt.want)
+			}
+			if tt.wantErr && err.Error() != tt.wantedError.Error() {
+				t.Errorf("Get() error = %v, wantedError % v", err, tt.wantedError.Error())
+			}
+		})
+	}
+}
+
+func TestPutOk(t *testing.T) {
+	assertions := require.New(t)
+	clientMock := mocks.HTTPClient{}
+
+	clientMock.On("Do", mock.Anything).Return(&http.Response{
+		StatusCode: http.StatusOK,
+	}, nil)
+
+	Client = &clientMock
+	if err := Put("http://localhost:9990", []byte("body")); err != nil {
+		t.Errorf("Put() error = %v, did not want error", err)
+	}
+	var actualRequest *http.Request
+	clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
+		actualRequest = req
+		return true
+	}))
+	assertions.Equal(http.MethodPut, actualRequest.Method)
+	assertions.Equal("http", actualRequest.URL.Scheme)
+	assertions.Equal("localhost:9990", actualRequest.URL.Host)
+	assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
+	body, _ := ioutil.ReadAll(actualRequest.Body)
+	expectedBody := []byte("body")
+	assertions.Equal(expectedBody, body)
+	clientMock.AssertNumberOfCalls(t, "Do", 1)
+}
+
+func TestPutBadResponse(t *testing.T) {
+	assertions := require.New(t)
+	clientMock := mocks.HTTPClient{}
+
+	clientMock.On("Do", mock.Anything).Return(&http.Response{
+		StatusCode: http.StatusBadRequest,
+		Body:       ioutil.NopCloser(bytes.NewReader([]byte("Bad Request"))),
+	}, nil)
+
+	Client = &clientMock
+	err := Put("url", []byte("body"))
+	assertions.NotNil("Put() error = %v, wanted error", err)
+	expectedErrorMessage := "Request failed due to error response with status: 400 and body: Bad Request"
+	assertions.Equal(expectedErrorMessage, err.Error())
+}
+
+func TestPutError(t *testing.T) {
+	assertions := require.New(t)
+	clientMock := mocks.HTTPClient{}
+
+	clientMock.On("Do", mock.Anything).Return(nil, errors.New("Failed Request"))
+
+	Client = &clientMock
+	err := Put("url", []byte("body"))
+	assertions.NotNil("Put() error = %v, wanted error", err)
+	expectedErrorMessage := "Failed Request"
+	assertions.Equal(expectedErrorMessage, err.Error())
+}