Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / github.com / Azure / go-autorest / autorest / utility.go
1 package autorest
2
3 // Copyright 2017 Microsoft Corporation
4 //
5 //  Licensed under the Apache License, Version 2.0 (the "License");
6 //  you may not use this file except in compliance with the License.
7 //  You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 //  Unless required by applicable law or agreed to in writing, software
12 //  distributed under the License is distributed on an "AS IS" BASIS,
13 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 //  See the License for the specific language governing permissions and
15 //  limitations under the License.
16
17 import (
18         "bytes"
19         "encoding/json"
20         "encoding/xml"
21         "fmt"
22         "io"
23         "net"
24         "net/http"
25         "net/url"
26         "reflect"
27         "strings"
28
29         "github.com/Azure/go-autorest/autorest/adal"
30 )
31
32 // EncodedAs is a series of constants specifying various data encodings
33 type EncodedAs string
34
35 const (
36         // EncodedAsJSON states that data is encoded as JSON
37         EncodedAsJSON EncodedAs = "JSON"
38
39         // EncodedAsXML states that data is encoded as Xml
40         EncodedAsXML EncodedAs = "XML"
41 )
42
43 // Decoder defines the decoding method json.Decoder and xml.Decoder share
44 type Decoder interface {
45         Decode(v interface{}) error
46 }
47
48 // NewDecoder creates a new decoder appropriate to the passed encoding.
49 // encodedAs specifies the type of encoding and r supplies the io.Reader containing the
50 // encoded data.
51 func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder {
52         if encodedAs == EncodedAsJSON {
53                 return json.NewDecoder(r)
54         } else if encodedAs == EncodedAsXML {
55                 return xml.NewDecoder(r)
56         }
57         return nil
58 }
59
60 // CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy
61 // is especially useful if there is a chance the data will fail to decode.
62 // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v
63 // is the decoding destination.
64 func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) {
65         b := bytes.Buffer{}
66         return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v)
67 }
68
69 // TeeReadCloser returns a ReadCloser that writes to w what it reads from rc.
70 // It utilizes io.TeeReader to copy the data read and has the same behavior when reading.
71 // Further, when it is closed, it ensures that rc is closed as well.
72 func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser {
73         return &teeReadCloser{rc, io.TeeReader(rc, w)}
74 }
75
76 type teeReadCloser struct {
77         rc io.ReadCloser
78         r  io.Reader
79 }
80
81 func (t *teeReadCloser) Read(p []byte) (int, error) {
82         return t.r.Read(p)
83 }
84
85 func (t *teeReadCloser) Close() error {
86         return t.rc.Close()
87 }
88
89 func containsInt(ints []int, n int) bool {
90         for _, i := range ints {
91                 if i == n {
92                         return true
93                 }
94         }
95         return false
96 }
97
98 func escapeValueStrings(m map[string]string) map[string]string {
99         for key, value := range m {
100                 m[key] = url.QueryEscape(value)
101         }
102         return m
103 }
104
105 func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string {
106         mapOfStrings := make(map[string]string)
107         for key, value := range mapOfInterface {
108                 mapOfStrings[key] = ensureValueString(value)
109         }
110         return mapOfStrings
111 }
112
113 func ensureValueString(value interface{}) string {
114         if value == nil {
115                 return ""
116         }
117         switch v := value.(type) {
118         case string:
119                 return v
120         case []byte:
121                 return string(v)
122         default:
123                 return fmt.Sprintf("%v", v)
124         }
125 }
126
127 // MapToValues method converts map[string]interface{} to url.Values.
128 func MapToValues(m map[string]interface{}) url.Values {
129         v := url.Values{}
130         for key, value := range m {
131                 x := reflect.ValueOf(value)
132                 if x.Kind() == reflect.Array || x.Kind() == reflect.Slice {
133                         for i := 0; i < x.Len(); i++ {
134                                 v.Add(key, ensureValueString(x.Index(i)))
135                         }
136                 } else {
137                         v.Add(key, ensureValueString(value))
138                 }
139         }
140         return v
141 }
142
143 // AsStringSlice method converts interface{} to []string. This expects a
144 //that the parameter passed to be a slice or array of a type that has the underlying
145 //type a string.
146 func AsStringSlice(s interface{}) ([]string, error) {
147         v := reflect.ValueOf(s)
148         if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
149                 return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.")
150         }
151         stringSlice := make([]string, 0, v.Len())
152
153         for i := 0; i < v.Len(); i++ {
154                 stringSlice = append(stringSlice, v.Index(i).String())
155         }
156         return stringSlice, nil
157 }
158
159 // String method converts interface v to string. If interface is a list, it
160 // joins list elements using the separator. Note that only sep[0] will be used for
161 // joining if any separator is specified.
162 func String(v interface{}, sep ...string) string {
163         if len(sep) == 0 {
164                 return ensureValueString(v)
165         }
166         stringSlice, ok := v.([]string)
167         if ok == false {
168                 var err error
169                 stringSlice, err = AsStringSlice(v)
170                 if err != nil {
171                         panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err))
172                 }
173         }
174         return ensureValueString(strings.Join(stringSlice, sep[0]))
175 }
176
177 // Encode method encodes url path and query parameters.
178 func Encode(location string, v interface{}, sep ...string) string {
179         s := String(v, sep...)
180         switch strings.ToLower(location) {
181         case "path":
182                 return pathEscape(s)
183         case "query":
184                 return queryEscape(s)
185         default:
186                 return s
187         }
188 }
189
190 func pathEscape(s string) string {
191         return strings.Replace(url.QueryEscape(s), "+", "%20", -1)
192 }
193
194 func queryEscape(s string) string {
195         return url.QueryEscape(s)
196 }
197
198 // ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't).
199 // This is mainly useful for long-running operations that use the Azure-AsyncOperation
200 // header, so we change the initial PUT into a GET to retrieve the final result.
201 func ChangeToGet(req *http.Request) *http.Request {
202         req.Method = "GET"
203         req.Body = nil
204         req.ContentLength = 0
205         req.Header.Del("Content-Length")
206         return req
207 }
208
209 // IsTokenRefreshError returns true if the specified error implements the TokenRefreshError
210 // interface.  If err is a DetailedError it will walk the chain of Original errors.
211 func IsTokenRefreshError(err error) bool {
212         if _, ok := err.(adal.TokenRefreshError); ok {
213                 return true
214         }
215         if de, ok := err.(DetailedError); ok {
216                 return IsTokenRefreshError(de.Original)
217         }
218         return false
219 }
220
221 // IsTemporaryNetworkError returns true if the specified error is a temporary network error or false
222 // if it's not.  If the error doesn't implement the net.Error interface the return value is true.
223 func IsTemporaryNetworkError(err error) bool {
224         if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
225                 return true
226         }
227         return false
228 }