github.com/jaylevin/jenkins-library@v1.230.4/pkg/apim/APIMUtility.go (about) 1 package apim 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "github.com/SAP/jenkins-library/pkg/cpi" 8 piperhttp "github.com/SAP/jenkins-library/pkg/http" 9 "github.com/SAP/jenkins-library/pkg/xsuaa" 10 "github.com/pkg/errors" 11 ) 12 13 //Utils for apim 14 type Utils interface { 15 InitAPIM() error 16 IsPayloadJSON() bool 17 } 18 19 //Bundle struct 20 type Bundle struct { 21 APIServiceKey, Host, Payload string 22 Client piperhttp.Sender 23 } 24 25 //InitAPIM() fumnction initialize APIM bearer token for API access 26 func (apim *Bundle) InitAPIM() error { 27 serviceKey, err := cpi.ReadCpiServiceKey(apim.APIServiceKey) 28 if err != nil { 29 return err 30 } 31 apim.Host = serviceKey.OAuth.Host 32 httpClient := apim.Client 33 clientOptions := piperhttp.ClientOptions{} 34 x := xsuaa.XSUAA{ 35 OAuthURL: serviceKey.OAuth.OAuthTokenProviderURL, 36 ClientID: serviceKey.OAuth.ClientID, 37 ClientSecret: serviceKey.OAuth.ClientSecret, 38 } 39 token, tokenErr := x.GetBearerToken() 40 41 if tokenErr != nil { 42 return errors.Wrap(tokenErr, "failed to fetch Bearer Token") 43 } 44 clientOptions.Token = fmt.Sprintf("Bearer %s", token.AccessToken) 45 httpClient.SetOptions(clientOptions) 46 return nil 47 } 48 49 //IsJSON checks given string is valid json or not 50 func (apim *Bundle) IsPayloadJSON() bool { 51 var js json.RawMessage 52 return json.Unmarshal([]byte(apim.Payload), &js) == nil 53 }