Bug fixe version info print
[parser.git] / tosca2heat / tosca-parser / toscaparser / utils / urlutils.py
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13
14 from six.moves.urllib.parse import urljoin
15 from six.moves.urllib.parse import urlparse
16 from toscaparser.common.exception import ExceptionCollector
17 from toscaparser.utils.gettextutils import _
18
19 try:
20     # Python 3.x
21     import urllib.request as urllib2
22 except ImportError:
23     # Python 2.x
24     import urllib2
25
26
27 class UrlUtils(object):
28
29     @staticmethod
30     def validate_url(path):
31         """Validates whether the given path is a URL or not.
32
33         If the given path includes a scheme (http, https, ftp, ...) and a net
34         location (a domain name such as www.github.com) it is validated as a
35         URL.
36         """
37         parsed = urlparse(path)
38         if parsed.scheme == 'file':
39             # If the url uses the file scheme netloc will be ""
40             return True
41         else:
42             return bool(parsed.scheme) and bool(parsed.netloc)
43
44     @staticmethod
45     def join_url(url, relative_path):
46         """Builds a new URL from the given URL and the relative path.
47
48         Example:
49           url: http://www.githib.com/openstack/heat
50           relative_path: heat-translator
51           - joined: http://www.githib.com/openstack/heat-translator
52         """
53         if not UrlUtils.validate_url(url):
54             ExceptionCollector.appendException(
55                 ValueError(_('"%s" is not a valid URL.') % url))
56         return urljoin(url, relative_path)
57
58     @staticmethod
59     def url_accessible(url):
60         """Validates whether the given URL is accessible.
61
62         Returns true if the get call returns a 200 response code.
63         Otherwise, returns false.
64         """
65         return urllib2.urlopen(url).getcode() == 200