Skip to content
38 changes: 35 additions & 3 deletions grails-app/services/au/org/ala/ecodata/forms/EcpWebService.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,37 @@ class EcpWebService {
}
}

/**
* This method is used when the response is expected to be a stream, e.g. for downloading files.
* It returns a Map with keys [statusCode: <http status code>, error: <error message if applicable>]
* The supplied outputStream will be written to with the response from the web service if the call is successful.
* The caller is responsible for closing the outputStream.
*/
Map readToStream(String url, OutputStream outputStream, boolean includeUserId = true, Integer timeout = null) {
HttpURLConnection conn = null
Map resp = [:]
try {
conn = configureConnection(url, includeUserId, timeout)
try (InputStream inputStream = conn.inputStream) {
outputStream << inputStream
}
resp = [statusCode: conn.responseCode]

} catch (SocketTimeoutException e) {
resp = [error: "Timed out calling web service. URL= ${url}.", statusCode: conn?.responseCode?:""]
log.error "Timed out calling web service. URL= ${url}.", e
} catch (SocketException se) {
resp = [error: "Timed out calling web service. URL= ${url}.", statusCode: conn?.responseCode?:""]

log.warn "Socket connection closed. ${se.getMessage()} URL= ${url}.", se
} catch (Exception e) {
resp = [error: "Timed out calling web service. URL= ${url}.", statusCode: conn?.responseCode?:""]

log.error "Failed calling web service. ${e.getClass()} ${e.getMessage()} URL= ${url}.", e
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling disconnect is only recommended if more calls to the server are not anticipated. Almost all requests are to ecodata and we don't want to close the socket here.

Comment on lines +109 to +127
}
resp
}

Map getString(String url, boolean includeAuth) {
URLConnection conn = null
Map resp = [:]
Expand All @@ -104,7 +135,7 @@ class EcpWebService {
resp.statusCode = conn.responseCode
} catch (SocketTimeoutException e) {
resp.error = "Timed out calling web service. URL= ${url}."
resp.statusCode = HttpStatus.CONNECTION_TIMED_OUT
resp.statusCode = HttpStatus.SC_GATEWAY_TIMEOUT
log.warn resp.error
} catch (SocketException se) {
resp.error = "Socket connection closed. ${se.getMessage()} URL= ${url}."
Expand Down Expand Up @@ -607,9 +638,10 @@ class EcpWebService {
}

def user = userService.getUser()
String userId = user.userId
String userIdHeader = grailsApplication.config.getProperty('app.http.header.userId')

if (user) {
String userIdHeader = grailsApplication.config.getProperty('app.http.header.userId')
String userId = user.userId
requestBuilder.addHeader(userIdHeader, userId)
} else {
log.warn("No user associated with request: ${url}")
Expand Down
Loading