Skip to content

Commit

Permalink
Merge pull request #45 from anusii/zy/16_rdflib_read_remote_turtle
Browse files Browse the repository at this point in the history
Zy/16 rdflib read remote turtle
  • Loading branch information
zheyxu authored Jul 18, 2024
2 parents a6ce331 + 2b87b50 commit 73e13db
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
21 changes: 21 additions & 0 deletions example/example_6.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:rdflib/rdflib.dart';

main() async {
String webLink = 'https://www.w3.org/TR/turtle/examples/example3.ttl';

// Create a graph to read Turtle file and store info.
Graph g = Graph();

// Parse the Turtle file from the web.
await g.parseTurtleFromWeb(webLink);

// Serialize the Graph for output.
g.serialize(format: 'ttl', abbr: 'short');
print('-------Serialized String--------\n${g.serializedString}');

// Print out full format of triples (will use shorthand in serialization/export).
print('--------All triples in the graph-------');
for (Triple t in g.triples) {
print(t);
}
}
30 changes: 30 additions & 0 deletions lib/src/graph.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'dart:convert';
import 'dart:io' show File;

import 'package:http/http.dart' as http;

import './namespace.dart';
import './term.dart';
import './triple.dart';
Expand Down Expand Up @@ -710,6 +712,34 @@ class Graph {
}
}

/// Parses a valid turtle file from a web link [webLink].
///
/// Updates [Graph.ctx], [Graph.groups] and [Graph.triples] in the process.
/// The [webLink] should point to a valid Turtle (.ttl) file to ensure correct parsing.
/// If the [webLink] does not point to a .ttl file, it might cause unexpected parsing errors.
Future<void> parseTurtleFromWeb(String webLink) async {
String fileContent = '';

try {
// Fetch the content from the web link.
final response = await http.get(
Uri.parse(webLink),
);

if (response.statusCode == 200) {
fileContent = utf8.decode(response.bodyBytes);

// Parse the Turtle content.
parseTurtle(fileContent);
} else {
print(
'Failed to load content from $webLink. Status code: ${response.statusCode}');
}
} catch (e) {
print('Failed to load content from $webLink. Error: $e');
}
}

/// Finds the line number of a given triple in the content.
///
/// This is a helper method to aid in error reporting by providing the line number.
Expand Down
6 changes: 3 additions & 3 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ homepage: https://github.com/anusii/rdflib
repository: https://github.com/anusii/rdflib

environment:
sdk: ">=3.0.0 <4.0.0"
sdk: '>=3.0.0 <4.0.0'

dependencies:
http: ^1.2.1
logging: ^1.1.0
petitparser: ^6.0.1
http: ^1.1.0
uuid: ^4.4.1

dev_dependencies:
lints: ^2.0.1
test: ^1.22.0

0 comments on commit 73e13db

Please sign in to comment.