Example #1
0
def htRecord(record):
    html = []
    wr = html.append
    wr('<table border=0 width=100%>')
    keys = record.keys()
    keys.sort()
    for key in keys:
        htKey = htmlEncode(key)

        # determine the HTML for the value
        value = record[key]
        htValue = None

        # check for special cases where we want a custom display
        if hasattr(value, '__class__'):
            if issubclass(value.__class__, Queue):
                htValue = htQueue(value)
        if key == 'timestamp':
            htValue = '%s (%s)' % (time.asctime(
                time.localtime(value)), str(value))

        # the general case:
        if not htValue:
            htValue = htmlEncode(str(value))

        wr('<tr> <td bgcolor=#EEEEEE> %s </td> <td bgcolor=#EEEEEE> %s </td> </tr>'
           % (htKey, htValue))
    wr('</table>')
    return string.join(html, '')
Example #2
0
 def writeContent(self):
     req = self.request()
     self.write('Path:<br>\n')
     self.write('<tt>%s</tt><p>\n'
         % htmlEncode(req.extraURLPath()))
     self.write('Variables:<br>\n')
     self.write('<table border="1">')
     for name in sorted(req.fields()):
         self.write('<tr><td align="right">%s:</td><td>%s</td></tr>\n'
             % (htmlEncode(name), htmlEncode(req.field(name))))
     self.write('</table><p>\n')
     self.write('Server-side path:<br>\n')
     self.write('<tt>%s</tt><p>\n' % req.serverSidePath())
Example #3
0
 def writeContent(self):
     req = self.request()
     self.write('Path:<br>\n')
     self.write('<code>%s</code><p>\n' % htmlEncode(req.extraURLPath()))
     self.write('Variables:<br>\n')
     self.write('<table>')
     for name in sorted(req.fields()):
         self.write(
             '<tr><td style="text-align:right">%s:</td><td>%s</td></tr>\n' %
             (htmlEncode(name), htmlEncode(req.field(name))))
     self.write('</table><p>\n')
     self.write('Server-side path:<br>\n')
     self.write('<code>%s</code><p>\n' % req.serverSidePath())
Example #4
0
 def htBody(self):
     """The HTML body of the page."""
     body = self.htDescription()
     if self.args:
         body += ''.join(['<p>%s</p>\n'
             % htmlEncode(str(p)) for p in self.args])
     return body
Example #5
0
 def html(self):
     trans = self._transaction
     page = trans.application()._error404
     if page:
         uri = trans.request().uri()
         return page.format(htmlEncode(uri))
     return HTTPException.html(self)
Example #6
0
    def cellContents(self, rowIndex, colIndex, value):
        """Return cell contents of CSV file.

        This is a hook for subclasses to customize the contents of a cell
        based on any criteria (including location).
        """
        return htmlEncode(value)
Example #7
0
 def htBody(self):
     """The HTML body of the page."""
     body = self.htDescription()
     if self.args:
         body += ''.join(
             ['<p>%s</p>\n' % htmlEncode(str(p)) for p in self.args])
     return body
Example #8
0
    def cellContents(self, rowIndex, colIndex, value):
        """Return cell contents of CSV file.

        This is a hook for subclasses to customize the contents of a cell
        based on any criteria (including location).
        """
        return htmlEncode(value)
Example #9
0
 def html(self):
     trans = self._transaction
     page = trans.application()._error404
     if page:
         uri = trans.request().uri()
         return page % htmlEncode(uri)
     else:
         return HTTPException.html(self)
Example #10
0
 def htBody(self):
     """The HTML body of the page."""
     body = self.htDescription()
     if self.args:  # pylint: disable=using-constant-test
         # pylint: disable=not-an-iterable
         body += ''.join('<p>{}</p>\n'.format(
             htmlEncode(str(p)) for p in self.args))
     return body
Example #11
0
def htRecord(record):
    html = []
    wr = html.append
    for key in sorted(record):
        htKey = htmlEncode(key)
        # determine the HTML for the value
        value = record[key]
        htValue = None
        # check for special cases where we want a custom display
        if hasattr(value, '__name__'):
            htValue = value.__name__
        if key == 'mtime':
            htValue = '%s (%s)' % (time.asctime(time.localtime(value)), value)
        # the general case:
        if not htValue:
            htValue = htmlEncode(str(value))
        wr('<tr><th>%s</th><td>%s</td></tr>' % (htKey, htValue))
    return '\n'.join(html)
