convert method

  1. @override
RdfGraph convert(
  1. String input, {
  2. String? documentUrl,
})
override

Decodes RDF content by auto-detecting its format

This method implements a multi-stage format detection strategy:

  1. First tries to detect the format using heuristic analysis
  2. If detected, attempts to parse with the detected format
  3. If detection fails or parsing with the detected format fails, tries each registered codec in sequence
  4. If all codecs fail, throws an exception with details

The input parameter contains the RDF content to decode. The documentUrl parameter is an optional base URL for resolving relative IRIs.

Returns an RdfGraph containing the parsed triples.

Throws CodecNotSupportedException if no codec can parse the content or if no codecs are registered.

Implementation

@override
RdfGraph convert(String input, {String? documentUrl}) {
  // First try to use format auto-detection
  final format = _registry.detectGraphCodec(input);

  if (format != null) {
    _logger.fine('Using detected format: ${format.primaryMimeType}');
    try {
      return (_decoderOptions == null
              ? format.decoder
              : format.decoder.withOptions(_decoderOptions))
          .convert(input, documentUrl: documentUrl);
    } catch (e) {
      _logger.fine(
        'Failed with detected format ${format.primaryMimeType}: $e',
      );
      // If the detected format fails, fall through to trying all formats
    }
  }

  // If we can't detect or the detected format fails, try all formats in sequence
  final codecs = _registry.getAllGraphCodecs();
  if (codecs.isEmpty) {
    throw CodecNotSupportedException('No RDF codecs registered');
  }

  // Try each format in sequence until one works
  Exception? lastException;
  for (final codec in codecs) {
    try {
      _logger.fine('Trying codec: ${codec.primaryMimeType}');
      return (_decoderOptions == null
              ? codec.decoder
              : codec.decoder.withOptions(_decoderOptions))
          .convert(input, documentUrl: documentUrl);
    } catch (e) {
      _logger.fine('Failed with format ${codec.primaryMimeType}: $e');
      lastException = e is Exception ? e : Exception(e.toString());
    }
  }

  throw CodecNotSupportedException(
    'Could not parse content with any registered codec: ${lastException?.toString() ?? "unknown error"}',
  );
}