use of org.folio.inventory.common.Context in project mod-inventory by folio-org.
the class ReplaceInstanceEventHandlerTest method shouldReplaceExistingPrecedingTitleOnInstanceUpdate.
@Test
public void shouldReplaceExistingPrecedingTitleOnInstanceUpdate() throws InterruptedException, ExecutionException {
JsonObject existingPrecedingTitle = new JsonObject().put("id", UUID.randomUUID().toString()).put(TITLE_KEY, "Butterflies in the snow");
JsonObject precedingSucceedingTitles = new JsonObject().put(PRECEDING_SUCCEEDING_TITLES_KEY, new JsonArray().add(existingPrecedingTitle));
when(mockedClient.get(anyString())).thenReturn(CompletableFuture.completedFuture(createResponse(HttpStatus.SC_OK, precedingSucceedingTitles.encode())));
String instanceTypeId = UUID.randomUUID().toString();
String title = "titleValue";
Reader fakeReader = Mockito.mock(Reader.class);
when(fakeReader.read(any(MappingRule.class))).thenReturn(StringValue.of(instanceTypeId), StringValue.of(title));
when(fakeReaderFactory.createReader()).thenReturn(fakeReader);
when(storage.getInstanceCollection(any())).thenReturn(instanceRecordCollection);
MappingManager.registerReaderFactory(fakeReaderFactory);
MappingManager.registerWriterFactory(new InstanceWriterFactory());
HashMap<String, String> context = new HashMap<>();
Record record = new Record().withParsedRecord(new ParsedRecord().withContent(PARSED_CONTENT));
context.put(MARC_BIBLIOGRAPHIC.value(), Json.encode(record));
context.put(INSTANCE.value(), new JsonObject().put("id", UUID.randomUUID().toString()).put("hrid", UUID.randomUUID().toString()).put("_version", INSTANCE_VERSION).encode());
DataImportEventPayload dataImportEventPayload = new DataImportEventPayload().withEventType(DI_INVENTORY_INSTANCE_CREATED.value()).withContext(context).withCurrentNode(profileSnapshotWrapper.getChildSnapshotWrappers().get(0)).withTenant(TENANT_ID).withOkapiUrl(mockServer.baseUrl()).withToken(TOKEN).withJobExecutionId(UUID.randomUUID().toString());
;
CompletableFuture<DataImportEventPayload> future = replaceInstanceEventHandler.handle(dataImportEventPayload);
DataImportEventPayload actualDataImportEventPayload = future.get();
assertEquals(DI_INVENTORY_INSTANCE_UPDATED.value(), actualDataImportEventPayload.getEventType());
assertNotNull(actualDataImportEventPayload.getContext().get(INSTANCE.value()));
JsonObject updatedInstance = new JsonObject(actualDataImportEventPayload.getContext().get(INSTANCE.value()));
assertEquals(title, updatedInstance.getString("title"));
assertThat(updatedInstance.getJsonArray("precedingTitles").size(), is(1));
assertNotEquals(existingPrecedingTitle.getString(TITLE_KEY), updatedInstance.getJsonArray("precedingTitles").getJsonObject(0).getString(TITLE_KEY));
assertThat(updatedInstance.getString("_version"), is(INSTANCE_VERSION_AS_STRING));
ArgumentCaptor<Set<String>> titleIdCaptor = ArgumentCaptor.forClass(Set.class);
verify(precedingSucceedingTitlesHelper).deletePrecedingSucceedingTitles(titleIdCaptor.capture(), any(Context.class));
assertTrue(titleIdCaptor.getValue().contains(existingPrecedingTitle.getString("id")));
}
use of org.folio.inventory.common.Context in project mod-inventory by folio-org.
the class UpdateInstanceQuickMarcEventHandlerTest method shouldProcessEvent.
@Test
public void shouldProcessEvent() {
HashMap<String, String> eventPayload = new HashMap<>();
eventPayload.put("RECORD_TYPE", "MARC_BIB");
eventPayload.put("MARC_BIB", record.encode());
eventPayload.put("MAPPING_RULES", mappingRules.encode());
eventPayload.put("MAPPING_PARAMS", new JsonObject().encode());
eventPayload.put("RELATED_RECORD_VERSION", INSTANCE_VERSION);
Future<Instance> future = updateInstanceEventHandler.handle(eventPayload);
Instance updatedInstance = future.result();
Assert.assertNotNull(updatedInstance);
Assert.assertEquals(INSTANCE_ID, updatedInstance.getId());
Assert.assertEquals(INSTANCE_VERSION, updatedInstance.getVersion());
Assert.assertEquals("Victorian environmental nightmares and something else/", updatedInstance.getIndexTitle());
Assert.assertNotNull(updatedInstance.getIdentifiers().stream().filter(i -> "(OCoLC)1060180367".equals(i.value)).findFirst().orElse(null));
Assert.assertNotNull(updatedInstance.getContributors().stream().filter(c -> "Mazzeno, Laurence W., 1234566".equals(c.name)).findFirst().orElse(null));
Assert.assertNotNull(updatedInstance.getSubjects());
Assert.assertEquals(1, updatedInstance.getSubjects().size());
Assert.assertTrue(updatedInstance.getSubjects().get(0).contains("additional subfield"));
Assert.assertFalse(updatedInstance.getSubjects().get(0).contains("Environmentalism in literature"));
Assert.assertNotNull(updatedInstance.getNotes());
Assert.assertEquals("Adding a note", updatedInstance.getNotes().get(0).note);
ArgumentCaptor<Context> argument = ArgumentCaptor.forClass(Context.class);
verify(instanceUpdateDelegate).handle(any(), any(), argument.capture());
Assert.assertEquals("token", argument.getValue().getToken());
Assert.assertEquals("dummy", argument.getValue().getTenantId());
Assert.assertEquals("http://localhost", argument.getValue().getOkapiLocation());
}
use of org.folio.inventory.common.Context in project mod-inventory by folio-org.
the class QuickMarcKafkaHandlerTest method setUp.
@Before
public void setUp() throws IOException {
bibMappingRules = new JsonObject(TestUtil.readFileFromPath(BIB_MAPPING_RULES_PATH));
holdingsMappingRules = new JsonObject(TestUtil.readFileFromPath(HOLDINGS_MAPPING_RULES_PATH));
authorityMappingRules = new JsonObject(TestUtil.readFileFromPath(AUTHORITY_MAPPING_RULES_PATH));
existingInstance = Instance.fromJson(new JsonObject(TestUtil.readFileFromPath(INSTANCE_PATH)));
existingHoldings = new JsonObject(TestUtil.readFileFromPath(HOLDINGS_PATH)).mapTo(HoldingsRecord.class);
existingAuthority = new JsonObject(TestUtil.readFileFromPath(AUTHORITY_PATH)).mapTo(Authority.class);
bibRecord = Json.decodeValue(TestUtil.readFileFromPath(BIB_RECORD_PATH), Record.class);
bibRecord.getParsedRecord().withContent(JsonObject.mapFrom(bibRecord.getParsedRecord().getContent()).encode());
holdingsRecord = Json.decodeValue(TestUtil.readFileFromPath(HOLDINGS_RECORD_PATH), Record.class);
holdingsRecord.getParsedRecord().withContent(JsonObject.mapFrom(holdingsRecord.getParsedRecord().getContent()).encode());
authorityRecord = Json.decodeValue(TestUtil.readFileFromPath(AUTHORITY_RECORD_PATH), Record.class);
authorityRecord.getParsedRecord().withContent(JsonObject.mapFrom(authorityRecord.getParsedRecord().getContent()).encode());
mocks = MockitoAnnotations.openMocks(this);
when(mockedStorage.getInstanceCollection(any(Context.class))).thenReturn(mockedInstanceCollection);
when(mockedStorage.getHoldingsRecordCollection(any(Context.class))).thenReturn(mockedHoldingsRecordCollection);
when(mockedStorage.getAuthorityRecordCollection(any(Context.class))).thenReturn(mockedAuthorityRecordCollection);
doAnswer(invocationOnMock -> {
Consumer<Success<Instance>> successHandler = invocationOnMock.getArgument(1);
successHandler.accept(new Success<>(existingInstance));
return null;
}).when(mockedInstanceCollection).findById(anyString(), any(), any());
doAnswer(invocationOnMock -> {
Consumer<Success<HoldingsRecord>> successHandler = invocationOnMock.getArgument(1);
successHandler.accept(new Success<>(existingHoldings));
return null;
}).when(mockedHoldingsRecordCollection).findById(anyString(), any(), any());
doAnswer(invocationOnMock -> {
Instance instance = invocationOnMock.getArgument(0);
Consumer<Success<Instance>> successHandler = invocationOnMock.getArgument(1);
successHandler.accept(new Success<>(instance));
return null;
}).when(mockedInstanceCollection).update(any(Instance.class), any(), any());
doAnswer(invocationOnMock -> {
HoldingsRecord instance = invocationOnMock.getArgument(0);
Consumer<Success<HoldingsRecord>> successHandler = invocationOnMock.getArgument(1);
successHandler.accept(new Success<>(instance));
return null;
}).when(mockedHoldingsRecordCollection).update(any(HoldingsRecord.class), any(), any());
doAnswer(invocationOnMock -> {
Authority authority = invocationOnMock.getArgument(0);
Consumer<Success<Authority>> successHandler = invocationOnMock.getArgument(1);
successHandler.accept(new Success<>(authority));
return null;
}).when(mockedAuthorityRecordCollection).update(any(Authority.class), any(), any());
when(okapiHttpClient.get(anyString())).thenReturn(CompletableFuture.completedFuture(new Response(200, new JsonObject().encode(), null, null)));
when(okapiHttpClient.put(anyString(), any(JsonObject.class))).thenReturn(CompletableFuture.completedFuture(new Response(204, null, null, null)));
String[] hostAndPort = cluster.getBrokerList().split(":");
kafkaConfig = KafkaConfig.builder().envId("env").kafkaHost(hostAndPort[0]).kafkaPort(hostAndPort[1]).maxRequestSize(1048576).build();
PrecedingSucceedingTitlesHelper precedingSucceedingTitlesHelper = new PrecedingSucceedingTitlesHelper(context -> okapiHttpClient);
handler = new QuickMarcKafkaHandler(vertx, mockedStorage, 100, kafkaConfig, precedingSucceedingTitlesHelper);
when(kafkaRecord.headers()).thenReturn(List.of(KafkaHeader.header(XOkapiHeaders.TENANT.toLowerCase(), TENANT_ID), KafkaHeader.header(XOkapiHeaders.URL.toLowerCase(), OKAPI_URL)));
}
use of org.folio.inventory.common.Context in project mod-inventory by folio-org.
the class UpdateAuthorityQuickMarcEventHandlerTest method shouldProcessEvent.
@Test
public void shouldProcessEvent() {
HashMap<String, String> eventPayload = new HashMap<>();
eventPayload.put("RECORD_TYPE", "MARC_AUTHORITY");
eventPayload.put("MARC_AUTHORITY", record.encode());
eventPayload.put("MAPPING_RULES", mappingRules.encode());
eventPayload.put("MAPPING_PARAMS", new JsonObject().encode());
eventPayload.put("RELATED_RECORD_VERSION", AUTHORITY_VERSION.toString());
Future<Authority> future = updateAuthorityQuickMarcEventHandler.handle(eventPayload);
Authority updatedAuthority = future.result();
Assert.assertNotNull(updatedAuthority);
Assert.assertEquals(AUTHORITY_ID, updatedAuthority.getId());
Assert.assertEquals(AUTHORITY_VERSION, updatedAuthority.getVersion());
Assert.assertNotNull(updatedAuthority.getIdentifiers());
Assert.assertEquals(4, updatedAuthority.getIdentifiers().size());
Assert.assertNotNull(updatedAuthority.getNotes());
ArgumentCaptor<Context> argument = ArgumentCaptor.forClass(Context.class);
verify(authorityUpdateDelegate).handle(any(), any(), argument.capture());
Assert.assertEquals("token", argument.getValue().getToken());
Assert.assertEquals("dummy", argument.getValue().getTenantId());
Assert.assertEquals("http://localhost", argument.getValue().getOkapiLocation());
}
use of org.folio.inventory.common.Context in project mod-inventory by folio-org.
the class AbstractLoader method loadEntity.
@Override
public CompletableFuture<LoadResult> loadEntity(LoadQuery loadQuery, DataImportEventPayload eventPayload) {
if (loadQuery == null) {
return CompletableFuture.completedFuture(new LoadResult());
}
CompletableFuture<LoadResult> future = new CompletableFuture<>();
LoadResult loadResult = new LoadResult();
loadResult.setEntityType(getEntityType().value());
Context context = constructContext(eventPayload.getTenant(), eventPayload.getToken(), eventPayload.getOkapiUrl());
vertx.runOnContext(v -> {
try {
String cql = loadQuery.getCql() + addCqlSubMatchCondition(eventPayload);
getSearchableCollection(context).findByCql(cql, PagingParameters.defaults(), success -> {
MultipleRecords<T> collection = success.getResult();
if (collection.totalRecords == 1) {
loadResult.setValue(mapEntityToJsonString(collection.records.get(0)));
} else if (collection.totalRecords > 1) {
if (canProcessMultiMatchResult(eventPayload)) {
LOG.info("Found multiple records by CQL query: [{}]. Found records IDs: {}", cql, mapEntityListToIdsJsonString(collection.records));
loadResult.setEntityType(MULTI_MATCH_IDS);
loadResult.setValue(mapEntityListToIdsJsonString(collection.records));
} else {
String errorMessage = String.format("Found multiple records matching specified conditions. CQL query: [%s].%nFound records: %s", cql, Json.encodePrettily(collection.records));
LOG.error(errorMessage);
future.completeExceptionally(new MatchingException(errorMessage));
return;
}
}
future.complete(loadResult);
}, failure -> {
LOG.error(failure.getReason());
future.completeExceptionally(new MatchingException(failure.getReason()));
});
} catch (UnsupportedEncodingException e) {
LOG.error("Failed to retrieve records", e);
future.completeExceptionally(e);
}
});
return future;
}
Aggregations