}
/**
+ * If an exception is not thrown, the response needs to be closed by either calling close() directly, or closing the
+ * body content's stream/reader.
* @throws IllegalStateException if the request could not be executed due to
* a connectivity problem or timeout. Because networks can
* fail during an exchange, it is possible that the remote server
private void failIfUnauthorized(WsResponse response) {
int code = response.code();
if (code == HTTP_UNAUTHORIZED) {
+ response.close();
if (hasCredentials) {
// credentials are not valid
throw MessageException.of(format("Not authorized. Please check the properties %s and %s.",
}
if (code == HTTP_FORBIDDEN || code == HTTP_BAD_REQUEST) {
// SONAR-4397 Details are in response content
+ response.close();
throw MessageException.of(tryParseAsJsonError(response.content()));
}
response.failIfNotSuccessful();
@Override
public GlobalRepositories load() {
GetRequest getRequest = new GetRequest(BATCH_GLOBAL_URL);
- Reader reader = wsClient.call(getRequest).contentReader();
String str;
- try {
+ try (Reader reader = wsClient.call(getRequest).contentReader()) {
str = IOUtils.toString(reader);
} catch (IOException e) {
throw new IllegalStateException(e);
import org.sonarqube.ws.WsBatch.WsProjectResponse.Settings;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
+import org.sonarqube.ws.client.WsResponse;
public class DefaultProjectRepositoriesLoader implements ProjectRepositoriesLoader {
private static final Logger LOG = LoggerFactory.getLogger(DefaultProjectRepositoriesLoader.class);
@Override
public ProjectRepositories load(String projectKey, boolean issuesMode) {
- try {
- GetRequest request = new GetRequest(getUrl(projectKey, issuesMode));
- InputStream is = wsClient.call(request).contentStream();
+ GetRequest request = new GetRequest(getUrl(projectKey, issuesMode));
+ try (WsResponse response = wsClient.call(request)) {
+ InputStream is = response.contentStream();
return processStream(is, projectKey);
} catch (RuntimeException e) {
if (shouldThrow(e)) {
@Override
public WsResponse failIfNotSuccessful() {
if (!isSuccessful()) {
+ close();
throw new HttpException(requestUrl(), code());
}
return this;
public boolean hasContent() {
return code() != HTTP_NO_CONTENT;
}
+
+ @Override
+ public void close() {
+ // override if needed
+ }
}
private RuntimeException fail(Exception e) {
throw new IllegalStateException("Fail to read response of " + requestUrl(), e);
}
+
+ /**
+ * Equivalent to closing contentReader or contentStream.
+ */
+ @Override
+ public void close() {
+ okResponse.close();
+ }
}
*/
package org.sonarqube.ws.client;
+import java.io.Closeable;
import java.io.InputStream;
import java.io.Reader;
/**
* @since 5.3
*/
-public interface WsResponse {
+public interface WsResponse extends Closeable {
/**
* The absolute requested URL
Reader contentReader();
String content();
+
+ @Override
+ void close();
}