Example #12
0
    def cellContents(self, rowIndex, colIndex, value):
        """Return cell contents of CSV file.

        This subclass adds a link to error files.
        """
        if self._headings[colIndex] == 'error report filename':
            return '<a href="_viewError?filename=%s">%s</a>' % (value, value)
        else:
            return htmlEncode(value)
Example #13
0
def htRecord(record):
    html = []
    wr = html.append
    for key in sorted(record):
        htKey = htmlEncode(key)
        # determine the HTML for the value
        value = record[key]
        htValue = None
        # check for special cases where we want a custom display
        if hasattr(value, '__name__'):
            htValue = value.__name__
        if key == 'mtime':
            htValue = '%s (%s)' % (time.asctime(time.localtime(value)), value)
        # the general case:
        if not htValue:
            htValue = htmlEncode(str(value))
        wr('<tr><th>%s</th><td>%s</td></tr>' % (htKey, htValue))
    return '\n'.join(html)
Example #14
0
 def showConsole(self, contents):
     width = self.setting('ConsoleWidth')
     if width:
         contents = charWrap(contents, self.setting('ConsoleWidth'),
                             self.setting('ConsoleHangingIndent'))
     contents = htmlEncode(contents)
     sys.stdout.write(
         '<br><p><table><tr><td bgcolor=#EEEEEE><pre>%s</pre></td></tr></table>'
         % contents)
Example #15
0
    def cellContents(self, rowIndex, colIndex, value):
        """Return cell contents of CSV file.

        This subclass adds a link to error files.
        """
        if self._headings[colIndex] == 'error report filename':
            return '<a href="_viewError?filename=%s">%s</a>' % (value, value)
        else:
            return htmlEncode(value)
Example #16
0
 def htValue(self, value, obj):
     if isinstance(value, long):
         classSerialNum = (value & 0xFFFFFFFF00000000L) >> 32
         objSerialNum = value & 0xFFFFFFFFL
         klass = obj.store().klassForId(classSerialNum)
         klassName = klass.name()
         return ('<a href="BrowseObject?class=%s&serialNum=%i">%s.%i</a>'
             % (klassName, objSerialNum, klassName, objSerialNum))
     else:
         return htmlEncode(str(value))
Example #17
0
 def htValue(self, value, obj):
     if type(value) is LongType:
         classSerialNum = (value & 0xFFFFFFFF00000000L) >> 32
         objSerialNum = value & 0xFFFFFFFFL
         klass = obj.store().klassForId(classSerialNum)
         klassName = klass.name()
         return '<a href=BrowseObject?class=%s&serialNum=%i>%s.%i</a>' % (
             klassName, objSerialNum, klassName, objSerialNum)
     else:
         return htmlEncode(str(value))
Example #18
0
	def htValue(self, value, obj):
		if type(value) is LongType:
			classSerialNum = (value & 0xFFFFFFFF00000000L) >> 32
			objSerialNum = value & 0xFFFFFFFFL
			klass = obj.store().klassForId(classSerialNum)
			klassName = klass.name()
			return '<a href="BrowseObject?class=%s&serialNum=%i">%s.%i</a>' \
				% (klassName, objSerialNum, klassName, objSerialNum)
		else:
			return htmlEncode(str(value))
Example #19
0
    def showConsole(self, contents):
        width = self.setting('ConsoleWidth')
        if width:
            contents = charWrap(contents, self.setting('ConsoleWidth'),
                self.setting('ConsoleHangingIndent'))
        contents = htmlEncode(contents)
        sys.stdout.write('''<br><br><table>
<tr><td style="background-color: #eee">
<pre>%s</pre>
</td></tr></table>''' % contents)
Example #20
0
    def showConsole(self, contents):
        width = self.setting('ConsoleWidth')
        if width:
            contents = charWrap(contents, self.setting('ConsoleWidth'),
                                self.setting('ConsoleHangingIndent'))
        contents = htmlEncode(contents)
        sys.stdout.write('''<br><br><table>
<tr><td style="background-color: #eee">
<pre>%s</pre>
</td></tr></table>''' % contents)
Example #21
0
def htRecord(record):
	html = []
	wr = html.append
	keys = record.keys()
	keys.sort()
	for key in keys:
		htKey = htmlEncode(key)
		# determine the HTML for the value
		value = record[key]
		htValue = None
		# check for special cases where we want a custom display
		if hasattr(value, '__name__'):
			htValue = value.__name__
		if key == 'mtime':
			htValue = '%s (%s)' % (time.asctime(time.localtime(value)),
				str(value))
		# the general case:
		if not htValue:
			htValue = htmlEncode(str(value))
		wr('<tr><th style="background-color:#DDD">%s</th>'
			'<td style="background-color:#EEE">%s</td></tr>'
			% (htKey, htValue))
	return '\n'.join(html)
