Skip to content

Commit

Permalink
Merge pull request nutanix#31 from nutanix/29-network-sec-rules-client
Browse files Browse the repository at this point in the history
29-Network Security Rules Client
  • Loading branch information
crizstian authored May 7, 2018
2 parents 2adb673 + c3b235f commit 449ac89
Show file tree
Hide file tree
Showing 4 changed files with 392 additions and 41 deletions.
18 changes: 11 additions & 7 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ type Credentials struct {
func NewClient(credentials *Credentials) (*Client, error) {

transCfg := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates
TLSClientConfig: &tls.Config{InsecureSkipVerify: credentials.Insecure}, // ignore expired SSL certificates
}

httpClient := http.DefaultClient
Expand Down Expand Up @@ -100,8 +100,7 @@ func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body int
req.Header.Add("Authorization", "Basic "+
base64.StdEncoding.EncodeToString([]byte(c.Credentials.Username+":"+c.Credentials.Password)))

// log.Printf("REQUEST BODY \n")
// utils.PrintToJSON(req, "REQUEST BODY")
utils.PrintToJSON(req, "REQUEST BODY")

// requestDump, err := httputil.DumpRequestOut(req, true)
// if err != nil {
Expand Down Expand Up @@ -156,7 +155,6 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) error
if err != nil {
return err
}

utils.PrintToJSON(v, "RESPONSE BODY")
}
}
Expand All @@ -171,6 +169,11 @@ func CheckResponse(r *http.Response) error {
}

data, err := ioutil.ReadAll(r.Body)

if err != nil {
return err
}

