Diff for /cdli/cdli_files.py between versions 1.47 and 1.55

version 1.47, 2006/10/05 06:38:13 version 1.55, 2006/12/22 20:35:33
Line 1 Line 1
 """CDLI extensions of the filearchive"""      """CDLI extensions of the filearchive"""    
 from Products.versionedFile.versionedFile import *  
 from Products.versionedFile.extVersionedFile import *  from Products.versionedFile.extVersionedFile import *
 from Products.ZCatalog.CatalogPathAwareness import CatalogAware  from Products.ZCatalog.CatalogPathAwareness import CatalogAware
 from tempfile import mkstemp,mkdtemp      from tempfile import mkstemp,mkdtemp    
Line 7  import os.path Line 6  import os.path
 import os  import os
 from types import *  from types import *
 import urlparse  import urlparse
   import urllib
   import cgi
 from OFS.OrderedFolder import OrderedFolder  from OFS.OrderedFolder import OrderedFolder
 from OFS.SimpleItem import SimpleItem  from OFS.SimpleItem import SimpleItem
 import time  import time
Line 20  from ZPublisher.HTTPRequest import HTTPR Line 21  from ZPublisher.HTTPRequest import HTTPR
 from ZPublisher.HTTPResponse import HTTPResponse  from ZPublisher.HTTPResponse import HTTPResponse
 from ZPublisher.BaseRequest import RequestContainer  from ZPublisher.BaseRequest import RequestContainer
 import threading  import threading
   from BTrees.OOBTree import OOBTree
   
   def unique(s):
       """Return a list of the elements in s, but without duplicates.
   
       For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
       unique("abcabc") some permutation of ["a", "b", "c"], and
       unique(([1, 2], [2, 3], [1, 2])) some permutation of
       [[2, 3], [1, 2]].
   
       For best speed, all sequence elements should be hashable.  Then
       unique() will usually work in linear time.
   
       If not possible, the sequence elements should enjoy a total
       ordering, and if list(s).sort() doesn't raise TypeError it's
       assumed that they do enjoy a total ordering.  Then unique() will
       usually work in O(N*log2(N)) time.
   
       If that's not possible either, the sequence elements must support
       equality-testing.  Then unique() will usually work in quadratic
       time.
       (from the python cookbook)
       """
   
       n = len(s)
       if n == 0:
           return []
   
       # Try using a dict first, as that's the fastest and will usually
       # work.  If it doesn't work, it will usually fail quickly, so it
       # usually doesn't cost much to *try* it.  It requires that all the
       # sequence elements be hashable, and support equality comparison.
       u = {}
       try:
           for x in s:
               u[x] = 1
       except TypeError:
           del u  # move on to the next method
       else:
           return u.keys()
   
       # We can't hash all the elements.  Second fastest is to sort,
       # which brings the equal elements together; then duplicates are
       # easy to weed out in a single pass.
       # NOTE:  Python's list.sort() was designed to be efficient in the
       # presence of many duplicate elements.  This isn't true of all
       # sort functions in all languages or libraries, so this approach
       # is more effective in Python than it may be elsewhere.
       try:
           t = list(s)
           t.sort()
       except TypeError:
           del t  # move on to the next method
       else:
           assert n > 0
           last = t[0]
           lasti = i = 1
           while i < n:
               if t[i] != last:
                   t[lasti] = last = t[i]
                   lasti += 1
               i += 1
           return t[:lasti]
   
       # Brute force is all that's left.
       u = []
       for x in s:
           if x not in u:
               u.append(x)
       return u
           
   
 class BasketContent(SimpleItem):  class BasketContent(SimpleItem):
Line 99  class uploadATFfinallyThread(Thread): Line 170  class uploadATFfinallyThread(Thread):
         conn.close()          conn.close()
         #set flag for end of this method          #set flag for end of this method
         self.end=True          self.end=True
       print "ended"
         return True          return True
           
     def __del__(self):      def __del__(self):