Example #22
0
    def repr(self, value):
        """Get HTML encoded representation.

        Returns the repr() of value already HTML encoded. As a special case,
        dictionaries are nicely formatted in table.

        This is a utility method for `writeAttrs`.
        """
        if isinstance(value, dict):
            return htmlForDict(value, addSpace=self._addSpace,
                filterValueCallBack=self.filterDictValue,
                maxValueLength=self._maxValueLength)
        else:
            rep = repr(value)
            if self._maxValueLength and len(rep) > self._maxValueLength:
                rep = rep[:self._maxValueLength] + '...'
            return htmlEncode(rep)
    def repr(self, value):
        """Get HTML encoded representation.

        Returns the repr() of value already HTML encoded. As a special case,
        dictionaries are nicely formatted in table.

        This is a utility method for `writeAttrs`.
        """
        if isinstance(value, dict):
            return htmlForDict(value,
                               addSpace=self._addSpace,
                               filterValueCallBack=self.filterDictValue,
                               maxValueLength=self._maxValueLength)
        rep = repr(value)
        if self._maxValueLength and len(rep) > self._maxValueLength:
            rep = rep[:self._maxValueLength] + '...'
        return htmlEncode(rep)
Example #24
0
	def repr(self, x):
		"""Get HTML encoded representation.

		Returns the repr() of x already HTML encoded. As a special case,
		dictionaries are nicely formatted in table.

		This is a utility method for `writeAttrs`.

		"""
		if type(x) is DictType:
			return htmlForDict(x, filterValueCallBack=self.filterDictValue,
				maxValueLength=self._maxValueLength)
		else:
			rep = repr(x)
			if self._maxValueLength and len(rep) > self._maxValueLength:
				rep = rep[:self._maxValueLength] + '...'
			return htmlEncode(rep)
Example #25
0
    def sendRedirect(self, url, status=None):
        """Redirect to another url.

        This method sets the headers and content for the redirect,
        but does not change the cookies and other headers.
        Use clearCookies() or clearHeaders() as appropriate.

        See https://www.ietf.org/rfc/rfc2616 (section 10.3.3)
        and https://www.ietf.org/rfc/rfc3875 (section 6.2.3).
        """
        self.assertNotCommitted()
        self.setHeader('Status', status or '302 Found')
        self.setHeader('Location', url)
        self.setHeader('Content-Type', 'text/html')
        self.write('<html><body>This page has been redirected'
                   ' to <a href="{0}">{0}</a>.</body></html>'.format(
                       htmlEncode(url)))
