VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/common/webutils.py@ 62556

Last change on this file since 62556 was 62484, checked in by vboxsync, 8 years ago

(C) 2016

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 6.3 KB
Line 
1# -*- coding: utf-8 -*-
2# $Id: webutils.py 62484 2016-07-22 18:35:33Z vboxsync $
3
4"""
5Common Web Utility Functions.
6"""
7
8__copyright__ = \
9"""
10Copyright (C) 2012-2016 Oracle Corporation
11
12This file is part of VirtualBox Open Source Edition (OSE), as
13available from http://www.virtualbox.org. This file is free software;
14you can redistribute it and/or modify it under the terms of the GNU
15General Public License (GPL) as published by the Free Software
16Foundation, in version 2 as it comes in the "COPYING" file of the
17VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19
20The contents of this file may alternatively be used under the terms
21of the Common Development and Distribution License Version 1.0
22(CDDL) only, as it comes in the "COPYING.CDDL" file of the
23VirtualBox OSE distribution, in which case the provisions of the
24CDDL are applicable instead of those of the GPL.
25
26You may elect to license modified versions of this file under the
27terms and conditions of either the GPL or the CDDL or both.
28"""
29__version__ = "$Revision: 62484 $"
30
31# Standard Python imports.
32import os;
33import sys;
34import unittest;
35
36# Python 3 hacks:
37if sys.version_info[0] < 3:
38 from urllib2 import quote as urllib_quote;
39 from urllib import urlencode as urllib_urlencode;
40 from urllib import urlopen as urllib_urlopen;
41else:
42 from urllib.parse import quote as urllib_quote; # pylint: disable=F0401,E0611
43 from urllib.parse import urlencode as urllib_urlencode; # pylint: disable=F0401,E0611
44 from urllib.request import urlopen as urllib_urlopen; # pylint: disable=F0401,E0611
45
46# Validation Kit imports.
47from common import utils;
48
49
50def escapeElem(sText):
51 """
52 Escapes special character to HTML-safe sequences.
53 """
54 sText = sText.replace('&', '&amp;')
55 sText = sText.replace('<', '&lt;')
56 return sText.replace('>', '&gt;')
57
58def escapeAttr(sText):
59 """
60 Escapes special character to HTML-safe sequences.
61 """
62 sText = sText.replace('&', '&amp;')
63 sText = sText.replace('<', '&lt;')
64 sText = sText.replace('>', '&gt;')
65 return sText.replace('"', '&quot;')
66
67def escapeElemToStr(oObject):
68 """
69 Stringifies the object and hands it to escapeElem.
70 """
71 if utils.isString(oObject):
72 return escapeElem(oObject);
73 return escapeElem(str(oObject));
74
75def escapeAttrToStr(oObject):
76 """
77 Stringifies the object and hands it to escapeAttr. May return unicode string.
78 """
79 if utils.isString(oObject):
80 return escapeAttr(oObject);
81 return escapeAttr(str(oObject));
82
83def escapeAttrJavaScriptStringDQ(sText):
84 """ Escapes a javascript string that is to be emitted between double quotes. """
85 if '"' not in sText:
86 chMin = min(sText);
87 if ord(chMin) >= 0x20:
88 return sText;
89
90 sRet = '';
91 for ch in sText:
92 if ch == '"':
93 sRet += '\\"';
94 elif ord(ch) >= 0x20:
95 sRet += ch;
96 elif ch == '\n':
97 sRet += '\\n';
98 elif ch == '\r':
99 sRet += '\\r';
100 elif ch == '\t':
101 sRet += '\\t';
102 else:
103 sRet += '\\x%02x' % (ch,);
104 return sRet;
105
106def quoteUrl(sText):
107 """
108 See urllib.quote().
109 """
110 return urllib_quote(sText);
111
112def encodeUrlParams(dParams):
113 """
114 See urllib.urlencode().
115 """
116 return urllib_urlencode(dParams, doseq=True)
117
118def hasSchema(sUrl):
119 """
120 Checks if the URL has a schema (e.g. http://) or is file/server relative.
121 Returns True if schema is present, False if not.
122 """
123 iColon = sUrl.find(':');
124 if iColon > 0:
125 sSchema = sUrl[0:iColon];
126 if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower() and sSchema.isalpha():
127 return True;
128 return False;
129
130def getFilename(sUrl):
131 """
132 Extracts the filename from the URL.
133 """
134 ## @TODO This isn't entirely correct. Use the urlparser instead!
135 sFilename = os.path.basename(sUrl.replace('/', os.path.sep));
136 return sFilename;
137
138
139def downloadFile(sUrlFile, sDstFile, sLocalPrefix, fnLog, fnError = None, fNoProxies=True):
140 """
141 Downloads the given file if an URL is given, otherwise assume it's
142 something on the build share and copy it from there.
143
144 Raises no exceptions, returns log + success indicator instead.
145
146 Note! This method may use proxies configured on the system and the
147 http_proxy, ftp_proxy, no_proxy environment variables.
148
149 @todo Fixed build burn here. Please set default value for fNoProxies
150 to appropriate one.
151 """
152 if fnError is None:
153 fnError = fnLog;
154
155 if sUrlFile.startswith('http://') \
156 or sUrlFile.startswith('https://') \
157 or sUrlFile.startswith('ftp://'):
158 # Download the file.
159 fnLog('Downloading "%s" to "%s"...' % (sUrlFile, sDstFile));
160 try:
161 ## @todo We get 404.html content instead of exceptions here, which is confusing and should be addressed.
162 if fNoProxies:
163 oSrc = urllib_urlopen(sUrlFile);
164 else:
165 oSrc = urllib_urlopen(sUrlFile, proxies = dict());
166 oDst = utils.openNoInherit(sDstFile, 'wb');
167 oDst.write(oSrc.read());
168 oDst.close();
169 oSrc.close();
170 except Exception, oXcpt:
171 fnError('Error downloading "%s" to "%s": %s' % (sUrlFile, sDstFile, oXcpt));
172 return False;
173 else:
174 # Assumes file from the build share.
175 sSrcPath = os.path.join(sLocalPrefix, sUrlFile);
176 fnLog('Copying "%s" to "%s"...' % (sSrcPath, sDstFile));
177 try:
178 utils.copyFileSimple(sSrcPath, sDstFile);
179 except Exception, oXcpt:
180 fnError('Error copying "%s" to "%s": %s' % (sSrcPath, sDstFile, oXcpt));
181 return False;
182
183 return True;
184
185
186
187#
188# Unit testing.
189#
190
191# pylint: disable=C0111
192class CommonUtilsTestCase(unittest.TestCase):
193 def testHasSchema(self):
194 self.assertTrue(hasSchema('http://www.oracle.com/'));
195 self.assertTrue(hasSchema('https://virtualbox.com/'));
196 self.assertFalse(hasSchema('://virtualbox.com/'));
197 self.assertFalse(hasSchema('/usr/bin'));
198 self.assertFalse(hasSchema('usr/bin'));
199 self.assertFalse(hasSchema('bin'));
200 self.assertFalse(hasSchema('C:\\WINNT'));
201
202if __name__ == '__main__':
203 unittest.main();
204 # not reached.
205
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette