1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements. See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License. You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from urlparse import urljoin
19 from ...extension import parser
20 from ...utils.collections import StrictList
21 from ...utils.uris import as_file
22 from .loader import Loader
23 from .file import FileTextLoader
24 from .request import RequestTextLoader
25 from .exceptions import DocumentNotFoundException
28 class UriTextLoader(Loader):
30 Base class for ARIA URI loaders.
32 See :class:`~aria.parser.loading.UriLocation`.
34 Supports a list of search prefixes that are tried in order if the URI cannot be found.
37 * If ``origin_location`` is provided its prefix will come first.
38 * Then the prefixes in the :class:`LoadingContext` will be added.
39 * Finally, the parser can supply a ``uri_loader_prefix`` function with extra prefixes.
42 def __init__(self, context, location, origin_location=None):
43 self.context = context
44 self.location = location
45 self._prefixes = StrictList(value_class=basestring)
48 def add_prefix(prefix):
49 if prefix and (prefix not in self._prefixes):
50 self._prefixes.append(prefix)
52 def add_prefixes(prefixes):
53 for prefix in prefixes:
56 if origin_location is not None:
57 add_prefix(origin_location.prefix)
59 add_prefixes(context.prefixes)
60 add_prefixes(parser.uri_loader_prefix())
64 self._open(self.location.uri)
66 except DocumentNotFoundException:
67 # Try prefixes in order
68 for prefix in self._prefixes:
69 prefix_as_file = as_file(prefix)
70 if prefix_as_file is not None:
71 uri = os.path.join(prefix_as_file, self.location.uri)
73 uri = urljoin(prefix, self.location.uri)
77 except DocumentNotFoundException:
79 raise DocumentNotFoundException('document not found at URI: "%s"' % self.location)
82 if self._loader is not None:
86 return self._loader.load() if self._loader is not None else None
89 the_file = as_file(uri)
90 if the_file is not None:
92 loader = FileTextLoader(self.context, uri)
94 loader = RequestTextLoader(self.context, uri)
95 loader.open() # might raise an exception
97 self.location.uri = uri