1616
1717package uk .gov .hmrc .voabar .services
1818
19- import org .apache .pekko .stream .Materializer
20- import play .api .http .Status
21- import play .api .libs .ws .ahc .{AhcConfigBuilder , AhcWSClient , StandaloneAhcWSClient }
22- import play .api .libs .ws .{WSAuthScheme , WSClient , WSResponse , writeableOf_urlEncodedForm }
23- import play .api .{Configuration , Logging }
24- import play .shaded .ahc .org .asynchttpclient .proxy .{ProxyServer , ProxyType }
25- import play .shaded .ahc .org .asynchttpclient .{AsyncHttpClient , DefaultAsyncHttpClient , Realm }
26- import uk .gov .hmrc .http .UnauthorizedException
19+ import play .api .Logging
20+ import play .api .http .HeaderNames .AUTHORIZATION
21+ import play .api .http .Status .{INTERNAL_SERVER_ERROR , OK , UNAUTHORIZED }
22+ import play .api .libs .ws .writeableOf_urlEncodedForm
23+ import uk .gov .hmrc .http .HttpReads .Implicits .*
24+ import uk .gov .hmrc .http .client .HttpClientV2
25+ import uk .gov .hmrc .http .{HeaderCarrier , HttpResponse , StringContextOps , UnauthorizedException }
2726import uk .gov .hmrc .play .bootstrap .config .ServicesConfig
2827
29- import java .util .Collections
28+ import java .net .URL
29+ import java .nio .charset .StandardCharsets .UTF_8
30+ import java .util .Base64
3031import javax .inject .{Inject , Singleton }
3132import scala .concurrent .duration .*
3233import scala .concurrent .{ExecutionContext , Future }
3334import scala .language .postfixOps
3435import scala .util .{Failure , Success , Try }
3536import scala .xml .XML
3637
37- // TODO: use uk.gov.hmrc.http.client.HttpClientV2 and method .withProxy
3838@ Singleton
3939class EbarsClientV2 @ Inject () (
40- servicesConfig : ServicesConfig ,
41- configuration : Configuration
42- )(implicit ec : ExecutionContext ,
43- materialize : Materializer
44- ) extends Logging
45- with Status {
40+ httpClientV2 : HttpClientV2 ,
41+ servicesConfig : ServicesConfig
42+ )(implicit ec : ExecutionContext
43+ ) extends Logging :
4644
47- private val voaEbarsBaseUrl = servicesConfig.baseUrl(" voa-ebars" )
48- private val xmlFileUploadUrl = s " $voaEbarsBaseUrl/ebars_dmz_pres_ApplicationWeb/uploadXmlSubmission "
49- private val timeout = 120 seconds
45+ private val voaEbarsBaseUrl : String = servicesConfig.baseUrl(" voa-ebars" )
46+ private val xmlFileUploadURL : URL = url " $voaEbarsBaseUrl/ebars_dmz_pres_ApplicationWeb/uploadXmlSubmission "
47+ private val timeout : FiniteDuration = 120 seconds
5048
51- private val ws : WSClient = {
52- val proxyAhcConfig = configuration.getOptional[Boolean ](" proxy.enabled" ) flatMap {
53- case true => Some {
54- val proxyHost = configuration.get[String ](" proxy.host" )
55- val proxyPort = configuration.get[Int ](" proxy.port" )
56- val proxyUsername = configuration.get[String ](" proxy.username" )
57- val proxyPassword = configuration.get[String ](" proxy.password" )
58- val realm = new Realm .Builder (proxyUsername, proxyPassword)
59- .setScheme(Realm .AuthScheme .BASIC )
60- .setUsePreemptiveAuth(true )
61- .build()
62-
63- new AhcConfigBuilder ().modifyUnderlying {
64- _.setProxyServer(new ProxyServer (proxyHost, proxyPort, proxyPort, realm, Collections .emptyList(), ProxyType .HTTP ))
65- }.build()
66- }
67- case _ => None
68- }
69-
70- val clientConfig = proxyAhcConfig.getOrElse(new AhcConfigBuilder ().build())
71- val asyncHttpClient : AsyncHttpClient = new DefaultAsyncHttpClient (clientConfig)
72- val standaloneClient : StandaloneAhcWSClient = new StandaloneAhcWSClient (asyncHttpClient)
73- new AhcWSClient (standaloneClient)
74- }
49+ private def basicAuth (clientId : String , clientSecret : String ): String =
50+ val encodedCredentials = Base64 .getEncoder.encodeToString(s " $clientId: $clientSecret" .getBytes(UTF_8 ))
51+ s " Basic $encodedCredentials"
7552
7653 def uploadXMl (username : String , password : String , xml : String , attempt : Int ): Future [Try [Int ]] =
77- ws.url(xmlFileUploadUrl)
78- .withAuth(username, password, WSAuthScheme .BASIC )
79- .withRequestTimeout(timeout)
80- .post(Map (" xml" -> Seq (xml)))
54+ httpClientV2.post(xmlFileUploadURL)(using HeaderCarrier ())
55+ .setHeader(AUTHORIZATION -> basicAuth(username, password))
56+ .withBody(Map (" xml" -> Seq (xml)))
57+ .withProxy
58+ .transform(_.withRequestTimeout(timeout))
59+ .execute[HttpResponse ]
8160 .map(processResponse(attempt))
8261
83- private def processResponse (attempt : Int )(response : WSResponse ): Try [Int ] = {
62+ private def processResponse (attempt : Int )(response : HttpResponse ): Try [Int ] =
8463 logger.trace(s " Response : $response" )
8564 response.status match {
86- case Status . OK => parseOkResponse(response, attempt)
87- case Status . UNAUTHORIZED => Failure (new UnauthorizedException (" UNAUTHORIZED" ))
88- case status =>
65+ case OK => parseOkResponse(response, attempt)
66+ case UNAUTHORIZED => Failure (new UnauthorizedException (" UNAUTHORIZED" ))
67+ case status =>
8968 logger.warn(s " Couldn't send BA Reports. status: $status\n ${response.body}" )
90- Failure (EbarsApiError (status, s " ${response.statusText }. attempt: $attempt" ))
69+ Failure (EbarsApiError (status, s " ${response.status }. attempt: $attempt" ))
9170 }
92- }
9371
94- private def parseOkResponse (response : WSResponse , attempt : Int ): Try [Int ] = {
72+ private def parseOkResponse (response : HttpResponse , attempt : Int ): Try [Int ] =
9573 val body = response.body
9674 if body.contains(" 401 Unauthorized" ) then
9775 Failure (new UnauthorizedException (" UNAUTHORIZED" ))
@@ -104,14 +82,11 @@ class EbarsClientV2 @Inject() (
10482 case " error" =>
10583 val errorDetail = (responseXML \ " message" ).text
10684 logger.warn(s " Couldn't send BA Reports. error: $errorDetail" )
107- Failure (EbarsApiError (OK , s " $errorDetail. attempt: $attempt" ))
85+ Failure (EbarsApiError (INTERNAL_SERVER_ERROR , s " $errorDetail. attempt: $attempt" ))
10886 }
10987 } getOrElse {
11088 logger.warn(s " Parsing eBars response failed. Body: \n $body" )
111- Failure (EbarsApiError (OK , s " Parsing eBars response failed. attempt: $attempt" ))
89+ Failure (EbarsApiError (INTERNAL_SERVER_ERROR , s " Parsing eBars response failed. attempt: $attempt" ))
11290 }
113- }
114-
115- }
11691
11792case class EbarsApiError (status : Int , message : String ) extends RuntimeException (s " $status. $message" )
0 commit comments