Key Elements of an Input Adapter
Here we demonstrate how the key elements of an input adapter are implemented in the CSV inbound Adapter.
Prerequisites: For additional background or context regarding the following material, see Data Flow Overview.
The key elements of an import adapter are straightforward: You process and validate the data, creating the raw items. Then you construct and supply an appropriate message header, push the fragments in the payload of a message to the Spring Integration channel. If relevant, return the result. In the following sections, we use code fragments from the CSV inbound adapter to demonstrate how we have implemented each of these key elements.
The ImportCsv Method
The main method used in our CSV adapter is the importCsv method. This method takes the feed name, item type, and input stream, and throws a validation exception on failure.
public ResultData importCsv(final String feedName, final String itemType, final InputStream csvInput) throws ValidationException
{
validateForFailure(feedName, itemType, csvInput);
final List<Map<String, String>> rawFragments = validateAndCreateRawFragments(feedName, itemType, csvInput);
logger.info("Importing " + rawFragments.size() + " raw fragments of type " + itemType + " into data feed " + feedName);
rawFragmentInputChannel.send(new GenericMessage<Object>(rawFragments, constructMessageHeader(itemType, feedName)));
final ResultData result = new ResultData();
result.setNumberProcessed(rawFragments.size());
return result;
}
We first validate the data, creating the raw fragments and storing them in a list. It is important to note that the list is a list of mapped key-value pairs, essentially untyped (String, String). (Line 4)
After logging the details of the raw fragment import, we then send the raw fragments to the Spring Integration rawFragmentInputChannel, with the appropriate header. The header includes the item type and feed name, allowing Spring Integration to direct the input stream to the correct data feed and pool. (Line 7)
Finally, we process and return the result, this being the number of items processed. (Lines 9-11)
Validating the Data and Creating Raw Fragments
When validating data, it's important to be sure to handle the failure case. Handling the failure case allows you to create a FailedDataLoadingAction. Our validateForFailure method checks the item type and feed name. In case of failure, it creates a failedDataLoadingAction, and throws a validation exception.
private void validateForFailure(final String feedName, final String itemType, final InputStream csvInput) throws ValidationException
{
try
{
dataLoadingValidator.validateForFailure(feedName, itemType);
}
catch (ValidationException e)
{
createFailedDataLoadingAction(e, feedName, csvReaderService.extractBodyAndHeaders(csvInput).getCsvBody().size());
throw e;
}
}
When creating the raw fragments, we extract the CSV data using the csvReaderService, then validate both CSV headers and CSV line items. In case of failure, we create a failedDataLoadingAction, and throw a validation exception. Otherwise, we use the csvRawFragmentConversionService.createRawFragments method to construct the raw fragment.
private List<Map<String, String>> validateAndCreateRawFragments(final String feedName, final String itemType, final InputStream csvInput) throws ValidationException
{
final CsvData bodyAndHeaders = csvReaderService.extractBodyAndHeaders(csvInput);
try
{
dataLoadingValidator.validateCsv(bodyAndHeaders, itemType);
}
catch (ValidationException e)
{
createFailedDataLoadingAction(e, feedName, bodyAndHeaders.getCsvBody().size());
throw e;
}
return csvRawFragmentConversionService.createRawFragments(bodyAndHeaders, itemType);
}
Using the eventPublicationService to Report a dataFailedLoading Event
When throwing a validation exception, we want to provide more details of the DataLoadingAction that failed, including the feed name and raw fragment count. We then publish this event using the eventPublicationService so that Data Hub may properly register and report the error. (Line 15).
private void createFailedDataLoadingAction(final ValidationException e, final String feedName, final long rawFragmentCount)
{
final TransactionTemplate template = new TransactionTemplate(transactionManager);
template.execute(new TransactionCallbackWithoutResult()
{
@Override
protected void doInTransactionWithoutResult(final TransactionStatus status)
{
final DataHubFeed feed = dataHubFeedService.findDataFeedByName(feedName);
final String message = buildErrorMessage(e);
final DataLoadingAction dataLoadingAction = dataLoadingService.createFailedAction(feed, rawFragmentCount, message);
eventPublicationService.publishEvent(new DataLoadingCompletedEvent(dataLoadingAction.getActionId(),
-1, dataLoadingAction.getFeed() != null ? dataLoadingAction.getFeed().getFeedId() : -1,
rawFragmentCount, DataLoadingActionStatusType.FAILURE.name()));
}
});
}
Message Header Construction
Once we have our raw fragments list, we construct an appropriate message header for the Spring Integration channel. With a sound header, we can successfully deliver the new fragments list into the correct feed. The delivery is done using the constructMessageHeader method, which takes the item type and feed name, and returns the header as a Map<String, Object>.
private Map<String, Object> constructMessageHeader(final String itemType, final String feedName)
{
final Map<String, Object> header = new HashMap<>();
header.put("itemType", itemType);
header.put("feedName", feedName);
return header;
}
Without the message header, the load would FAIL.
Summary
In summary, our inbound adapter has performed the following steps.
- Import the source data and perform validation (in this case, the CSV file format).
- Cycle through each line of data, validating it, and creating the raw fragments.
- In the case of any failures, create a FailedDataLoadingAction.
- Use the eventPublicationService to report any failures.
- Construct an appropriate message header, and send it along with the raw fragment payload to the Spring Integration channel.