Skip to content

Commit

Permalink
Make ResponseWrapper less confusing and better exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
s-frei committed Mar 26, 2024
1 parent d4664b3 commit 7e60175
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public interface ClientHelper extends ClassLogger {
default <T extends Track> Optional<String> getStreamUrl(TrackSearchClient<T> searchClient, T track,
Function<String, Integer> requestForCodeFunction,
final int retries) {

log().trace("Get stream url for: {}", track);
return tryToGetStreamUrl(searchClient, track, requestForCodeFunction, retries + INITIAL_TRY);
}
Expand All @@ -46,7 +45,7 @@ private <T extends Track> Optional<String> tryToGetStreamUrl(TrackSearchClient<T

try {
final String streamUrl = searchClient.getStreamUrl(track);
final int code = requestForCodeFunction.apply(streamUrl);
final Integer code = requestForCodeFunction.apply(streamUrl);
if (Client.successResponseCode(code))
return Optional.ofNullable(streamUrl);
else {
Expand Down
33 changes: 16 additions & 17 deletions src/main/java/io/sfrei/tracksearch/clients/setup/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.sfrei.tracksearch.clients.setup;

import io.sfrei.tracksearch.exceptions.TrackSearchException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.jetbrains.annotations.Nullable;
Expand Down Expand Up @@ -43,10 +44,17 @@ public static ResponseWrapper request(Call<ResponseWrapper> call) {
log.trace("Requesting: {}", url);
try {
final Response<ResponseWrapper> response = call.execute();
return getBody(response);

if (response.isSuccessful() && response.body() != null && response.body().hasContent()) {
return response.body();
}

return ResponseWrapper.empty(
new TrackSearchException(String.format("No response body (%s) requesting: %s", response.code(), url))
);

} catch (IOException e) {
logRequestException(url, e);
return ResponseWrapper.empty();
return ResponseWrapper.empty(requestException(url, e));
}
}

Expand All @@ -56,33 +64,24 @@ public ResponseWrapper requestURL(String url) {
try (final okhttp3.Response response = okHttpClient.newCall(request).execute()) {
return ResponseProviderFactory.wrapResponse(response.body());
} catch (IOException e) {
logRequestException(url, e);
return ResponseWrapper.empty(requestException(url, e));
}
return ResponseWrapper.empty();
}

public static boolean successResponseCode(int code) {
return code == OK || code == PARTIAL_CONTENT;
public static boolean successResponseCode(Integer code) {
return code != null && (code == OK || code == PARTIAL_CONTENT);
}

protected int requestAndGetCode(String url) {
protected Integer requestAndGetCode(String url) {
final Request request = new Request.Builder().url(url)
.header("connection", "close")
.header("range", "bytes=0-1")
.build();
try (final okhttp3.Response response = okHttpClient.newCall(request).execute()) {
return response.code();
} catch (IOException e) {
logRequestException(url, e);
return 418;
}
}

private static ResponseWrapper getBody(Response<ResponseWrapper> response) {
if (response.isSuccessful() && response.body() != null && response.body().hasContent()) {
return response.body();
return null;
}
return ResponseWrapper.of(response.raw().code(), null);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.sfrei.tracksearch.clients.setup;

import io.sfrei.tracksearch.exceptions.TrackSearchException;
import io.sfrei.tracksearch.utils.UserAgentUtility;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -52,8 +53,9 @@ private static void logResponseCode(String url, int code) {
log.error("Code: {} for request not successful '{}' ", code, url);
}

protected static void logRequestException(String url, IOException e) {
log.error("Failed to request '{}' cause: {}", url, e);
@NotNull
protected static TrackSearchException requestException(String url, IOException e) {
return new TrackSearchException(String.format("Failed requesting: %s", url), e);
}

@RequiredArgsConstructor
Expand Down Expand Up @@ -81,7 +83,7 @@ public Response intercept(Interceptor.Chain chain) throws IOException {
try {
response = chain.proceed(modifiedRequest);
} catch (IOException e) {
logRequestException(url, e);
log.error("Failed to requesting {}", url, e);
throw e;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.sfrei.tracksearch.clients.setup;

import io.sfrei.tracksearch.exceptions.TrackSearchException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -55,12 +56,12 @@ public static ResponseWrapper wrapResponse(ResponseBody responseBody) {
if (responseBody != null) {
try {
String body = new String(responseBody.string().getBytes(StandardCharsets.UTF_8));
return ResponseWrapper.of(Client.OK, body);
return ResponseWrapper.content(Client.OK, body);
} catch (IOException e) {
log.error("Cannot process response", e);
return ResponseWrapper.empty(new TrackSearchException("Cannot process response", e));
}
}
return ResponseWrapper.empty();
return ResponseWrapper.empty(new TrackSearchException("No response body"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@

package io.sfrei.tracksearch.clients.setup;

import io.sfrei.tracksearch.exceptions.ResponseException;
import io.sfrei.tracksearch.exceptions.TrackSearchException;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ResponseWrapper {

private int code;
private Integer code;

@Getter
private String content;

private TrackSearchException exception;

public boolean hasContent() {
return content != null;
}
Expand All @@ -40,18 +40,17 @@ public boolean isHttpCode(int code) {
return this.code == code;
}

public static ResponseWrapper empty() {
return new ResponseWrapper();
public static ResponseWrapper content(Integer code, @NonNull String content) {
return new ResponseWrapper(code, content, null);
}

public String getContentOrThrow() throws TrackSearchException {
if (hasContent())
return content;
throw new ResponseException("No content - code: " + code);
public static ResponseWrapper empty(TrackSearchException exception) {
return new ResponseWrapper(null, null, exception);
}

public String getContent() {
return this.content;
public String getContentOrThrow() throws TrackSearchException {
if (hasContent()) return content;
throw exception;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
public class UserAgentUtility {

/**
* List obtained from <link>https://gist.github.com/fijimunkii/952acac988f2d25bef7e0284bc63c406</link>
* List obtained from <link><a href="https://gist.github.com/fijimunkii/952acac988f2d25bef7e0284bc63c406">...</a></link>
*/
private static final String[] USER_AGENTS = {
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/io/sfrei/tracksearch/clients/ClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public void getStreamUrl(Track track) {
.isNotEmpty();

final int code = requestAndGetCode(streamUrl);
assertNotEquals(FORBIDDEN, code);
assertTrue(Client.successResponseCode(code));
}

}

0 comments on commit 7e60175

Please sign in to comment.