use of javax.ws.rs.core.HttpHeaders.ACCEPT in project mod-oai-pmh by folio-org.
the class MarcWithHoldingsRequestHelper method enrichInstances.
private Future<List<JsonObject>> enrichInstances(List<JsonObject> result, Request request) {
Map<String, JsonObject> instances = result.stream().collect(LinkedHashMap::new, (map, instance) -> map.put(instance.getString(INSTANCE_ID_FIELD_NAME), instance), Map::putAll);
Promise<List<JsonObject>> promise = Promise.promise();
var webClient = WebClientProvider.getWebClient();
var httpRequest = webClient.postAbs(request.getOkapiUrl() + INVENTORY_ITEMS_AND_HOLDINGS_ENDPOINT);
if (request.getOkapiUrl().contains("https:")) {
httpRequest.ssl(true);
}
httpRequest.putHeader(OKAPI_TOKEN, request.getOkapiToken());
httpRequest.putHeader(OKAPI_TENANT, TenantTool.tenantId(request.getOkapiHeaders()));
httpRequest.putHeader(ACCEPT, APPLICATION_JSON);
httpRequest.putHeader(CONTENT_TYPE, APPLICATION_JSON);
JsonObject entries = new JsonObject();
entries.put(INSTANCE_IDS_ENRICH_PARAM_NAME, new JsonArray(new ArrayList<>(instances.keySet())));
entries.put(SKIP_SUPPRESSED_FROM_DISCOVERY_RECORDS, isSkipSuppressed(request));
Promise<Boolean> responseChecked = Promise.promise();
var jsonParser = new OaiPmhJsonParser().objectValueMode();
jsonParser.handler(event -> {
JsonObject itemsAndHoldingsFields = event.objectValue();
String instanceId = itemsAndHoldingsFields.getString(INSTANCE_ID_FIELD_NAME);
JsonObject instance = instances.get(instanceId);
if (instance != null) {
enrichDiscoverySuppressed(itemsAndHoldingsFields, instance);
instance.put(RecordMetadataManager.ITEMS_AND_HOLDINGS_FIELDS, itemsAndHoldingsFields);
// case when no items
if (itemsAndHoldingsFields.getJsonArray(ITEMS).isEmpty()) {
enrichOnlyEffectiveLocationEffectiveCallNumberFromHoldings(instance);
} else {
adjustItems(instance);
}
} else {
logger.info("Instance with instanceId {} wasn't in the request.", instanceId);
}
});
jsonParser.exceptionHandler(throwable -> responseChecked.future().onSuccess(invalidResponseReceivedAndProcessed -> {
if (invalidResponseReceivedAndProcessed) {
return;
}
logger.error("Error has been occurred at JsonParser while reading data from items-and-holdings response. Message:{}", throwable.getMessage(), throwable);
promise.fail(throwable);
}));
httpRequest.as(BodyCodec.jsonStream(jsonParser)).sendBuffer(entries.toBuffer()).onSuccess(response -> {
switch(response.statusCode()) {
case 200:
responseChecked.complete(false);
break;
case 403:
{
String errorMsg = getErrorFromStorageMessage(INVENTORY_STORAGE, request.getOkapiUrl() + INVENTORY_ITEMS_AND_HOLDINGS_ENDPOINT, ENRICH_INSTANCES_MISSED_PERMISSION);
logger.error(errorMsg);
promise.fail(new IllegalStateException(errorMsg));
responseChecked.complete(true);
break;
}
default:
{
String errorFromStorageMessage = getErrorFromStorageMessage(INVENTORY_STORAGE, request.getOkapiUrl() + INVENTORY_ITEMS_AND_HOLDINGS_ENDPOINT, response.statusMessage());
String errorMessage = errorFromStorageMessage + response.statusCode();
logger.error(errorMessage);
promise.fail(new IllegalStateException(errorFromStorageMessage));
responseChecked.complete(true);
}
}
promise.complete(new ArrayList<>(instances.values()));
}).onFailure(e -> {
logger.error(e.getMessage());
promise.fail(e);
});
return promise.future();
}
use of javax.ws.rs.core.HttpHeaders.ACCEPT in project fcrepo by fcrepo.
the class FedoraVersioningIT method verifyTimemapResponse.
/**
* Verify an application/link-format TimeMap response.
*
* @param uri The full URI of the Original Resource.
* @param id The path of the Original Resource.
* @param mementoDateTime Array of all the RFC-1123 datetimes for all the mementos.
* @param rangeStart RFC-1123 datetime of the first memento.
* @param rangeEnd RFC-1123 datetime of the last memento.
* @throws Exception on HTTP request error
*/
private void verifyTimemapResponse(final String uri, final String id, final String[] mementoDateTime, final String rangeStart, final String rangeEnd) throws Exception {
final String ldpcvUri = uri + "/" + FCR_VERSIONS;
final var expectedLinksOther = new ArrayList<Link>();
final var expectedLinksMemento = new ArrayList<Link>();
expectedLinksOther.add(Link.fromUri(uri).rel("original").build());
expectedLinksOther.add(Link.fromUri(uri).rel("timegate").build());
expectedLinksOther.sort(Comparator.comparing(Link::toString));
final var expectedSelfLinkBuilder = Link.fromUri(ldpcvUri).rel("self").type(APPLICATION_LINK_FORMAT);
if (rangeStart != null && rangeEnd != null) {
expectedSelfLinkBuilder.param("from", rangeStart).param("until", rangeEnd);
}
final var expectedSelfLink = expectedSelfLinkBuilder.build();
if (mementoDateTime != null) {
for (final String memento : mementoDateTime) {
final TemporalAccessor instant = MEMENTO_RFC_1123_FORMATTER.parse(memento);
expectedLinksMemento.add(Link.fromUri(ldpcvUri + "/" + MEMENTO_LABEL_FORMATTER.format(instant)).rel("memento").param("datetime", memento).build());
}
}
expectedLinksMemento.sort(Comparator.comparing(Link::toString));
final HttpGet httpGet = getObjMethod(id + "/" + FCR_VERSIONS);
httpGet.setHeader("Accept", APPLICATION_LINK_FORMAT);
try (final CloseableHttpResponse response = execute(httpGet)) {
assertEquals("Didn't get a OK response!", OK.getStatusCode(), getStatus(response));
// verify headers in link format.
verifyTimeMapHeaders(response, uri);
final var responseBody = EntityUtils.toString(response.getEntity());
final List<String> bodyList = asList(responseBody.split("," + System.lineSeparator()));
// the links from the body are not
Link selfLink = null;
final var mementoLinks = new ArrayList<Link>();
final var otherLinks = new ArrayList<Link>();
final var allLinks = bodyList.stream().map(String::trim).filter(t -> !t.isEmpty()).sorted(Comparator.naturalOrder()).map(Link::valueOf).collect(Collectors.toList());
for (final var link : allLinks) {
if ("memento".equals(link.getRel())) {
mementoLinks.add(link);
} else if ("self".equals(link.getRel())) {
selfLink = link;
} else {
otherLinks.add(link);
}
}
assertSelfLink(expectedSelfLink, selfLink);
assertEquals(expectedLinksOther, otherLinks);
assertEquals(expectedLinksMemento.size(), mementoLinks.size());
for (var i = 0; i < expectedLinksMemento.size(); i++) {
assertMementoLink(expectedLinksMemento.get(i), mementoLinks.get(i));
}
}
}
use of javax.ws.rs.core.HttpHeaders.ACCEPT in project mod-oai-pmh by folio-org.
the class MarcWithHoldingsRequestHelper method buildInventoryQuery.
private HttpRequest<Buffer> buildInventoryQuery(Request request) {
Map<String, String> paramMap = new HashMap<>();
Date date = convertStringToDate(request.getFrom(), false, false);
if (date != null) {
paramMap.put(START_DATE_PARAM_NAME, dateFormat.format(date));
}
date = convertStringToDate(request.getUntil(), true, false);
if (date != null) {
paramMap.put(END_DATE_PARAM_NAME, dateFormat.format(date));
}
paramMap.put(DELETED_RECORD_SUPPORT_PARAM_NAME, String.valueOf(RepositoryConfigurationUtil.isDeletedRecordsEnabled(request.getRequestId())));
paramMap.put(SKIP_SUPPRESSED_FROM_DISCOVERY_RECORDS, String.valueOf(isSkipSuppressed(request)));
final String params = paramMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
String inventoryQuery = format("%s%s?%s", request.getOkapiUrl(), INVENTORY_UPDATED_INSTANCES_ENDPOINT, params);
logger.debug("Sending request to {}", inventoryQuery);
final HttpRequest<Buffer> httpRequest = WebClientProvider.getWebClientToDownloadInstances().getAbs(inventoryQuery);
httpRequest.putHeader(OKAPI_TOKEN, request.getOkapiToken());
httpRequest.putHeader(OKAPI_TENANT, TenantTool.tenantId(request.getOkapiHeaders()));
httpRequest.putHeader(ACCEPT, APPLICATION_JSON);
if (request.getOkapiUrl().contains("https")) {
httpRequest.ssl(true);
}
return httpRequest;
}
Aggregations