Example #26
0
def main(webKitDir=None):
    if webKitDir is None:
        webKitDir = os.path.dirname(os.getcwd())
    try:
        OneShotAdapter(webKitDir).run()
    except:
        import traceback
        sys.stderr.write('[%s] [error] OneShotAdapter:'
                         ' Error while responding to request (unknown)\n' %
                         (time.asctime(time.localtime(time.time()))))
        sys.stderr.write('Python exception:\n')
        traceback.print_exc(file=sys.stderr)
        output = ''.join(traceback.format_exception(*sys.exc_info()))
        output = htmlEncode(output)
        sys.stdout.write('''Content-Type: text/html\n
<html><head><title>CGI Error</title><body>
<h3>CGI Error</h3>
<pre>%s</pre>
</body></html>\n''' % output)
Example #27
0
def main(webKitDir=None):
    if webKitDir is None:
        webKitDir = os.path.dirname(os.getcwd())
    try:
        OneShotAdapter(webKitDir).run()
    except:
        import traceback
        sys.stderr.write('[%s] [error] OneShotAdapter:'
            ' Error while responding to request (unknown)\n'
            % (time.asctime(time.localtime(time.time()))))
        sys.stderr.write('Python exception:\n')
        traceback.print_exc(file=sys.stderr)
        output = ''.join(traceback.format_exception(*sys.exc_info()))
        output = htmlEncode(output)
        sys.stdout.write('''Content-Type: text/html\n
<html><head><title>CGI Error</title><body>
<h3>CGI Error</h3>
<pre>%s</pre>
</body></html>\n''' % output)
Example #28
0
def encodeWithIndentation(html):
	html = string.replace(htmlEncode(html), '  ', '&nbsp; ')
	return string.replace(html, '\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
Example #29
0
def encodeWithIndentation(html):
	html = htmlEncode(html).replace('  ', '&nbsp; ')
	return html.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
Example #30
0
File: Doc.py Project: Cito/w4py
    def generateHTML(self):
        path = os.path.join(self.outDir, self.model.name()+'.html')
        wr = open(path, 'w').write
        wr('''
<html>

<head>
<link rel="stylesheet" type="text/css" href="%s">
</head>

<body>
<a name=#top></a>
''' % self.destStyleSheetFilename)

        wr('<div class="head1">%s Model (MiddleKit)</div>\n'
            % self.model.name())
        wr('Generated on %s <br>\n' % time.asctime())
        wr('From %s <br>\n' % self.model.filename())

        wr('<br>\n')

        wr('<table>\n')
        wr('<tr class="Class">'
            '<td class="ClassName" colspan="3">Classes</td></tr>\n')
        wr('<tr class="AttrTitles"><td class=AttrTitles>In Alpha Order</td>'
            '<td class="AttrTitles">In Inheritance Order</td></tr>\n')
        wr('<tr><td style="vertical-align:top">\n')
        klasses = self.model.allKlassesInOrder()
        for klass in sorted(klasses, key=lambda klass: klass.name().lower()):
            name = klass.name()
            wr('<a href="#%s">%s</a><br>\n' % (name, name))
        wr('<td style="vertical-align:top">')
        for klass in klasses:
            if not klass.superklass():
                self.writeKlassLinkAndRecurse(wr, klass)
        wr('</table>\n')

        for klass in klasses:
            name = klass.name()
            wr('''
<a id="%(name)s"></a>
<table class="Class">
<tr class="ClassName">
    <td class="ClassName" colspan="7">
        <table style="width:100%%">
            <tr>
                <td class="ClassName">%(name)s</td>
                <td class="Top" style="text-align:right"><a href="#top">top</a></td>
            </tr>
        </table>
    </td>
</tr>
            ''' % locals())

            wr('<tr class="ClassInfo"><td class="ClassInfo" colspan="7">\n')

            # ancestor classes
            wr('<table>\n')
            if klass.get('isAbstract'):
                wr('<tr><td style="vertical-align:top">abstract:</td>'
                    '<td style="vertical-align:top">yes</td></tr>\n')
            wr('<tr><td style="vertical-align:top">ancestors:</td>'
               '<td style="vertical-align:top">')
            ancestor = klass.superklass()
            if ancestor:
                while ancestor:
                    name = ancestor.name()
                    wr(' <a href="#%s">%s</a>&nbsp;' % (name, name))
                    ancestor = ancestor.superklass()
            else:
                wr('none')
            wr('</td></tr>\n')

            # subclasses
            wr('<tr><td style="vertical-align:top">subclasses:</td>'
               '<td style="vertical-align:top">\n')
            if klass.subklasses():
                for subklass in klass.subklasses():
                    name = subklass.name()
                    wr('<a href="#%s">%s</a>&nbsp;' % (name, name))
            else:
                wr('none')
            wr('</td></tr>\n')

            # notes
            wr('<tr> <td style="vertical-align:top">notes:</td>'
               '<td style="vertical-align:top">')
            if klass.get('Notes'):
                wr(htmlEncode(klass['Notes']))
            else:
                wr('none')
            wr('</td></tr>\n')

            wr('</table>\n')

            wr('''
<tr class="AttrTitles">
<td class="AttrTitles">Name</td>
<td class="AttrTitles">Type</td>
<td class="AttrTitles">IsRequired</td>
<td class="AttrTitles">Default</td>
<td class="AttrTitles">Notes</td>
</tr>
''')

            for attr in klass.allAttrs():
                # print attr
                values = Values(attr)
                if attr.klass() is klass:
                    values['Prefix'] = ''
                else:
                    values['Prefix'] = 'Inh'
                values['Type'] = attr.htmlForType()
                wr('''
<tr class="Attr">
<td class="%(Prefix)sAttrName">%(Name)s</td>
<td class="%(Prefix)sAttr">%(Type)s</td>
<td class="%(Prefix)sAttr">%(isRequired)s</td>
<td class="%(Prefix)sAttr">%(Default)s</td>
''' % values)
                notes = []
                if attr.get('Notes'):
                    notes.append(htmlEncode(attr.get('Notes')))
                for key in self.otherKeys:
                    if attr.get(key) is not None:
                        notes.append('%s = %s' % (key, attr[key]))

                if notes:
                    notes = '<br>'.join(notes)
                    notes = mystr(notes)
                    values['Notes'] = notes
                    # wr('<tr class=Attr><td class=%(Prefix)sAttr>&nbsp;</td>'
                    # '<td class=%(Prefix)sAttrNotes colspan=7>%(Notes)s</td>'
                    # '</tr>\n' % values)
                    wr('<td class="%(Prefix)sAttrNotes">%(Notes)s</td>\n' % values)
                else:
                    wr('<td class="%(Prefix)sAttrNotes">&nbsp;</td>\n' % values)
                wr('</tr>')
            wr('</table>\n')
        wr('</body></html>\n')
Example #31
0
 def description(self):
     return ('The resource you are accessing has been moved to'
         ' <a href="%s">%s</a>' % ((htmlEncode(self.location()),)*2))
Example #32
0
 def description(self):
     return ('The resource you are accessing has been moved to'
             ' <a href="{0}">{0}</a>'.format(htmlEncode(self.location())))
Example #33
0
def encodeWithIndentation(html):
    """Encode HTML and create indentation from tab characters."""
    html = htmlEncode(html).replace('  ', '&nbsp; ')
    return html.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
Example #34
0
 def htValue(self, value, obj):
     return htmlEncode(str(value))
Example #35
0
    def generateHTML(self):
        path = os.path.join(self.outDir, self.model.name() + '.html')
        wr = open(path, 'w').write
        wr('''
<html>

<head>
<link rel="stylesheet" type="text/css" href="%s">
</head>

<body>
<a name=#top></a>
''' % self.destStyleSheetFilename)

        wr('<div class="head1">%s Model (MiddleKit)</div>\n' %
           self.model.name())
        wr('Generated on %s <br>\n' % time.asctime())
        wr('From %s <br>\n' % self.model.filename())

        wr('<br>\n')

        wr('<table>\n')
        wr('<tr class="Class">'
           '<td class="ClassName" colspan="3">Classes</td></tr>\n')
        wr('<tr class="AttrTitles"><td class=AttrTitles>In Alpha Order</td>'
           '<td class="AttrTitles">In Inheritance Order</td></tr>\n')
        wr('<tr><td style="vertical-align:top">\n')
        klasses = self.model.allKlassesInOrder()
        for klass in sorted(klasses, key=lambda klass: klass.name().lower()):
            name = klass.name()
            wr('<a href="#%s">%s</a><br>\n' % (name, name))
        wr('<td style="vertical-align:top">')
        for klass in klasses:
            if not klass.superklass():
                self.writeKlassLinkAndRecurse(wr, klass)
        wr('</table>\n')

        for klass in klasses:
            name = klass.name()
            wr('''
<a id="%(name)s"></a>
<table class="Class">
<tr class="ClassName">
    <td class="ClassName" colspan="7">
        <table style="width:100%%">
            <tr>
                <td class="ClassName">%(name)s</td>
                <td class="Top" style="text-align:right"><a href="#top">top</a></td>
            </tr>
        </table>
    </td>
</tr>
            ''' % locals())

            wr('<tr class="ClassInfo"><td class="ClassInfo" colspan="7">\n')

            # ancestor classes
            wr('<table>\n')
            if klass.get('isAbstract'):
                wr('<tr><td style="vertical-align:top">abstract:</td>'
                   '<td style="vertical-align:top">yes</td></tr>\n')
            wr('<tr><td style="vertical-align:top">ancestors:</td>'
               '<td style="vertical-align:top">')
            ancestor = klass.superklass()
            if ancestor:
                while ancestor:
                    name = ancestor.name()
                    wr(' <a href="#%s">%s</a>&nbsp;' % (name, name))
                    ancestor = ancestor.superklass()
            else:
                wr('none')
            wr('</td></tr>\n')

            # subclasses
            wr('<tr><td style="vertical-align:top">subclasses:</td>'
               '<td style="vertical-align:top">\n')
            if klass.subklasses():
                for subklass in klass.subklasses():
                    name = subklass.name()
                    wr('<a href="#%s">%s</a>&nbsp;' % (name, name))
            else:
                wr('none')
            wr('</td></tr>\n')

            # notes
            wr('<tr> <td style="vertical-align:top">notes:</td>'
               '<td style="vertical-align:top">')
            if klass.get('Notes'):
                wr(htmlEncode(klass['Notes']))
            else:
                wr('none')
            wr('</td></tr>\n')

            wr('</table>\n')

            wr('''
<tr class="AttrTitles">
<td class="AttrTitles">Name</td>
<td class="AttrTitles">Type</td>
<td class="AttrTitles">IsRequired</td>
<td class="AttrTitles">Default</td>
<td class="AttrTitles">Notes</td>
</tr>
''')

            for attr in klass.allAttrs():
                # print attr
                values = Values(attr)
                if attr.klass() is klass:
                    values['Prefix'] = ''
                else:
                    values['Prefix'] = 'Inh'
                values['Type'] = attr.htmlForType()
                wr('''
<tr class="Attr">
<td class="%(Prefix)sAttrName">%(Name)s</td>
<td class="%(Prefix)sAttr">%(Type)s</td>
<td class="%(Prefix)sAttr">%(isRequired)s</td>
<td class="%(Prefix)sAttr">%(Default)s</td>
''' % values)
                notes = []
                if attr.get('Notes'):
                    notes.append(htmlEncode(attr.get('Notes')))
                for key in self.otherKeys:
                    if attr.get(key) is not None:
                        notes.append('%s = %s' % (key, attr[key]))

                if notes:
                    notes = '<br>'.join(notes)
                    notes = mystr(notes)
                    values['Notes'] = notes
                    # wr('<tr class=Attr><td class=%(Prefix)sAttr>&nbsp;</td>'
                    # '<td class=%(Prefix)sAttrNotes colspan=7>%(Notes)s</td>'
                    # '</tr>\n' % values)
                    wr('<td class="%(Prefix)sAttrNotes">%(Notes)s</td>\n' %
                       values)
                else:
                    wr('<td class="%(Prefix)sAttrNotes">&nbsp;</td>\n' %
                       values)
                wr('</tr>')
            wr('</table>\n')
        wr('</body></html>\n')
Example #36
0
def encodeWithIndentation(html):
    """Encode HTML and create indentation from tab characters."""
    html = htmlEncode(html).replace('  ', '&nbsp; ')
    return html.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;')
Example #37
0
	def htValue(self, value, obj):
		return htmlEncode(str(value))
Example #38
0
    def run(self):

        timestamp = time.time() # start time

        # to capture the console output of the application
        stdout, sys.stdout = sys.stdout, StringIO()

        try:

            # MS Windows: no special translation of end-of-lines
            if os.name == 'nt':
                import msvcrt
                msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)

            requestDict = dict(
                format='CGI', time=timestamp,
                # ce: a little tricky. We use marshal which only works
                # on built-in types, so we need environ's dictionary:
                environ=os.environ.data, input=sys.stdin)

            from WebKit import Profiler
            Profiler.startTime = time.time()

            print 'ONE SHOT MODE\n'

            from WebKit.OneShotAppServer import OneShotAppServer
            appSvr = OneShotAppServer(self._webKitDir)

            # It is important to call transaction.die() after using it, rather than
            # just letting it fall out of scope, to avoid circular references
            from WebKit.ASStreamOut import ASStreamOut
            rs = ASStreamOut()
            transaction = appSvr.dispatchRawRequest(requestDict, rs)
            rs.close()
            if transaction:
                transaction.die()
                del transaction

            appSvr.shutDown()
            appSvr = None

            print "AppServer run time %.2f seconds" % (time.time() - Profiler.startTime)

            sys.stdout = stdout

            # MS Windows: no special translation of end-of-lines
            if os.name == 'nt':
                import msvcrt
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

            response = rs._buffer
            if response:
                sys.stdout.write(response)
            else:
                sys.stdout.write('''Content-Type: text/html\n
<html><head><title>WebKit CGI Error</title><body>
<h3>WebKit CGI Error</h3>
<h4>No response from application server</h4>
</body></html>\n''')

            if self.setting('ShowConsole'):
                # show the contents of the console,
                # but only if we are serving up an HTML file
                endheaders = response.find("\r\n\r\n")
                if endheaders < 0:
                    endheaders = response.find("\n\n")
                if not endheaders:
                    print "No Headers Found"
                    return
                headers = response[:endheaders].split("\n")
                entries = []
                for header in headers:
                    if header:
                        entries.append(header.split(":", 1))
                found = False
                for name, value in entries:
                    if name.lower() == 'content-type':
                        found = True
                        break
                if found and value.strip().lower() == 'text/html':
                    self.showConsole(_console.getvalue())
        except:
            import traceback
            sys.stderr.write('[%s] [error] WebKit.OneShotAdapter:'
                ' Error while responding to request (unknown)\n'
                % (time.asctime(time.localtime(time.time()))))
            sys.stderr.write('Python exception:\n')
            traceback.print_exc(file=sys.stderr)
            sys.stdout = stdout
            output = ''.join(traceback.format_exception(*sys.exc_info()))
            output = htmlEncode(output)
            sys.stdout.write('''Content-Type: text/html\n
<html><head><title>WebKit CGI Error</title><body>
<h3>WebKit CGI Error</h3>
<pre>%s</pre>
</body></html>\n''' % output)
Example #39
0
 def description(self):
     return ('The resource you are accessing has been moved to'
             ' <a href="%s">%s</a>' % ((htmlEncode(self.location()), ) * 2))
