Search in sources :

Example 21 with Failure

use of org.folio.inventory.common.domain.Failure in project mod-inventory by folio-org.

the class ExternalStorageModuleCollection method add.

public void add(T item, Consumer<Success<T>> resultCallback, Consumer<Failure> failureCallback) {
    final var futureResponse = new CompletableFuture<AsyncResult<HttpResponse<Buffer>>>();
    final HttpRequest<Buffer> request = withStandardHeaders(webClient.postAbs(storageAddress));
    request.sendJsonObject(mapToRequest(item), futureResponse::complete);
    futureResponse.thenCompose(this::mapAsyncResultToCompletionStage).thenAccept(response -> {
        if (response.getStatusCode() == 201) {
            try {
                T created = mapFromJson(response.getJson());
                resultCallback.accept(new Success<>(created));
            } catch (Exception e) {
                LOGGER.error(e);
                failureCallback.accept(new Failure(e.getMessage(), response.getStatusCode()));
            }
        } else {
            failureCallback.accept(new Failure(response.getBody(), response.getStatusCode()));
        }
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) CompletableFuture(java.util.concurrent.CompletableFuture) ACCEPT(org.apache.http.HttpHeaders.ACCEPT) HttpResponse(io.vertx.ext.web.client.HttpResponse) Failure(org.folio.inventory.common.domain.Failure)

Example 22 with Failure

use of org.folio.inventory.common.domain.Failure in project mod-inventory by folio-org.

the class ExternalStorageModuleCollection method interpretMultipleRecordResponse.

private void interpretMultipleRecordResponse(Consumer<Success<MultipleRecords<T>>> resultCallback, Consumer<Failure> failureCallback, Response response) {
    if (response.getStatusCode() == 200) {
        try {
            JsonObject wrappedRecords = response.getJson();
            List<JsonObject> records = JsonArrayHelper.toList(wrappedRecords.getJsonArray(collectionWrapperPropertyName));
            List<T> foundRecords = records.stream().map(this::mapFromJson).collect(Collectors.toList());
            MultipleRecords<T> result = new MultipleRecords<>(foundRecords, wrappedRecords.getInteger("totalRecords"));
            resultCallback.accept(new Success<>(result));
        } catch (Exception e) {
            LOGGER.error(e);
            failureCallback.accept(new Failure(e.getMessage(), response.getStatusCode()));
        }
    } else {
        failureCallback.accept(new Failure(response.getBody(), response.getStatusCode()));
    }
}
Also used : ACCEPT(org.apache.http.HttpHeaders.ACCEPT) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) JsonObject(io.vertx.core.json.JsonObject) Failure(org.folio.inventory.common.domain.Failure)

Example 23 with Failure

use of org.folio.inventory.common.domain.Failure in project mod-inventory by folio-org.

the class MarcHoldingsRecordHridSetKafkaHandlerTest method shouldReturnFailedFutureWhenOLError.

@Test
public void shouldReturnFailedFutureWhenOLError(TestContext context) {
    // given
    Async async = context.async();
    Map<String, String> payload = new HashMap<>();
    payload.put(JOB_EXECUTION_ID_KEY, UUID.randomUUID().toString());
    payload.put("MARC_HOLDINGS", Json.encode(record));
    payload.put("CURRENT_RETRY_NUMBER", "1");
    Event event = new Event().withId("01").withEventPayload(Json.encode(payload));
    String expectedKafkaRecordKey = "test_key";
    when(kafkaRecord.key()).thenReturn(expectedKafkaRecordKey);
    when(kafkaRecord.value()).thenReturn(Json.encode(event));
    when(kafkaRecord.headers()).thenReturn(okapiHeaders);
    doAnswer(invocationOnMock -> {
        Consumer<Failure> failureHandler = invocationOnMock.getArgument(2);
        failureHandler.accept(new Failure("Cannot update record 601a8dc4-dee7-48eb-b03f-d02fdf0debd0 because it has been changed (optimistic locking): Stored _version is 2, _version of request is 1", 409));
        return null;
    }).when(mockedHoldingsCollection).update(any(), any(), any());
    // when
    Future<String> future = marcHoldingsRecordHridSetKafkaHandler.handle(kafkaRecord);
    // then
    future.onComplete(ar -> {
        context.assertTrue(ar.failed());
        async.complete();
    });
}
Also used : HashMap(java.util.HashMap) Async(io.vertx.ext.unit.Async) Event(org.folio.rest.jaxrs.model.Event) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Failure(org.folio.inventory.common.domain.Failure) Test(org.junit.Test)

Example 24 with Failure

use of org.folio.inventory.common.domain.Failure in project mod-inventory by folio-org.

the class MarcHoldingsRecordHridSetKafkaHandlerTest method shouldReturnFailedFutureWhenOLErrorExist.

@Test
public void shouldReturnFailedFutureWhenOLErrorExist(TestContext context) {
    // given
    Async async = context.async();
    Map<String, String> payload = new HashMap<>();
    payload.put(JOB_EXECUTION_ID_KEY, UUID.randomUUID().toString());
    payload.put("MARC_HOLDINGS", Json.encode(record));
    payload.put("CURRENT_RETRY_NUMBER", "1");
    Event event = new Event().withId("01").withEventPayload(Json.encode(payload));
    String expectedKafkaRecordKey = "test_key";
    when(kafkaRecord.key()).thenReturn(expectedKafkaRecordKey);
    when(kafkaRecord.value()).thenReturn(Json.encode(event));
    when(kafkaRecord.headers()).thenReturn(okapiHeaders);
    doAnswer(invocationOnMock -> {
        Consumer<Failure> failureHandler = invocationOnMock.getArgument(2);
        failureHandler.accept(new Failure("Cannot update record 601a8dc4-dee7-48eb-b03f-d02fdf0debd0 because it has been changed (optimistic locking): Stored _version is 2, _version of request is 1", 409));
        return null;
    }).when(mockedHoldingsCollection).update(any(), any(), any());
    // when
    Future<String> future = marcHoldingsRecordHridSetKafkaHandler.handle(kafkaRecord);
    // then
    future.onComplete(ar -> {
        context.assertTrue(ar.failed());
        async.complete();
    });
}
Also used : HashMap(java.util.HashMap) Async(io.vertx.ext.unit.Async) Event(org.folio.rest.jaxrs.model.Event) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Failure(org.folio.inventory.common.domain.Failure) Test(org.junit.Test)

Example 25 with Failure

use of org.folio.inventory.common.domain.Failure in project mod-inventory by folio-org.

the class CreateHoldingEventHandlerTest method shouldNotProcessEventEvenIfDuplicatedInventoryStorageErrorExists.

@Test(expected = Exception.class)
public void shouldNotProcessEventEvenIfDuplicatedInventoryStorageErrorExists() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    Reader fakeReader = Mockito.mock(Reader.class);
    String permanentLocationId = UUID.randomUUID().toString();
    when(fakeReader.read(any(MappingRule.class))).thenReturn(StringValue.of(permanentLocationId));
    when(fakeReaderFactory.createReader()).thenReturn(fakeReader);
    when(storage.getHoldingsRecordCollection(any())).thenReturn(holdingsRecordsCollection);
    doAnswer(invocationOnMock -> {
        Consumer<Failure> failureHandler = invocationOnMock.getArgument(2);
        failureHandler.accept(new Failure(UNIQUE_ID_ERROR_MESSAGE, 400));
        return null;
    }).when(holdingsRecordsCollection).add(any(), any(), any());
    MappingManager.registerReaderFactory(fakeReaderFactory);
    MappingManager.registerWriterFactory(new HoldingWriterFactory());
    String instanceId = String.valueOf(UUID.randomUUID());
    Instance instance = new Instance(instanceId, "5", String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID()));
    Record record = new Record().withParsedRecord(new ParsedRecord().withContent(PARSED_CONTENT_WITH_INSTANCE_ID));
    HashMap<String, String> context = new HashMap<>();
    context.put("INSTANCE", new JsonObject(new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(instance)).encode());
    context.put(MARC_BIBLIOGRAPHIC.value(), Json.encode(record));
    DataImportEventPayload dataImportEventPayload = new DataImportEventPayload().withEventType(DI_INVENTORY_HOLDING_CREATED.value()).withJobExecutionId(UUID.randomUUID().toString()).withContext(context).withProfileSnapshot(profileSnapshotWrapper).withCurrentNode(profileSnapshotWrapper.getChildSnapshotWrappers().get(0));
    CompletableFuture<DataImportEventPayload> future = createHoldingEventHandler.handle(dataImportEventPayload);
    future.get(5, TimeUnit.SECONDS);
}
Also used : Instance(org.folio.inventory.domain.instances.Instance) HashMap(java.util.HashMap) Reader(org.folio.processing.mapping.mapper.reader.Reader) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ParsedRecord(org.folio.rest.jaxrs.model.ParsedRecord) MappingRule(org.folio.rest.jaxrs.model.MappingRule) DataImportEventPayload(org.folio.DataImportEventPayload) HoldingWriterFactory(org.folio.inventory.dataimport.HoldingWriterFactory) HoldingsRecord(org.folio.HoldingsRecord) ParsedRecord(org.folio.rest.jaxrs.model.ParsedRecord) Record(org.folio.rest.jaxrs.model.Record) Failure(org.folio.inventory.common.domain.Failure) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Aggregations

Failure (org.folio.inventory.common.domain.Failure)50 Test (org.junit.Test)44 CompletableFuture (java.util.concurrent.CompletableFuture)26 HashMap (java.util.HashMap)21 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)18 DataImportEventPayload (org.folio.DataImportEventPayload)17 JsonObject (io.vertx.core.json.JsonObject)16 PagingParameters (org.folio.inventory.common.api.request.PagingParameters)10 Record (org.folio.rest.jaxrs.model.Record)10 ParsedRecord (org.folio.rest.jaxrs.model.ParsedRecord)9 Async (io.vertx.ext.unit.Async)8 Consumer (java.util.function.Consumer)7 HoldingsRecord (org.folio.HoldingsRecord)7 AuthorityRecordCollection (org.folio.inventory.domain.AuthorityRecordCollection)7 InstanceCollection (org.folio.inventory.domain.instances.InstanceCollection)7 ItemCollection (org.folio.inventory.domain.items.ItemCollection)6 EventHandler (org.folio.processing.events.services.handler.EventHandler)6 MultipleRecords (org.folio.inventory.common.domain.MultipleRecords)4 Instance (org.folio.inventory.domain.instances.Instance)4 Reader (org.folio.processing.mapping.mapper.reader.Reader)4