Changeset 613:c57d80a649ea in documentViewer


Ignore:
Timestamp:
Oct 17, 2013, 2:25:39 PM (11 years ago)
Author:
casties
Branch:
default
Message:

CLOSED - # 281: List of thumbnails verschluckt Seite, wenn odd-scan-position gesetzt ist
https://it-dev.mpiwg-berlin.mpg.de/tracs/mpdl-project-software/ticket/281

Files:
4 edited

Legend:

Unmodified
Added
Removed
  • MpdlXmlTextServer.py

    r588 r613  
    1010import base64
    1111
    12 from SrvTxtUtils import getInt, getText, getHttpData
    13 
    14 def serialize(node):
    15     """returns a string containing an XML snippet of node"""
    16     s = ET.tostring(node, 'UTF-8')
    17     # snip off XML declaration
    18     if s.startswith('<?xml'):
    19         i = s.find('?>')
    20         return s[i+3:]
    21 
    22     return s
     12from SrvTxtUtils import getInt, getText, getHttpData, serialize
    2313
    2414
  • MpiwgXmlTextServer.py

    r610 r613  
    1212from datetime import datetime
    1313
    14 from SrvTxtUtils import getInt, getText, getHttpData
     14from SrvTxtUtils import getInt, getText, getHttpData, serialize
    1515
    1616# mapping of fields in the output of /mpiwg-mpdl-cms-web/query/GetDocInfo to documentViewer docinfo
     
    2323                    'countTocEntries' : 'numTocEntries'
    2424                    }
    25 
    26 def serialize(node):
    27     """returns a string containing an XML snippet of node"""
    28     s = ET.tostring(node, 'UTF-8')
    29     # snip off XML declaration
    30     if s.startswith('<?xml'):
    31         i = s.find('?>')
    32         return s[i+3:]
    33 
    34     return s
    3525
    3626
  • SrvTxtUtils.py

    r585 r613  
    88import stat
    99import urllib
    10 import urllib2
    1110import logging
    12 
    13 
    14 srvTxtUtilsVersion = "1.6"
     11import time
     12import re
     13import string
     14import datetime
     15try:
     16    import httplib2
     17    httplib = 'httplib2'
     18except:
     19    logging.warn("Unable to import httplib2! Falling back to urllib2!")
     20    import urllib2
     21    httplib = 'urllib2'
     22
     23import xml.etree.ElementTree as ET
     24
     25srvTxtUtilsVersion = "1.12.1"
     26
     27map_months = {'en': [u"",
     28               u"January",
     29               u"February",
     30               u"March",
     31               u"April",
     32               u"May",
     33               u"June",
     34               u"July",
     35               u"August",
     36               u"September",
     37               u"October",
     38               u"November",
     39               u"December"],
     40              'de': [u"",
     41               u"Januar",
     42               u"Februar",
     43               u"M\u00e4rz",
     44               u"April",
     45               u"Mai",
     46               u"Juni",
     47               u"Juli",
     48               u"August",
     49               u"September",
     50               u"Oktober",
     51               u"November",
     52               u"Dezember"]}
    1553
    1654def getInt(number, default=0):
     
    3876            return s.decode('latin-1')
    3977    else:
    40         return unicode(s)
     78        return s
    4179
    4280def utf8ify(s):
     
    4583    if not s:
    4684        return ""
    47     if isinstance(s, unicode):
     85    if isinstance(s, str):
     86        return s
     87    else:
    4888        return s.encode('utf-8')
    49     else:
    50         return str(s)
    5189
    5290def getText(node, recursive=0):
    53     """returns all text content of a node and its subnodes"""
     91    """returns all text content of a (etree) node and its subnodes"""
    5492    if node is None:
    5593        return ''
     
    75113
    76114
    77 
    78 def getHttpData(url, data=None, num_tries=3, timeout=10, noExceptions=False):
     115def serialize(node):
     116    """returns a string containing an XML snippet of (etree) node"""
     117    s = ET.tostring(node, 'UTF-8')
     118    # snip off XML declaration
     119    if s.startswith('<?xml'):
     120        i = s.find('?>')
     121        return s[i+3:]
     122
     123    return s
     124
     125
     126def getMonthName(mon, lang):
     127    """returns the name of the month mon in the language lang"""
     128    return map_months[lang][mon]
     129
     130
     131def getDateString(date=None, lang='en', withYear=True, monthNames=True, abbrev=False):
     132    """Return formatted date string."""
     133    if date is None:
     134        return None
     135   
     136    ds = None
     137    if callable(date.day):
     138        # callable members
     139        day = date.day()
     140        month = date.month()
     141        year = date.year()
     142    else:
     143        # data members
     144        day = date.day
     145        month = date.month
     146        year = date.year
     147       
     148    if lang.lower() == 'en':
     149        ds = "%s %s"%(getMonthName(month, lang), day)
     150        if withYear:
     151            ds += ", %s"%year
     152           
     153    elif lang.lower() == 'de':
     154        ds = "%s. %s"%(day, getMonthName(month, lang))
     155        if withYear:
     156            ds += " %s"%year
     157
     158    elif lang.lower() == 'iso':
     159        ds = date.isoformat()
     160           
     161    return ds
     162       
     163
     164def getDate(date):
     165    """return date object from date or datetime date."""
     166    if isinstance(date, datetime.datetime):
     167        # strip time
     168        return date.date()
     169   
     170    return date
     171
     172
     173def getDatetime(date):
     174    """return datetime object from date or datetime date."""
     175    if isinstance(date, datetime.date):
     176        # add time 0:00
     177        return datetime.datetime.combine(date, datetime.time())
     178   
     179    return date
     180
     181
     182def getHttpData(url, data=None, num_tries=3, timeout=10, username=None, password=None, cache=None, insecure=False, noExceptions=False):
    79183    """returns result from url+data HTTP request"""
    80184    # we do GET (by appending data to url)
     
    85189        # urlencode
    86190        url = "%s?%s"%(url,urllib.urlencode(data))
    87    
    88     response = None
     191
    89192    errmsg = None
    90     for cnt in range(num_tries):
    91         try:
    92             logging.debug("getHttpData(#%s %ss) url=%s"%(cnt+1,timeout,url))
    93             if sys.version_info < (2, 6):
    94                 # set timeout on socket -- ugly :-(
    95                 import socket
    96                 socket.setdefaulttimeout(float(timeout))
    97                 response = urllib2.urlopen(url)
    98             else:
    99                 # timeout as parameter
    100                 response = urllib2.urlopen(url,timeout=float(timeout))
    101             # check result?
    102             break
    103         except urllib2.HTTPError, e:
    104             logging.error("getHttpData: HTTP error(%s): %s"%(e.code,e))
    105             errmsg = str(e)
    106             # stop trying
    107             break
    108         except urllib2.URLError, e:
    109             logging.error("getHttpData: URLLIB error(%s): %s"%(e.reason,e))
    110             errmsg = str(e)
    111             # stop trying
    112             #break
    113 
    114     if response is not None:
    115         data = response.read()
    116         response.close()
    117         return data
     193    if httplib == 'httplib2':
     194        # use httplib2
     195        for cnt in range(num_tries):
     196            try:
     197                logging.debug("getHttp(lib2)Data(#%s %ss) url=%s"%(cnt+1,timeout,url))
     198                h = httplib2.Http(cache=cache, timeout=float(timeout), disable_ssl_certificate_validation=insecure)
     199                if username:
     200                    h.add_credentials(username, password)
     201                   
     202                resp, data = h.request(url)
     203                return data
     204           
     205            except httplib2.HttpLib2Error, e:
     206                logging.error("getHttp(lib2)Data: HTTP error(%s): %s"%(e.code,e))
     207                errmsg = str(e)
     208                # stop trying
     209                break
     210   
     211    else:
     212        # use urllib2
     213        response = None
     214        for cnt in range(num_tries):
     215            try:
     216                logging.debug("getHttpData(#%s %ss) url=%s"%(cnt+1,timeout,url))
     217                if sys.version_info < (2, 6):
     218                    # set timeout on socket -- ugly :-(
     219                    import socket
     220                    socket.setdefaulttimeout(float(timeout))
     221                    response = urllib2.urlopen(url)
     222                else:
     223                    # timeout as parameter
     224                    response = urllib2.urlopen(url,timeout=float(timeout))
     225                # check result?
     226                data = response.read()
     227                response.close()
     228                return data
     229
     230            except urllib2.HTTPError, e:
     231                logging.error("getHttpData: HTTP error(%s): %s"%(e.code,e))
     232                errmsg = str(e)
     233                # stop trying
     234                break
     235            except urllib2.URLError, e:
     236                logging.error("getHttpData: URLLIB error(%s): %s"%(e.reason,e))
     237                errmsg = str(e)
     238                # stop trying
     239                #break
    118240   
    119241    if noExceptions:
     
    134256
    135257
     258def shortenString(s, l, ellipsis='...'):
     259    """returns a string of length l (or l-1) by omitting characters in the middle of s, replacing with ellipsis."""
     260    if len(s) <= l:
     261        return s
     262   
     263    l1 = int((l - len(ellipsis)) / 2)
     264    return "%s%s%s"%(s[:l1],ellipsis,s[-l1:])
     265
     266
     267def sqlName(s, lc=True, more=''):
     268    """returns restricted ASCII-only version of string"""
     269    if s is None:
     270        return ""
     271   
     272    if not isinstance(s, basestring):
     273        # make string object
     274        s = str(s)
     275       
     276    # remove '
     277    s = s.replace("'","")
     278    # all else -> "_"
     279    s = re.sub('[^A-Za-z0-9_'+more+']','_',s)
     280    if lc:
     281        return s.lower()
     282   
     283    return s
     284
     285
    136286def getBrowserType(self):
    137     """check the browsers request to find out the browser type"""
     287    """(legacy) check the browsers request to find out the browser type"""
    138288    bt = {}
    139289    ua = self.REQUEST.get_header("HTTP_USER_AGENT")
     
    161311    return bt
    162312
    163 
  • documentViewer.py

    r612 r613  
    55from AccessControl import ClassSecurityInfo
    66from AccessControl import getSecurityManager
    7 from Globals import package_home
    87
    98import xml.etree.ElementTree as ET
    109
    1110import os
    12 import sys
    1311import urllib
    1412import logging
    1513import math
    1614import urlparse
    17 import re
    18 import string
    1915import json
    2016
     
    2319from SrvTxtUtils import getInt, utf8ify, getText, getHttpData, refreshingImageFileIndexHtml
    2420   
    25 def serializeNode(node, encoding="utf-8"):
    26     """returns a string containing node as XML"""
    27     s = ET.tostring(node)
    28    
    29     # 4Suite:
    30     #    stream = cStringIO.StringIO()
    31     #    Ft.Xml.Domlette.Print(node, stream=stream, encoding=encoding)
    32     #    s = stream.getvalue()
    33     #    stream.close()
    34     return s
    3521
    3622def getMDText(node):
     
    994980
    995981    def getPageBatch(self, start=1, rows=10, cols=2, pageFlowLtr=True, pageZero=False, minIdx=1, maxIdx=0):
    996         """returns dict with array of page information for one screenfull of thumbnails"""
     982        """Return dict with array of page information for one screenfull of thumbnails.
     983
     984        :param start: index of current page
     985        :param rows: number of rows in one batch
     986        :param cols: number of columns in one batch
     987        :param pageFlowLtr: do indexes increase from left to right
     988        :param pageZero: is there a zeroth non-visible page
     989        :param minIdx: minimum index to use
     990        :param maxIdx: maximum index to use
     991        :returns: dict with
     992            first: first page index
     993            last: last page index
     994            batches: list of all possible batches(dict: 'start': index, 'end': index)
     995            pages: list for current batch of rows(list of cols(list of pages(dict: 'idx': index)))
     996            nextStart: first index of next batch
     997            prevStart: first index of previous batch
     998        """
    997999        logging.debug("getPageBatch start=%s minIdx=%s maxIdx=%s"%(start,minIdx,maxIdx))
    9981000        batch = {}
     
    10021004
    10031005        np = maxIdx - minIdx + 1
     1006        if pageZero:
     1007            # correct number of pages for batching
     1008            np += 1
     1009           
    10041010        nb = int(math.ceil(np / float(grpsize)))
     1011       
    10051012        # list of all batch start and end points
    10061013        batches = []
     
    10171024        batch['batches'] = batches
    10181025
     1026        # list of pages for current screen
    10191027        pages = []
    10201028        if pageZero and start == minIdx:
     
    10461054           
    10471055        if start + grpsize <= maxIdx:
    1048             batch['nextStart'] = start + grpsize
     1056            if pageZero and start == minIdx:
     1057                # correct nextStart for pageZero
     1058                batch['nextStart'] = grpsize
     1059            else:
     1060                batch['nextStart'] = start + grpsize
    10491061        else:
    10501062            batch['nextStart'] = None
     
    10531065        batch['first'] = minIdx
    10541066        batch['last'] = maxIdx
     1067        logging.debug("batch: %s"%repr(batch))
    10551068        return batch
     1069       
    10561070       
    10571071    def getBatch(self, start=1, size=10, end=0, data=None, fullData=True):
Note: See TracChangeset for help on using the changeset viewer.