Search in sources :

Example 16 with Context

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")));
}
Also used : Context(org.folio.inventory.common.Context) Set(java.util.Set) HashMap(java.util.HashMap) JsonObject(io.vertx.core.json.JsonObject) Reader(org.folio.processing.mapping.mapper.reader.Reader) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ParsedRecord(org.folio.rest.jaxrs.model.ParsedRecord) MappingRule(org.folio.rest.jaxrs.model.MappingRule) DataImportEventPayload(org.folio.DataImportEventPayload) JsonArray(io.vertx.core.json.JsonArray) InstanceWriterFactory(org.folio.inventory.dataimport.InstanceWriterFactory) ParsedRecord(org.folio.rest.jaxrs.model.ParsedRecord) Record(org.folio.rest.jaxrs.model.Record) Test(org.junit.Test)

Example 17 with Context

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());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Json(io.vertx.core.json.Json) Context(org.folio.inventory.common.Context) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Failure(org.folio.inventory.common.domain.Failure) Response(org.folio.inventory.support.http.client.Response) InstanceCollection(org.folio.inventory.domain.instances.InstanceCollection) TestUtil(org.folio.inventory.TestUtil) ArgumentCaptor(org.mockito.ArgumentCaptor) TITLE_KEY(org.folio.inventory.domain.instances.titles.PrecedingSucceedingTitle.TITLE_KEY) Mockito.doAnswer(org.mockito.Mockito.doAnswer) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) PrecedingSucceedingTitlesHelper(org.folio.inventory.dataimport.handlers.actions.PrecedingSucceedingTitlesHelper) Record(org.folio.rest.jaxrs.model.Record) UpdateInstanceQuickMarcEventHandler(org.folio.inventory.dataimport.handlers.quickmarc.UpdateInstanceQuickMarcEventHandler) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) Storage(org.folio.inventory.storage.Storage) Consumer(java.util.function.Consumer) InstanceUpdateDelegate(org.folio.inventory.dataimport.handlers.actions.InstanceUpdateDelegate) Mockito(org.mockito.Mockito) Success(org.folio.inventory.common.domain.Success) Instance(org.folio.inventory.domain.instances.Instance) OptimisticLockingException(org.folio.inventory.dataimport.exceptions.OptimisticLockingException) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Context(org.folio.inventory.common.Context) HashMap(java.util.HashMap) Instance(org.folio.inventory.domain.instances.Instance) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 18 with Context

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)));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Context(org.folio.inventory.common.Context) Authority(org.folio.Authority) Instance(org.folio.inventory.domain.instances.Instance) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Success(org.folio.inventory.common.domain.Success) Response(org.folio.inventory.support.http.client.Response) HoldingsRecord(org.folio.HoldingsRecord) PrecedingSucceedingTitlesHelper(org.folio.inventory.dataimport.handlers.actions.PrecedingSucceedingTitlesHelper) QuickMarcKafkaHandler(org.folio.inventory.dataimport.consumers.QuickMarcKafkaHandler) HoldingsRecord(org.folio.HoldingsRecord) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Record(org.folio.rest.jaxrs.model.Record) Before(org.junit.Before)

Example 19 with Context

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());
}
Also used : Context(org.folio.inventory.common.Context) HashMap(java.util.HashMap) Authority(org.folio.Authority) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 20 with Context

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;
}
Also used : Context(org.folio.inventory.common.Context) EventHandlingUtil.constructContext(org.folio.inventory.dataimport.handlers.matching.util.EventHandlingUtil.constructContext) CompletableFuture(java.util.concurrent.CompletableFuture) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MatchingException(org.folio.processing.exceptions.MatchingException) LoadResult(org.folio.processing.matching.loader.LoadResult)

Aggregations

Context (org.folio.inventory.common.Context)30 JsonObject (io.vertx.core.json.JsonObject)25 Future (io.vertx.core.Future)20 String.format (java.lang.String.format)20 HashMap (java.util.HashMap)19 Json (io.vertx.core.json.Json)17 Storage (org.folio.inventory.storage.Storage)17 Promise (io.vertx.core.Promise)16 LogManager (org.apache.logging.log4j.LogManager)16 Logger (org.apache.logging.log4j.Logger)16 DataImportEventPayload (org.folio.DataImportEventPayload)16 MappingMetadataCache (org.folio.inventory.dataimport.cache.MappingMetadataCache)16 EventProcessingException (org.folio.processing.exceptions.EventProcessingException)16 Record (org.folio.rest.jaxrs.model.Record)15 CompletableFuture (java.util.concurrent.CompletableFuture)13 UUID (java.util.UUID)12 MappingParameters (org.folio.processing.mapping.defaultmapper.processor.parameters.MappingParameters)11 List (java.util.List)10 MappingMetadataDto (org.folio.MappingMetadataDto)10 Instance (org.folio.inventory.domain.instances.Instance)10