Line 142  class uploadATFfinallyThread(Thread): Line 214  class uploadATFfinallyThread(Thread):
             if len(founds)>0:              if len(founds)>0:
                 SESSION['author']=str(username)                  SESSION['author']=str(username)
                 self.result+="<p>Changing : %s"%fn                  self.result+="<p>Changing : %s"%fn
                 founds[0].getObject().manage_addCDLIFileObject('',comment,SESSION['author'],file=file(os.path.join(SESSION['tmpdir'],fn)))                  founds[0].getObject().manage_addCDLIFileObject('',comment,SESSION['author'],file=os.path.join(SESSION['tmpdir'],fn),from_tmp=True)
                           
                   
         #now add the new files                  #now add the new files        
Line 525  class BasketObject_old(Folder): Line 597  class BasketObject_old(Folder):
                   
         ret=""          ret=""
         lockedObjects={}          lockedObjects={}
         print "x",self.temp_folder.downloadCounter      
         if self.temp_folder.downloadCounter > 10:          if self.temp_folder.downloadCounter > 10:
             return """I am sorry, currently the server has to many requests for downloads, please come back later!"""              return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
   
Line 690  class CDLIBasketContainer(OrderedFolder) Line 762  class CDLIBasketContainer(OrderedFolder)
         self.title=title          self.title=title
             
             
       def getBasketsId(self):
           """get all baskets als klartext"""
           
           ret=""
           baskets=self.ZopeFind(self,obj_metatypes=['CDLIBasket'])
           for basket in baskets:
               com,user,time,values = basket[1].getContentIds()
               ret+= "BASKET:"+com+"\t"+user+"\t"+time+"\n"
               for x in values:
                   ret+= x[0]+"\t"+x[1]+"\n"
           return ret
   
     def getBaskets(self,sortField='title'):      def getBaskets(self,sortField='title'):
         """get all baskets files"""          """get all baskets files"""
   
Line 763  class CDLIBasketContainer(OrderedFolder) Line 847  class CDLIBasketContainer(OrderedFolder)
     def setActiveBasket(self,basketId,REQUEST=None):      def setActiveBasket(self,basketId,REQUEST=None):
         """store active basketId in a cookie"""          """store active basketId in a cookie"""
         self.REQUEST.RESPONSE.setCookie("CDLIActiveBasket",basketId,path="/")          self.REQUEST.RESPONSE.setCookie("CDLIActiveBasket",basketId,path="/")
               try:
           qs=cgi.parse_qs(REQUEST['QUERY_STRING'])
           del(qs['basketId'])
       except:
           qs={}
         if REQUEST:          if REQUEST:
             REQUEST.RESPONSE.redirect(REQUEST['URL1']+'?'+REQUEST['QUERY_STRING'])              REQUEST.RESPONSE.redirect(REQUEST['URL1']+'?'+urllib.urlencode(qs))
                           
     def getActiveBasket(self):      def getActiveBasket(self):
         """get active basket from cookie"""          """get active basket from cookie"""
Line 969  class CDLIBasket(Folder,CatalogAware): Line 1057  class CDLIBasket(Folder,CatalogAware):
         newContent=[]          newContent=[]
         added=0          added=0
         for id in ids:          for id in ids:
           try:
             founds=self.CDLICatalog.search({'title':id})              founds=self.CDLICatalog.search({'title':id})
           except:
           founds=[]
             for found in founds:              for found in founds:
                 if found.getObject() not in oldContent:                  if found.getObject() not in oldContent:
                     #TODO: was passiert wenn, man eine Object dazufŸgt, das schon da ist aber eine neuere version                      #TODO: was passiert wenn, man eine Object dazufŸgt, das schon da ist aber eine neuere version