Example #40
0
    def run(self):

        timestamp = time.time()  # start time

        # to capture the console output of the application
        stdout, sys.stdout = sys.stdout, StringIO()

        try:

            # MS Windows: no special translation of end-of-lines
            if os.name == 'nt':
                import msvcrt
                msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)

            requestDict = dict(
                format='CGI',
                time=timestamp,
                # ce: a little tricky. We use marshal which only works
                # on built-in types, so we need environ's dictionary:
                environ=os.environ.data,
                input=sys.stdin)

            from WebKit import Profiler
            Profiler.startTime = time.time()

            print 'ONE SHOT MODE\n'

            from WebKit.OneShotAppServer import OneShotAppServer
            appSvr = OneShotAppServer(self._webKitDir)

            # It is important to call transaction.die() after using it, rather than
            # just letting it fall out of scope, to avoid circular references
            from WebKit.ASStreamOut import ASStreamOut
            rs = ASStreamOut()
            transaction = appSvr.dispatchRawRequest(requestDict, rs)
            rs.close()
            if transaction:
                transaction.die()
                del transaction

            appSvr.shutDown()
            appSvr = None

            print "AppServer run time %.2f seconds" % (time.time() -
                                                       Profiler.startTime)

            sys.stdout = stdout

            # MS Windows: no special translation of end-of-lines
            if os.name == 'nt':
                import msvcrt
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

            response = rs._buffer
            if response:
                sys.stdout.write(response)
            else:
                sys.stdout.write('''Content-Type: text/html\n
<html><head><title>WebKit CGI Error</title><body>
<h3>WebKit CGI Error</h3>
<h4>No response from application server</h4>
</body></html>\n''')

            if self.setting('ShowConsole'):
                # show the contents of the console,
                # but only if we are serving up an HTML file
                endheaders = response.find("\r\n\r\n")
                if endheaders < 0:
                    endheaders = response.find("\n\n")
                if not endheaders:
                    print "No Headers Found"
                    return
                headers = response[:endheaders].split("\n")
                entries = []
                for header in headers:
                    if header:
                        entries.append(header.split(":", 1))
                found = False
                for name, value in entries:
                    if name.lower() == 'content-type':
                        found = True
                        break
                if found and value.strip().lower() == 'text/html':
                    self.showConsole(_console.getvalue())
        except:
            import traceback
            sys.stderr.write('[%s] [error] WebKit.OneShotAdapter:'
                             ' Error while responding to request (unknown)\n' %
                             (time.asctime(time.localtime(time.time()))))
            sys.stderr.write('Python exception:\n')
            traceback.print_exc(file=sys.stderr)
            sys.stdout = stdout
            output = ''.join(traceback.format_exception(*sys.exc_info()))
            output = htmlEncode(output)
            sys.stdout.write('''Content-Type: text/html\n
<html><head><title>WebKit CGI Error</title><body>
<h3>WebKit CGI Error</h3>
<pre>%s</pre>
</body></html>\n''' % output)
Example #41
0
 def htmlEncode(s):
     if isinstance(s, unicode):
         s = s.encode('utf-8')
     return htmlEncode(s)
