github.com/jaylevin/jenkins-library@v1.230.4/cmd/apiProxyDownload.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "net/http" 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/log" 10 "github.com/SAP/jenkins-library/pkg/telemetry" 11 "github.com/pkg/errors" 12 ) 13 14 func apiProxyDownload(config apiProxyDownloadOptions, telemetryData *telemetry.CustomData) { 15 // Utils can be used wherever the command.ExecRunner interface is expected. 16 // It can also be used for example as a mavenExecRunner. 17 httpClient := &piperhttp.Client{} 18 19 // For HTTP calls import piperhttp "github.com/SAP/jenkins-library/pkg/http" 20 // and use a &piperhttp.Client{} in a custom system 21 // Example: step checkmarxExecuteScan.go 22 23 // Error situations should be bubbled up until they reach the line below which will then stop execution 24 // through the log.Entry().Fatal() call leading to an os.Exit(1) in the end. 25 err := runApiProxyDownload(&config, telemetryData, httpClient) 26 if err != nil { 27 log.Entry().WithError(err).Fatal("step execution failed") 28 } 29 } 30 31 func runApiProxyDownload(config *apiProxyDownloadOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) error { 32 clientOptions := piperhttp.ClientOptions{} 33 header := make(http.Header) 34 header.Add("Accept", "application/zip") 35 serviceKey, err := cpi.ReadCpiServiceKey(config.APIServiceKey) 36 if err != nil { 37 return err 38 } 39 downloadArtifactURL := fmt.Sprintf("%s/apiportal/api/1.0/Transport.svc/APIProxies?name=%s", serviceKey.OAuth.Host, config.APIProxyName) 40 tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, 41 Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} 42 token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) 43 if err != nil { 44 return errors.Wrap(err, "failed to fetch Bearer Token") 45 } 46 clientOptions.Token = fmt.Sprintf("Bearer %s", token) 47 httpClient.SetOptions(clientOptions) 48 httpMethod := http.MethodGet 49 downloadResp, httpErr := httpClient.SendRequest(httpMethod, downloadArtifactURL, nil, header, nil) 50 if httpErr != nil { 51 return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, downloadArtifactURL) 52 } 53 if downloadResp == nil { 54 return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) 55 } 56 failureMessage := "Failed to download API Proxy artefact" 57 httpFileDownloadRequestParameters := cpi.HttpFileDownloadRequestParameters{ErrMessage: failureMessage, FileDownloadPath: config.DownloadPath, Response: downloadResp} 58 return cpi.HttpCPIUtils.HandleHTTPFileDownloadResponse(httpFileDownloadRequestParameters) 59 }