res := &ErrorResponse{}
err = json.Unmarshal(data, res)
if err != nil {
Expand All @@ -181,15 +184,16 @@ func CheckResponse(r *http.Response) error {
return fmt.Errorf("Error: %s", string(pretty))
}

// ErrorResponse ...
//ErrorResponse ...
type ErrorResponse struct {
ApiVersion string `json:"api_version"`
APIVersion string `json:"api_version"`
Code int64 `json:"code"`
Kind string `json:"kind"`
MessageList []MessageResource `json:"message_list"`
State string `json:"state"`
}

//MessageResource ...
type MessageResource struct {

// Custom key-value details relevant to the status.
Expand All @@ -205,7 +209,7 @@ type MessageResource struct {
func (r *ErrorResponse) Error() string {
err := ""
for key, value := range r.MessageList {
err = fmt.Sprintf("%s: %s", key, value)
err = fmt.Sprintf("%d: {message:%s, reason:%s }", key, value.Message, value.Reason)
}
return err
}
40 changes: 17 additions & 23 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func setup() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)

client, _ = NewClient(&Credentials{"", "username", "password", "", "", ""})
client, _ = NewClient(&Credentials{"", "username", "password", "", "", true})
client.BaseURL, _ = url.Parse(server.URL)
}

Expand All @@ -36,7 +36,7 @@ func teardown() {

func TestNewClient(t *testing.T) {
u := "foo.com"
c, err := NewClient(&Credentials{u, "username", "password", "", "", ""})
c, err := NewClient(&Credentials{u, "username", "password", "", "", true})

if err != nil {
t.Errorf("Unexpected Error: %v", err)
Expand All @@ -55,7 +55,7 @@ func TestNewClient(t *testing.T) {

func TestNewRequest(t *testing.T) {
u := "foo.com"
c, err := NewClient(&Credentials{u, "username", "password", "", "", ""})
c, err := NewClient(&Credentials{u, "username", "password", "", "", true})

if err != nil {
t.Errorf("Unexpected Error: %v", err)
Expand All @@ -79,7 +79,12 @@ func TestNewRequest(t *testing.T) {
}

func TestErrorResponse_Error(t *testing.T) {
err := ErrorResponse{Message: map[string]string{"name": "This field may not be blank."}}
messageResource := MessageResource{Message: "This field may not be blank."}
messageList := make([]MessageResource, 1)
messageList[0] = messageResource

err := ErrorResponse{MessageList: messageList}

if err.Error() == "" {
t.Errorf("Expected non-empty ErrorResponse.Error()")
}
Expand All @@ -89,45 +94,34 @@ func TestGetResponse(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`{"name": "This field may not be blank."}`)),
Body: ioutil.NopCloser(strings.NewReader(`{"api_version": "3.0", "code": 400, "kind": "error", "message_list": [{"message": "This field may not be blank."}], "state": "none"}`)),
}

err := CheckResponse(res).(*ErrorResponse)
err := CheckResponse(res)

if err == nil {
t.Fatal("Expected error response.")
}

expected := &ErrorResponse{
Message: map[string]string{
"name": "This field may not be blank.",
},
}

if !reflect.DeepEqual(err, expected) {
t.Errorf("Error = %#v, expected %#v", err, expected)
if !strings.Contains(fmt.Sprint(err), "This field may not be blank.") {
t.Errorf("Error = %#v, expected %#v", err, "This field may not be blank.")
}
}

func TestCheckResponse(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`{"name": "This field may not be blank."}`)),
Body: ioutil.NopCloser(strings.NewReader(`{"api_version": "3.0", "code": 400, "kind": "error", "message_list": [{"message": "This field may not be blank."}], "state": "none"}`)),
}
err := CheckResponse(res).(*ErrorResponse)
err := CheckResponse(res)

if err == nil {
t.Fatalf("Expected error response.")
}

expected := &ErrorResponse{
Message: map[string]string{
"name": "This field may not be blank.",
},
}
if !reflect.DeepEqual(err, expected) {
t.Errorf("Error = %#v, expected %#v", err, expected)
if !strings.Contains(fmt.Sprint(err), "This field may not be blank.") {
t.Errorf("Error = %#v, expected %#v", err, "This field may not be blank.")
}
}

Expand Down
136 changes: 125 additions & 11 deletions client/v3/v3_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ type Service interface {
GetCategoryValue(name string, value string) (*CategoryValueStatus, error)
DeleteCategoryValue(name string, value string) error
GetCategoryQuery(query *CategoryQueryInput) (*CategoryQueryResponse, error)
UpdateNetworkSecurityRule(UUID string, body *NetworkSecurityRuleIntentInput) (*NetworkSecurityRuleIntentResponse, error)
ListNetworkSecurityRule(getEntitiesRequest *ListMetadata) (*NetworkSecurityRuleListIntentResponse, error)
GetNetworkSecurityRule(UUID string) (*NetworkSecurityRuleIntentResponse, error)
DeleteNetworkSecurityRule(UUID string) error
CreateNetworkSecurityRule(request *NetworkSecurityRuleIntentInput) (*NetworkSecurityRuleIntentResponse, error)
}

/*CreateVM Creates a VM
Expand Down Expand Up @@ -497,9 +502,6 @@ func (op Operations) CreateOrUpdateCategoryKey(body *CategoryKey) (*CategoryKeyS
path := fmt.Sprintf("/categories/%s", utils.StringValue(body.Name))

req, err := op.client.NewRequest(ctx, http.MethodPut, path, body)
if err != nil {
return nil, err
}

categoryKeyResponse := new(CategoryKeyStatus)

Expand Down Expand Up @@ -575,6 +577,7 @@ func (op Operations) GetCategoryKey(name string) (*CategoryKeyStatus, error) {
categoryKeyStatusResponse := new(CategoryKeyStatus)

err = op.client.Do(ctx, req, categoryKeyStatusResponse)

if err != nil {
return nil, err
}
Expand All @@ -594,7 +597,6 @@ func (op Operations) ListCategoryValues(name string, getEntitiesRequest *Categor
path := fmt.Sprintf("/categories/%s/list", name)

req, err := op.client.NewRequest(ctx, http.MethodPost, path, getEntitiesRequest)

if err != nil {
return nil, err
}
Expand Down Expand Up @@ -623,9 +625,6 @@ func (op Operations) CreateOrUpdateCategoryValue(name string, body *CategoryValu
categoryValueResponse := new(CategoryValueStatus)

err = op.client.Do(ctx, req, categoryValueResponse)
if err != nil {
return nil, err
}

return categoryValueResponse, nil
}
Expand Down Expand Up @@ -657,7 +656,7 @@ func (op Operations) GetCategoryValue(name string, value string) (*CategoryValue
return categoryValueStatusResponse, nil
}

/*DeleteCategoryValue Deletes a Category
/*DeleteCategoryValue Deletes a Category Value
* This operation submits a request to delete a op.
*
* @param name The name of the entity.
Expand Down Expand Up @@ -688,16 +687,131 @@ func (op Operations) GetCategoryQuery(query *CategoryQueryInput) (*CategoryQuery
path := "/categories/query"

req, err := op.client.NewRequest(ctx, http.MethodPost, path, query)
categoryQueryResponse := new(CategoryQueryResponse)

err = op.client.Do(ctx, req, categoryQueryResponse)

if err != nil {
return nil, err
}

categoryQueryResponse := new(CategoryQueryResponse)
return categoryQueryResponse, nil
}

/*CreateNetworkSecurityRule Creates a Network security rule
* This operation submits a request to create a Network security rule based on the input parameters.
*
* @param request
* @return *NetworkSecurityRuleIntentResponse
*/
func (op Operations) CreateNetworkSecurityRule(request *NetworkSecurityRuleIntentInput) (*NetworkSecurityRuleIntentResponse, error) {
ctx := context.TODO()

req, err := op.client.NewRequest(ctx, http.MethodPost, "/network_security_rules", request)
networkSecurityRuleIntentResponse := new(NetworkSecurityRuleIntentResponse)

err = op.client.Do(ctx, req, networkSecurityRuleIntentResponse)

err = op.client.Do(ctx, req, categoryQueryResponse)
if err != nil {
return nil, err
}

return categoryQueryResponse, nil
return networkSecurityRuleIntentResponse, nil
}

/*DeleteNetworkSecurityRule Deletes a Network security rule
* This operation submits a request to delete a Network security rule.
*
* @param UUID The UUID of the entity.
* @return void
*/
func (op Operations) DeleteNetworkSecurityRule(UUID string) error {
ctx := context.TODO()

path := fmt.Sprintf("/network_security_rules/%s", UUID)

req, err := op.client.NewRequest(ctx, http.MethodDelete, path, nil)
if err != nil {
return err
}

return op.client.Do(ctx, req, nil)
}

/*GetNetworkSecurityRule Gets a Network security rule
* This operation gets a Network security rule.
*
* @param UUID The UUID of the entity.
* @return *NetworkSecurityRuleIntentResponse
*/
func (op Operations) GetNetworkSecurityRule(UUID string) (*NetworkSecurityRuleIntentResponse, error) {
ctx := context.TODO()

path := fmt.Sprintf("/network_security_rules/%s", UUID)

req, err := op.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}

networkSecurityRuleIntentResponse := new(NetworkSecurityRuleIntentResponse)

err = op.client.Do(ctx, req, networkSecurityRuleIntentResponse)
if err != nil {
return nil, err
}

return networkSecurityRuleIntentResponse, nil
}

/*ListNetworkSecurityRule Gets all network security rules
* This operation gets a list of Network security rules, allowing for sorting and pagination. Note: Entities that have not been created successfully are not listed.
*
* @param getEntitiesRequest
* @return *NetworkSecurityRuleListIntentResponse
*/
func (op Operations) ListNetworkSecurityRule(getEntitiesRequest *ListMetadata) (*NetworkSecurityRuleListIntentResponse, error) {
ctx := context.TODO()
path := "/network_security_rules/list"

req, err := op.client.NewRequest(ctx, http.MethodPost, path, getEntitiesRequest)

if err != nil {
return nil, err
}

networkSecurityRuleListIntentResponse := new(NetworkSecurityRuleListIntentResponse)
err = op.client.Do(ctx, req, networkSecurityRuleListIntentResponse)
if err != nil {
return nil, err
}

return networkSecurityRuleListIntentResponse, nil
}

/*UpdateNetworkSecurityRule Updates a Network security rule
* This operation submits a request to update a Network security rule based on the input parameters.
*
* @param uuid The UUID of the entity.
* @param body
* @return void
*/
func (op Operations) UpdateNetworkSecurityRule(UUID string, body *NetworkSecurityRuleIntentInput) (*NetworkSecurityRuleIntentResponse, error) {
ctx := context.TODO()

path := fmt.Sprintf("/network_security_rules/%s", UUID)

req, err := op.client.NewRequest(ctx, http.MethodPut, path, body)
if err != nil {
return nil, err
}

networkSecurityRuleIntentResponse := new(NetworkSecurityRuleIntentResponse)

err = op.client.Do(ctx, req, networkSecurityRuleIntentResponse)
if err != nil {
return nil, err
}

return networkSecurityRuleIntentResponse, nil
}
Loading

0 comments on commit 449ac89

Please sign in to comment.