Example #42
0
	def generateHTML(self):
		path = os.path.join(self.outDir, self.model.name()+'.html')
		file = open(path, 'w')
		wr = file.write
		wr('''
<html>

<head>
	<link rel=stylesheet type=text/css href=%s>
</head>

<body>
<a name=#top></a>
''' % self.destStyleSheetFilename)

		wr('<div class=head1>%s Model (MiddleKit)</div>\n' % self.model.name())
		wr('Generated on %s <br>\n' % time.asctime())
		wr('From %s <br>\n' % self.model.filename())

		wr('<br>\n')

		wr('<table border=0 cellpadding=2 cellspacing=2>\n')
		wr('<tr class=Class> <td class=ClassName colspan=3> Classes </td> </tr>\n')
		wr('<tr class=AttrTitles> <td class=AttrTitles> In Alpha Order </td> <td class=AttrTitles> In Inheritance Order </td> </tr>\n')
		wr('<tr> <td valign=top>\n')
		klasses = self.model.allKlassesInOrder()[:]
		klasses.sort(lambda a, b: cmp(a.name().lower(), b.name().lower()))
		for klass in klasses:
			name = klass.name()
			wr('<a href=#%s>%s</a> <br>\n' % (name, name))
		wr('<td valign=top>')
		for klass in self.model.allKlassesInOrder():
			if not klass.superklass():
				self.writeKlassLinkAndRecurse(wr, klass)
		wr('</table>\n')

		for klass in self.model.allKlassesInOrder():
			name = klass.name()
			wr('''
<a name="%(name)s"></a>
<table class=Class cellspacing=2 cellpadding=2>
	<tr class=ClassName>
		<td class=ClassName colspan=7>
			<table border=0 cellpadding=0 cellspacing=0 width=100%%>
				<tr>
					<td class=ClassName> %(name)s </td>
					<td class=Top align=right> <a href=#top>top</a> </td>
				</tr>
			</table>
		</td>
	</tr>
			''' % locals())

			wr('<tr class=ClassInfo> <td class=ClassInfo colspan=7>\n')

			# ancestor classes
			wr('<table border=0 cellpadding=3 cellspacing=0>\n')
			if klass.get('isAbstract'):
				wr('<tr> <td valign=top> abstract: </td> <td valign=top> yes </td> </tr>\n')
			wr('<tr> <td valign=top> ancestors: </td> <td valign=top> ')
			ancestor = klass.superklass()
			if ancestor:
				while ancestor:
					name = ancestor.name()
					wr(' <a href=#%s>%s</a>&nbsp; ' % (name, name))
					ancestor = ancestor.superklass()
			else:
				wr(' none ')
			wr('</td> </tr>\n')

			# subclasses
			wr('<tr> <td valign=top> subclasses: </td> <td valign=top>\n')
			if klass.subklasses():
				for subklass in klass.subklasses():
					name = subklass.name()
					wr(' <a href=#%s>%s</a>&nbsp; ' % (name, name))
			else:
				wr('none')
			wr('</td> </tr>\n')

			# notes
			wr('<tr> <td valign=top> notes: </td> <td valign=top> ')
			if klass.get('Notes'):
				wr(htmlEncode(klass['Notes']))
			else:
				wr('none')
			wr('</td> </tr>\n')

			wr('</table>\n')

			wr('''
<tr class=AttrTitles>
	<td class=AttrTitles> Name </td>
	<td class=AttrTitles> Type </td>
	<td class=AttrTitles> IsRequired </td>
	<td class=AttrTitles> Default </td>
	<td class=AttrTitles> Notes </td>
</tr>
''')

			for attr in klass.allAttrs():
				#print attr
				values = Values(attr)
				if attr.klass() is klass:
					values['Prefix'] = ''
				else:
					values['Prefix'] = 'Inh'
				values['Type'] = attr.htmlForType()
				wr('''
<tr class=Attr>
	<td class=%(Prefix)sAttrName> %(Name)s </td>
	<td class=%(Prefix)sAttr> %(Type)s </td>
	<td class=%(Prefix)sAttr> %(isRequired)s </td>
	<td class=%(Prefix)sAttr> %(Default)s </td>
''' % values)
				notes = []
				if attr.get('Notes'):
					notes.append(htmlEncode(attr.get('Notes')))
				for key in self.otherKeys:
					if attr.get(key) is not None:
						notes.append('%s = %s' % (key, attr[key]))

				if notes:
					notes = ' <br> '.join(notes)
					notes = mystr(notes)
					values['Notes'] = notes
					# wr('<tr class=Attr><td class=%(Prefix)sAttr>&nbsp;</td>'
					# '<td class=%(Prefix)sAttrNotes colspan=7>%(Notes)s</td>'
					# '</tr>\n' % values)
					wr('<td class=%(Prefix)sAttrNotes> %(Notes)s </td>\n' % values)
				else:
					wr('<td class=%(Prefix)sAttrNotes> &nbsp; </td>\n' % values)
				wr('</tr>')
			wr('</table>\n')
		wr('</body> </html>\n')
Example #43
0
def htQueue(queue):
    # @@ 2002-03-21 ce: Could probably do something nicer here in the
    # future, like put a <br> in between each element of the queue.
    return 'Queue: ' + htmlEncode(str(queue.queue))