Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

turtle & n3 parser don't correctly handle \uXXXX escapes #335

Closed
joernhees opened this issue Oct 16, 2013 · 6 comments
Closed

turtle & n3 parser don't correctly handle \uXXXX escapes #335

joernhees opened this issue Oct 16, 2013 · 6 comments
Labels
bug Something isn't working parsing Related to a parsing.

Comments

@joernhees
Copy link
Member

rdflib-4.0.1

According to http://www.w3.org/TeamSubmission/turtle/#sec-strings Turtle strings and URIs can use -escape sequences to represent Unicode code points, especially including \uXXXX and \UXXXXXXXX escapes.

Parsing a file called test.ttl looking like this:

@prefix owl:    <http://www.w3.org/2002/07/owl#> .
@prefix dbpedia:    <http://dbpedia.org/resource/> .
@prefix ns147:  <http://wo.dbpedia.org/resource/> .
dbpedia:Animal  owl:sameAs  ns147:Dundat_yi ,
        <http://vls.dbpedia.org/resource/B\u00EAesten_(ryk)> .

will incorrectly "double" escape the \:

In [1]: import rdflib

In [2]: g = rdflib.ConjunctiveGraph()

In [3]: g.parse('test.ttl', format='turtle')
No handlers could be found for logger "rdflib.term"
Out[3]: <Graph identifier=file:///Users/joern/Downloads/test.ttl (<class 'rdflib.graph.Graph'>)>

In [4]: list(g)
Out[4]:
[(rdflib.term.URIRef(u'http://dbpedia.org/resource/Animal'),
  rdflib.term.URIRef(u'http://www.w3.org/2002/07/owl#sameAs'),
  rdflib.term.URIRef(u'http://vls.dbpedia.org/resource/B\\u00EAesten_(ryk)'))]

trying to serialize this will obviously fail:

In [5]: g.serialize(format='turtle')
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-5-d57597f48018> in <module>()
----> 1 g.serialize(format='turtle')

/usr/local/lib/python2.7/site-packages/rdflib/graph.pyc in serialize(self, destination, format, base, encoding, **args)
    901         if destination is None:
    902             stream = BytesIO()
--> 903             serializer.serialize(stream, base=base, encoding=encoding, **args)
    904             return stream.getvalue()
    905         if hasattr(destination, "write"):

...

/usr/local/lib/python2.7/site-packages/rdflib/term.pyc in n3(self, namespace_manager)
    220     def n3(self, namespace_manager = None):
    221         if not _is_valid_uri(self):
--> 222             raise Exception('"%s" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?'%self)
    223
    224         if namespace_manager:

Exception: "http://vls.dbpedia.org/resource/B\u00EAesten_(ryk)" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?

For n3 there are two remarks: one under http://www.w3.org/TeamSubmission/n3/#subsets even pointing out that there is an option for this in cwm (which our n3 parser is based on) and http://www.w3.org/TeamSubmission/n3/#sec-mediaReg clearly stating that the -escapes are ok as well.

Am i missing something?
If not I'll try to fix this in the n3 parser (which we use for turtle as well) and include the above file as a new test-case.

@joernhees
Copy link
Member Author

note to self: raw-unicode-escape might be worth a try:

In [32]: print unicode(r'\u006a\x6f\n')
\u006a\x6f\n

In [33]: print unicode(r'\u006a\x6f\n', 'unicode-escape')
jo


In [34]: print unicode(r'\u006a\x6f\n', 'raw-unicode-escape')
j\x6f\n

@joernhees
Copy link
Member Author

👍

mamash pushed a commit to TritonDataCenter/pkgsrc-wip that referenced this issue Feb 15, 2014
	Update package
	2013/12/31 RELEASE 4.1
======================

This is a new minor version RDFLib, which includes a handful of new features:

* A TriG parser was added (we already had a serializer) - it is
  up-to-date wrt. to the newest spec from: http://www.w3.org/TR/trig/

* The Turtle parser was made up to date wrt. to the latest Turtle spec.

* Many more tests have been added - RDFLib now has over 2000
  (passing!) tests. This is mainly thanks to the NT, Turtle, TriG,
  NQuads and SPARQL test-suites from W3C. This also included many
  fixes to the nt and nquad parsers.

* ```ConjunctiveGraph``` and ```Dataset``` now support directly adding/removing
  quads with ```add/addN/remove``` methods.

* ```rdfpipe``` command now supports datasets, and reading/writing context
  sensitive formats.

* Optional graph-tracking was added to the Store interface, allowing
  empty graphs to be tracked for Datasets. The DataSet class also saw
  a general clean-up, see: RDFLib/rdflib#309

* After long deprecation, ```BackwardCompatibleGraph``` was removed.

Minor enhancements/bugs fixed:
------------------------------

* Many code samples in the documentation were fixed thanks to @PuckCh

* The new ```IOMemory``` store was optimised a bit

* ```SPARQL(Update)Store``` has been made more generic.

* MD5 sums were never reinitialized in ```rdflib.compare```

