Skip to content

Commit

Permalink
merging part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
StigNorland committed Oct 29, 2024
1 parent a58c097 commit 4dc1263
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import static com.google.common.net.MediaType.CSV_UTF_8;

import static no.unit.nva.constants.Words.COMMA;
import static no.unit.nva.search.common.constant.Functions.decodeUTF;
import static no.unit.nva.search.common.constant.Functions.hasContent;
import static no.unit.nva.search.common.enums.ParameterKind.FUZZY_KEYWORD;

import static nva.commons.core.attempt.Try.attempt;
import static nva.commons.core.paths.UriWrapper.fromUri;

import static java.util.Objects.nonNull;
Expand All @@ -16,6 +19,9 @@
import no.unit.nva.search.common.QueryKeys;
import no.unit.nva.search.common.csv.ResourceCsvTransformer;
import no.unit.nva.search.common.enums.ParameterKey;
import no.unit.nva.search.common.enums.ValueEncoding;

import nva.commons.core.paths.UriWrapper;

import java.net.URI;
import java.util.List;
Expand Down Expand Up @@ -55,9 +61,25 @@ public HttpResponseFormatter(
this.offset = offset;
this.size = size;
this.facetPaths = facetPaths;
trimUriToIdentifierWhereApplicable(requestParameter);
this.queryKeys = requestParameter;
}

private void trimUriToIdentifierWhereApplicable(QueryKeys<K> requestParameter) {
if (nonNull(requestParameter)) {
requestParameter
.getSearchKeys()
.filter(this::isFuzzyKeyword)
.forEach(
key -> {
var value = decodedValue(requestParameter, key);
if (isUri(value)) {
requestParameter.set(key, uriToIdentifier(value));
}
});
}
}

public HttpResponseFormatter(SwsResponse response, MediaType mediaType) {
this(response, mediaType, null, 0, 0, Map.of(), null);
}
Expand Down Expand Up @@ -125,6 +147,25 @@ private URI nextResultsBySortKey(Map<String, String> requestParameter, URI gatew
return fromUri(gatewayUri).addQueryParameters(requestParameter).getUri();
}

private boolean isFuzzyKeyword(K key) {
return FUZZY_KEYWORD.equals(key.fieldType());
}

private boolean isUri(String decodedValue) {
return attempt(() -> URI.create(decodedValue).toURL()).isSuccess();
}

private String uriToIdentifier(String decodedValue) {
return UriWrapper.fromUri(decodedValue).getLastPathElement();
}

private <K extends Enum<K> & ParameterKey<K>> String decodedValue(
QueryKeys<K> parameters, K key) {
return key.valueEncoding() == ValueEncoding.NONE
? parameters.get(key).toString()
: decodeUTF(parameters.get(key).toString());
}

@Override
public String toString() {
return CSV_UTF_8.is(this.mediaType) ? toCsvText() : toPagedResponse().toJsonString();
Expand Down

0 comments on commit 4dc1263

Please sign in to comment.