Line 987  class CDLIBasket(Folder,CatalogAware): Line 1077  class CDLIBasket(Folder,CatalogAware):
           
         return added          return added
           
       
                   
       
       def getContentIds(self):
           """print basket content"""
           ret=[]
           lv=self.getLastVersion()
           for obj in lv.content.getContent():
               ret.append((obj[0].getId(),obj[1].getId()))
           
           
           return lv.getComment(),lv.getUser(),lv.getTime(),ret
   
     def changeBasket(self,ids,submit,RESPONSE=None,REQUEST=None):      def changeBasket(self,ids,submit,RESPONSE=None,REQUEST=None):
         """change a basket"""          """change a basket"""
         if submit=="update":          if submit=="update":
Line 1132  class CDLIBasketVersion(Implicit,Persist Line 1235  class CDLIBasketVersion(Implicit,Persist
           
                 if (procedure=="downloadAll") or (object[1].lockedBy=='') or (object[1].lockedBy==self.REQUEST['AUTHENTICATED_USER']):                  if (procedure=="downloadAll") or (object[1].lockedBy=='') or (object[1].lockedBy==self.REQUEST['AUTHENTICATED_USER']):
                     if current=="no": #version as they are in the basket                      if current=="no": #version as they are in the basket
                         ret+=str(object[0].data)+"\n"                          ret+=str(object[0].getData())+"\n"
                     elif current=="yes":                      elif current=="yes":
                         #search current object                          #search current object
                         founds=self.CDLICatalog.search({'title':object[0].getId()})                          founds=self.CDLICatalog.search({'title':object[0].getId()})
                         if len(founds)>0:                                if len(founds)>0:      
                             ret+=str(founds[0].getObject().getLastVersion().data)+"\n"                              ret+=str(founds[0].getObject().getLastVersion().getData())+"\n"
                                                           
                 if lock and object[1].lockedBy=='':                  if lock and object[1].lockedBy=='':
                     object[1].lockedBy=self.REQUEST['AUTHENTICATED_USER']                      object[1].lockedBy=self.REQUEST['AUTHENTICATED_USER']
Line 1275  class CDLIFileObject(CatalogAware,extVer Line 1378  class CDLIFileObject(CatalogAware,extVer
           
     security.declarePublic('view')      security.declarePublic('view')
                                                                                   
       def getFormattedData(self):
           """fromat text"""
           data=self.getData()
           return re.sub("\s\#lem"," #lem",data) #remove return vor #lem
           
     def view(self):      def view(self):
         """view file"""          """view file"""
         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','viewCDLIFile.zpt')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','viewCDLIFile.zpt')).__of__(self)
Line 1284  class CDLIFileObject(CatalogAware,extVer Line 1392  class CDLIFileObject(CatalogAware,extVer
     def getPNumber(self):      def getPNumber(self):
         """get the pnumber"""          """get the pnumber"""
         try:          try:
                 txt=re.match("&[Pp](\d*)\s*=([^\r\n]*)",self.data[0:])                  txt=re.match("&[Pp](\d*)\s*=([^\r\n]*)",self.getData()[0:])
         except:          except:
                 txt=self.data[0:]                  txt=self.getData()[0:]
                                   
                 return "ERROR"                  return "ERROR"
         try:          try:
Line 1311  class CDLIFileObject(CatalogAware,extVer Line 1419  class CDLIFileObject(CatalogAware,extVer
 manage_addCDLIFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject', version='1')  manage_addCDLIFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject', version='1')
   
 def manage_addCDLIFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',  def manage_addCDLIFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',
                    REQUEST=None):                               from_tmp=False,REQUEST=None):
     """Add a new File object.      """Add a new File object.
   
     Creates a new File object 'id' with the contents of 'file'"""      Creates a new File object 'id' with the contents of 'file'"""
Line 1335  def manage_addCDLIFileObject(self,id,vC= Line 1443  def manage_addCDLIFileObject(self,id,vC=
           
     # Now we "upload" the data.  By doing this in two steps, we      # Now we "upload" the data.  By doing this in two steps, we
     # can use a database trick to make the upload more efficient.      # can use a database trick to make the upload more efficient.
     if file:  
       if file and not from_tmp:
         self._getOb(id).manage_upload(file)          self._getOb(id).manage_upload(file)
       elif file and from_tmp:
           self._getOb(id).manage_upload_from_tmp(file)
     if content_type:      if content_type:
         self._getOb(id).content_type=content_type          self._getOb(id).content_type=content_type
   
     self.reindex_object()      self.reindex_object()
       self._getOb(id).reindex_object()
   
     if REQUEST is not None:      if REQUEST is not None:
         REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')          REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
           
Line 1351  class CDLIFile(extVersionedFile,CatalogA Line 1464  class CDLIFile(extVersionedFile,CatalogA
     default_catalog='CDLICatalog'      default_catalog='CDLICatalog'
           
     #security.declarePublic('history')      #security.declarePublic('history')
       def getLastVersionData(self):
           """get last version data"""
           return self.getLastVersion().getData()
   
       def getLastVersionFormattedData(self):
           """get last version data"""
           return self.getLastVersion().getFormattedData()
   
       #security.declarePublic('history')
       
       
     def history(self):      def history(self):
         """history"""            """history"""  
   
Line 1411  class CDLIFile(extVersionedFile,CatalogA Line 1535  class CDLIFile(extVersionedFile,CatalogA
                                  precondition='',                                    precondition='', 
                                  content_type='',                                   content_type='',
                                  changeName='no',newName='',                                    changeName='no',newName='', 
                                  come_from=None,RESPONSE=None):                                   come_from=None,
                                    from_tmp=False,RESPONSE=None):
         """add"""          """add"""
         
         try: #TODO: der ganze vC unsinn muss ueberarbeitet werden          try: #TODO: der ganze vC unsinn muss ueberarbeitet werden
             vC=self.REQUEST['vC']              vC=self.REQUEST['vC']
         except:          except:
Line 1445  class CDLIFile(extVersionedFile,CatalogA Line 1571  class CDLIFile(extVersionedFile,CatalogA
                 id=tmp[0]+"_V%i"%self.getVersion()                  id=tmp[0]+"_V%i"%self.getVersion()
                           
               
         manage_addCDLIFileObject(self,id,vC,author,file,id,precondition, content_type)          manage_addCDLIFileObject(self,id,vC,author,file,id,precondition, content_type,from_tmp=from_tmp)
         objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))          #objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))
           objs=getattr(self,id).setVersionNumber(int(self.getVersion()))
         try:          try:
           #FIXME: wozu ist das gut?            #FIXME: wozu ist das gut?
           self.REQUEST.SESSION['objID_parent']=self.getId()            self.REQUEST.SESSION['objID_parent']=self.getId()
Line 1497  def checkFile(filename,data,folder): Line 1624  def checkFile(filename,data,folder):
     """check the files"""      """check the files"""
     # first check the file name      # first check the file name
     fn=filename.split(".") # no extension      fn=filename.split(".") # no extension
     print "_____",fn  
     if not fn[0][0]=="P":      if not fn[0][0]=="P":
         return False,"P missing in the filename"          return False,"P missing in the filename"
     elif len(fn[0])!=7:      elif len(fn[0])!=7:
Line 1509  def checkFile(filename,data,folder): Line 1636  def checkFile(filename,data,folder):
         ret= out.close()          ret= out.close()
   
         if value:          if value:
             print "ERRR"       
             return False,"atf checker error: %s"%value              return False,"atf checker error: %s"%value
         else:          else:
             return True,""              return True,""
Line 1519  def splitatf(fh,dir=None,ext=None): Line 1646  def splitatf(fh,dir=None,ext=None):
     ret=None      ret=None
     nf=None      nf=None
     i=0      i=0
     for line in fh.readlines():  
       for lineTmp in fh.readlines():
       for line in lineTmp.split("\r"):
         if ext:          if ext:
             i+=1              i+=1
             if (i%100)==0:              if (i%100)==0:
Line 1546  def splitatf(fh,dir=None,ext=None): Line 1675  def splitatf(fh,dir=None,ext=None):
                     filename=os.path.join(dir,filename)                      filename=os.path.join(dir,filename)
                 nf=file(filename,"w")                  nf=file(filename,"w")
             if nf:                  if nf:    
                 nf.write(line)              nf.write(line.replace("\n","")+"\n")
                   
     nf.close()      nf.close()
     fh.close()      fh.close()
Line 1693  class CDLIFileFolder(extVersionedFileFol Line 1822  class CDLIFileFolder(extVersionedFileFol
                   
         catalog=getattr(self,self.default_catalog)          catalog=getattr(self,self.default_catalog)
         #tf,tfilename=mkstemp()          #tf,tfilename=mkstemp()
         print self.temp_folder.downloadCounter      if not hasattr(self.temp_folder,'downloadCounter'):
         if self.temp_folder.downloadCounter > 5:          self.temp_folder.downloadCounter=0
   
           if getattr(self.temp_folder,'downloadCounter',0) > 5:
             return """I am sorry, currently the server has to many requests for downloads, please come back later!"""              return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
   
         self.temp_folder.downloadCounter+=1          self.temp_folder.downloadCounter+=1
Line 1716  class CDLIFileFolder(extVersionedFileFol Line 1847  class CDLIFileFolder(extVersionedFileFol
                                   
                 #os.write(tf,obj.getLastVersion().data)                  #os.write(tf,obj.getLastVersion().data)
                 if RESPONSE:                  if RESPONSE:
                     RESPONSE.write(obj.getLastVersion().data[0:])                      RESPONSE.write(obj.getLastVersion().getData()[0:])
                 self.temp_folder.downloadCounter-=1                   self.temp_folder.downloadCounter-=1 
                 self._p_changed=1                  self._p_changed=1
         get_transaction().commit()          get_transaction().commit()
Line 1800  class CDLIRoot(Folder): Line 1931  class CDLIRoot(Folder):
           
     meta_type="CDLIRoot"      meta_type="CDLIRoot"
     downloadCounterBaskets=0# counts the current basket downloads if counter > 10 no downloads are possible      downloadCounterBaskets=0# counts the current basket downloads if counter > 10 no downloads are possible
       
       def showInLineIndex(self):
           """get the index for debug purposes"""
           print "show"
           for x in self.lineIndex.iterkeys():
               print "word:",x
               for y in self.lineIndex[x].iterkeys():
                   print "doc",y,self.lineIndex[x][y]
                   
           return self.lineIndex
           
       def searchInLineIndexDocs(self,word,uniq=True):
           """search occurences"""
           
               
           lst=list(self.lineIndex.get(word.upper()).keys())
           if uniq:
               return unique(lst)
           else:
               return lst
           
       def getLinesFromIndex(self,word,doc):
           """get lines"""
           return self.lineIndex[word][doc]
   
       def cleanInLineIndex(self):
           """delete InlineIndex"""
           for x in list(self.lineIndex.keys()):
               del(self.lineIndex[x])
           print [x for x in self.lineIndex.keys()]
        
           return "ok"
       
       def storeInLineIndex(self,key,value):
           """store in index"""
        
           if (not hasattr(self,'lineIndex')) or (type(self.lineIndex) is DictType):
               self.lineIndex=OOBTree()
           li=self.lineIndex
           
           if li.has_key(key):
   
   #            if li[key].has_key(value[0]) and (not (value[1] in li[key][value[0]])):
               if li[key].has_key(value[0]):
                   tmp=li[key][value[0]]
                   tmp.append(value[1]) # add it if now in the array
                   li[key][value[0]]=tmp[0:]
               else:
                   li[key][value[0]]=[value[1]] # new array for lines
                   
           else:
               
               li[key]=OOBTree()# new btree for lines
               li[key][value[0]]=[value[1]] 
                       
           
           self.lineIndex=li
        
           get_transaction().commit()
           
   
       def showFile(self,fileId):
           """show a file"""
           f=self.CDLICatalog({'title':fileId})
           if not f:
               return ""
           
           return f[0].getObject().getLastVersionFormattedData()
       
       def showLineFromFile(self,fileId,lineNum):
           """get line lineNum fromFileId"""
           
           file=self.showFile(fileId)
           str="^%s\.(.*)"%lineNum
          
           m=re.search(str,file,flags=re.M)
           if m:
               return m.group(1)
           else:
               return ""
           
     def URLquote(self,str):      def URLquote(self,str):
         """quote url"""          """quote url"""
         return urllib.quote(str)          return urllib.quote(str)
Line 1947  class CDLIRoot(Folder): Line 2159  class CDLIRoot(Folder):
                 #tmp=self.cdli_main.tmpStore2[threadName]                  #tmp=self.cdli_main.tmpStore2[threadName]
                 tmp=self._v_uploadATF[threadName].returnValue                  tmp=self._v_uploadATF[threadName].returnValue
                                   
                 #self._v_uploadATF[threadName].continueVar=False                  self._v_uploadATF[threadName].continueVar=False
                                   
                 self.REQUEST.SESSION['changed']=[x[0].getId() for x in tmp['changed']]                  self.REQUEST.SESSION['changed']=[x[0].getId() for x in tmp['changed']]
                 self.REQUEST.SESSION['lockerrors']=[x[0].getId() for x in tmp['lockerrors']]                  self.REQUEST.SESSION['lockerrors']=[x[0].getId() for x in tmp['lockerrors']]
Line 2023  class CDLIRoot(Folder): Line 2235  class CDLIRoot(Folder):
               if RESPONSE is not None:                if RESPONSE is not None:
                   RESPONSE.redirect(self.absolute_url())                    RESPONSE.redirect(self.absolute_url())
   
     def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/Documents/workspace/cdli/atf", files=None,ext=None):      def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/atf", files=None,ext=None):
         """import files"""          """import files"""
         root=self.cdli_main          root=self.cdli_main
                   count=0
         if not files:          if not files:
             files=os.listdir(folderName)              files=os.listdir(folderName)
                           
Line 2053  class CDLIRoot(Folder): Line 2265  class CDLIRoot(Folder):
             else:              else:
                 fobj2=obj2[0][1]                  fobj2=obj2[0][1]
                               
             file2=file(os.path.join(folderName,f))                 file2=os.path.join(folderName,f)  
             id=f              id=f
             manage_addCDLIFile(fobj2,f,'','')              manage_addCDLIFile(fobj2,f,'','')
             id=f              id=f
             ob=fobj2._getOb(f)              ob=fobj2._getOb(f)
             ob.title=id              ob.title=id
                           
             manage_addCDLIFileObject(ob,id,comment,author,file2,content_type='')              manage_addCDLIFileObject(ob,id,comment,author,file2,content_type='',from_tmp=True)
             self.CDLICatalog.catalog_object(ob)              self.CDLICatalog.catalog_object(ob)
             #self.CDLICatalog.manage_catalogFoundItems(obj_ids=[id],search_sub=1)              #self.CDLICatalog.manage_catalogFoundItems(obj_ids=[id],search_sub=1)
             #self.CDLICatalog.manage_catalogObject(self.REQUEST, self.REQUEST.RESPONSE, 'CDLICatalog', urlparse.urlparse(ob.absolute_url())[1])              #self.CDLICatalog.manage_catalogObject(self.REQUEST, self.REQUEST.RESPONSE, 'CDLICatalog', urlparse.urlparse(ob.absolute_url())[1])
           count+=1
                           
           if count > 1000:
           print "committing"
           get_transaction().commit()
           count=0
       get_transaction().commit()
         return "ok"          return "ok"
                     
   

Removed from v.1.47  
changed lines
  Added in v.1.55


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>