* Correct default value for empty prefix in N3
  [#312]RDFLib/rdflib#312

* Fixed tests when running in a non UTF-8 locale
  [#344]RDFLib/rdflib#344

* Prefix in the original turtle have an impact on SPARQL query
  resolution
  [#313]RDFLib/rdflib#313

* Duplicate BNode IDs from N3 Parser
  [#305]RDFLib/rdflib#305

* Use QNames for TriG graph names
  [#330]RDFLib/rdflib#330

* \uXXXX escapes in Turtle/N3 were fixed
  [#335]RDFLib/rdflib#335

* A way to limit the number of triples retrieved from the
  ```SPARQLStore``` was added
  [#346]RDFLib/rdflib#346

* Dots in localnames in Turtle
  [#345]RDFLib/rdflib#345
  [#336]RDFLib/rdflib#336

* ```BNode``` as Graph's public ID
  [#300]RDFLib/rdflib#300

* Introduced ordering of ```QuotedGraphs```
  [#291]RDFLib/rdflib#291

2013/05/22 RELEASE 4.0.1
========================

Following RDFLib tradition, some bugs snuck into the 4.0 release.
This is a bug-fixing release:

* the new URI validation caused lots of problems, but is
  nescessary to avoid ''RDF injection'' vulnerabilities. In the
  spirit of ''be liberal in what you accept, but conservative in
  what you produce", we moved validation to serialisation time.

* the   ```rdflib.tools```   package    was   missing   from   the
  ```setup.py```  script, and  was therefore  not included  in the
  PYPI tarballs.

* RDF parser choked on empty namespace URI
  [#288](RDFLib/rdflib#288)

* Parsing from ```sys.stdin``` was broken
  [#285](RDFLib/rdflib#285)

* The new IO store had problems with concurrent modifications if
  several graphs used the same store
  [#286](RDFLib/rdflib#286)

* Moved HTML5Lib dependency to the recently released 1.0b1 which
  support python3

2013/05/16 RELEASE 4.0
======================

This release includes several major changes:

* The new SPARQL 1.1 engine (rdflib-sparql) has been included in
  the core distribution. SPARQL 1.1 queries and updates should
  work out of the box.

  * SPARQL paths are exposed as operators on ```URIRefs```, these can
    then be be used with graph.triples and friends:

    ```py
    # List names of friends of Bob:
    g.triples(( bob, FOAF.knows/FOAF.name , None ))

    # All super-classes:
    g.triples(( cls, RDFS.subClassOf * '+', None ))
    ```

      * a new ```graph.update``` method will apply SPARQL update statements

* Several RDF 1.1 features are available:
  * A new ```DataSet``` class
  * ```XMLLiteral``` and ```HTMLLiterals```
  * ```BNode``` (de)skolemization is supported through ```BNode.skolemize```,
    ```URIRef.de_skolemize```, ```Graph.skolemize``` and ```Graph.de_skolemize```

* Handled of Literal equality was split into lexical comparison
  (for normal ```==``` operator) and value space (using new ```Node.eq```
  methods). This introduces some slight backwards incomaptible
  changes, but was necessary, as the old version had
  inconsisten hash and equality methods that could lead the
  literals not working correctly in dicts/sets.
  The new way is more in line with how SPARQL 1.1 works.
  For the full details, see:

  https://github.com/RDFLib/rdflib/wiki/Literal-reworking

* Iterating over ```QueryResults``` will generate ```ResultRow``` objects,
  these allow access to variable bindings as attributes or as a
  dict. I.e.

  ```py
  for row in graph.query('select ... ') :
     print row.age, row["name"]
  ```

* "Slicing" of Graphs and Resources as syntactic sugar:
  ([#271](RDFLib/rdflib#271))

  ```py
  graph[bob : FOAF.knows/FOAF.name]
            -> generator over the names of Bobs friends
  ```

* The ```SPARQLStore``` and ```SPARQLUpdateStore``` are now included
  in the RDFLib core

* The documentation has been given a major overhaul, and examples
  for most features have been added.


Minor Changes:
--------------

* String operations on URIRefs return new URIRefs: ([#258](RDFLib/rdflib#258))
  ```py
  >>> URIRef('http://example.org/')+'test
  rdflib.term.URIRef('http://example.org/test')
  ```

* Parser/Serializer plugins are also found by mime-type, not just
  by plugin name:  ([#277](RDFLib/rdflib#277))
* ```Namespace``` is no longer a subclass of ```URIRef```
* URIRefs and Literal language tags are validated on construction,
  avoiding some "RDF-injection" issues ([#266](RDFLib/rdflib#266))
* A new memory store needs much less memory when loading large
  graphs ([#268](RDFLib/rdflib#268))
* Turtle/N3 serializer now supports the base keyword correctly ([#248](RDFLib/rdflib#248))
* py2exe support was fixed ([#257](RDFLib/rdflib#257))
* Several bugs in the TriG serializer were fixed
* Several bugs in the NQuads parser were fixed
@petrux
Copy link

petrux commented Jul 18, 2014

Hi guys. I got the same exception right now:

raise Exception('"%s" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?'%self)
Exception: "http://www.imdb.com/title/tt0091369//search/title?locations=West Wycombe Park, West Wycombe, Buckinghamshire, England, UK&ref_=tt_dt_dt" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?

Any hint?

@joernhees
Copy link
Member Author

@petrux i'm not entirely convinced that it's the same issue... your URI doesn't seem to include \uxxxx. Maybe open a separate issue and provide some minimalistic test-case which fails for you?

@petrux
Copy link

petrux commented Jul 18, 2014

@joernhees right, it's just the same error. I'll open another issue, as soon as i provide you some more information about my case. Thanks.

@petrux
Copy link

petrux commented Jul 24, 2014

@joernhees here. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working parsing Related to a parsing.
Projects
None yet
Development

No branches or pull requests

2 participants