Add transaction subsystem definition in the use case of
[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         return bool(parsed.scheme) and bool(parsed.netloc)
39
40     @staticmethod
41     def join_url(url, relative_path):
42         """Builds a new URL from the given URL and the relative path.
43
44         Example:
45           url: http://www.githib.com/openstack/heat
46           relative_path: heat-translator
47           - joined: http://www.githib.com/openstack/heat-translator
48         """
49         if not UrlUtils.validate_url(url):
50             ExceptionCollector.appendException(
51                 ValueError(_('"%s" is not a valid URL.') % url))
52         return urljoin(url, relative_path)
53
54     @staticmethod
55     def url_accessible(url):
56         """Validates whether the given URL is accessible.
57
58         Returns true if the get call returns a 200 response code.
59         Otherwise, returns false.
60         """
61         return urllib2.urlopen(url).getcode() == 200