view JSONClient.py @ 2:e6c3334e9611

new function: getSingleRelationFromEntity
author dwinter
date Wed, 30 May 2012 16:53:45 +0200
parents 0ed5ecf36693
children 3532f1c49efb
line wrap: on
line source

from OFS.SimpleItem import SimpleItem
from Globals import package_home
import json
import SrvTxtUtils
import urllib
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
import os
import os.path
import logging

from BTrees.OOBTree import OOBTree

class JSONClient(SimpleItem):
    
    meta_type="JSONClient"
    
    manage_options=SimpleItem.manage_options+(
                {'label':'Main Config','action':'changeJSONClientConfigPT'},
               )



    _v_jsonCache={}
    
    def __init__(self,id,url):
        """init"""
        self.id=id
        self.url=url
        
    def changeJSONClientConfigPT(self):
                """change form"""
                pt=zptFile(self, 'zpt/changeJSONClientForm.zpt')
                pt.content_type="text/html"
                return pt()
  
    
    def changeJSONClientConfig(self,url,RESPONSE=None):
        """cahnge the JSON config"""
        self.url=url
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
            
      
    def getEntityLink(self,entId):
        return "https://openmind-ismi-dev.mpiwg-berlin.mpg.de/om4-ismi/browse/entityDetails.iface?eid="+str(entId)
          
    def json(self,method,params={},cache=True):
        """json aufruf"""
        
       
        paramString=urllib.urlencode(params)
        callUrl = self.url%(method,paramString)
        logging.debug(callUrl)
        if (cache is True) and (self._v_jsonCache.get(callUrl,None)!=None):
            return self._v_jsonCache.get(callUrl)
        else:
                        
            txt=SrvTxtUtils.getHttpData(callUrl)
            logging.debug(txt)
            obj= json.loads(txt)
            
            self._v_jsonCache[callUrl]=obj
        return obj


    def mapEntityAttributesToData(self,entity,type):
        attrs=entity.get('attributes')
        attrsHash={}
        for attr in attrs:
            attrsHash[attr.get('name')]=attr.get('ownValue')
        attrsHash['@type']=type
        return attrsHash
        
    def getOV(self,entId):
        if (entId)<0: #-1 falls keine Entity gefunden wurde
            return""
        obj=self.json("getEntity", {'entId':entId})
        return obj.get('entity').get('ownValue')
    
    def getSingleRelationFromEntity(self,jsonHash,type="srcRelations",relName=None,idType="sourceId"):
        ret = self.getRelationFromEntity(jsonHash,type,relName,maxNum=1)
        if len(ret)==0:
            return -1
        else:
            return ret[0].get(idType)
        
    def getRelationFromEntity(self,jsonHash,type="srcRelations",relName=None,maxNum=30):
        hash=jsonHash.get("entity")
        logging.debug(type)
        logging.debug(".................")
        logging.debug(hash)
        rels = hash.get(type,None)
        logging.debug(".................")
        logging.debug(rels)
        
        if (rels is None) or (relName is None):
            logging.debug("return")
            return rels
        ret=[]
        
        
        counter=0
        for rel in rels:
            if rel.get("name","")==relName:
                counter+=1
                ret.append(rel)
                if counter > maxNum:
                    break
     
        logging.debug("++++++++++++++++++++++++++++++")
        logging.debug(rels)
        return ret
    
    def getPubmanOutput(self,url="http://pubman.mpiwg-berlin.mpg.de/search/SearchAndExport?cqlQuery=escidoc.context.objid=escidoc:79281&exportFormat=APA&outputFormat=html_linked&sortKeys=&sortOrder=ascending&startRecord=1&maximumRecords=50",cache=True):
        """getPubmanOutput"""
       
        callUrl = url
        
        if (cache is True) and (self._v_jsonCache.get(callUrl,None)!=None):
            return self._v_jsonCache.get(callUrl)
        else:
                        
            txt=SrvTxtUtils.getHttpData(callUrl)
            logging.debug(txt)
            #obj= json.loads(txt)
            
            self._v_jsonCache[callUrl]=txt
        return txt

    def activateUrl(self,value):
        #wenn ein wert eine url ist, dass mache daraus einen entsprechende a link.
        if value.startswith("http://") or value.startswith("https://"):
            return """<a class="activatedLink" href="%s">%s</a>"""%(value,value)
        else:
            return value
                                       
                                       
    def getISMIIDfromBiographie(self,name):
        #nimmt den Filenamen und gibt die ISMI Personen ID zurueck diese liegt auf dem Server in einer Datei bio2ismi.txt
        data = str(getattr(self.biographies,'bio2ismi.txt'))
        logging.debug(data)
        for line in data.split("\n"):
            splitted= line.split("\t")
            filename=splitted[1].replace(r"\w","_")
            filename=filename.replace(r"%\d+","_")
            logging.debug(line)
            if (len(splitted)> 1) and (name in filename):
                return splitted[0]
        return ""
    
    def collectURL(self,url,name,REQUEST):
        history=REQUEST.SESSION.get('history',None);
        if history is None:
            history=[]
        
        
        if len(history)>0:#wenn der letzte Eintrag gleich dem jetzigen ist, dann nicht eintragen
            urlStored,nameStored=history[-1]
            if urlStored==url:
                return self.createBreadcrumb(REQUEST);
       
            
        history.append((url,name))
        REQUEST.SESSION.set('history',history);
        return self.createBreadcrumb(REQUEST);
        
    def collectTriple(self,s,p,o,inverse=False,REQUEST=None,RESPONSE=None):
        """collect a triple and redirect"""
        
        history=REQUEST.SESSION.get('triple',None);
        if history is None:
            history=[]
        
        
       
        if not (s,p,o) in history:
         
            history.append((s,p,o))
            REQUEST.SESSION.set('triple',history);
        
        if inverse:
            RESPONSE.redirect(s)
        else:
            RESPONSE.redirect(o)
    
    def cleanHistoryAndTriple(self,REQUEST):
        """clean history"""
        REQUEST.SESSION.set('triple',[]);
        REQUEST.SESSION.set('history',[]);
        REQUEST.response.redirect(REQUEST['HTTP_REFERER'])
           
    def getTripleAsRDF(self,REQUEST):
        """show the triple as RDF"""
        ret="""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:ismi="http://ismi.mpiwg-berlin.mpg.de/ns/"> """
        
        rdfString="""<rdf:Description rdf:about="%s">
        <ismi:%s rdf:resource="%s"/>
        <ismi:has_ownValue>%s</ismi:has_ownValue>
        </rdf:Description>"""
        
        ownValueString="""<rdf:Description rdf:about="%s">
        <ismi:has_ownValue>%s</ismi:has_ownValue>
        </rdf:Description>"""
        
        history=REQUEST.SESSION.get('triple',None);
        if history is not None:
            for triple in history:
                s,p,o=triple
                ownValue=self.getOV(s.split("=")[1])
                ret+=rdfString%(s,p,o,ownValue)
                ret+=ownValueString%(o,self.getOV(o.split("=")[1]))
                
        
        ret+="</rdf:RDF>"
        
        urlBase=REQUEST['URL0']
        ret=ret.replace("../",urlBase+"ISMI/database/")
        REQUEST.response.setHeader("Content-type", "text/rdf")
        return ret
    def createBreadcrumb(self,REQUEST):
        history=REQUEST.SESSION.get('history',None);
        if history is None:
            return ""
        
        ret=[]
        for entry in history:
            ret.append("""<a href="%s">%s</a>"""%entry)
        return "-->".join(ret)
    
    def filter(self,list,filterValue,letter,cache=True,cacheName=None):
        """filters a list of jsonObjects, gives only elements where the filterValue, begins with letter."""
        
        if cache and cacheName and (self._v_jsonCache.get(cacheName,None)!=None):
            hash = self._v_jsonCache.get(cacheName).get(filterValue,None)
            if hash is not None:
                return hash.get(letter,[])
            
        
        caches = self._v_jsonCache.get(cacheName,None)
        if caches is None:
            caches= OOBTree()
        
        hash=caches.get(filterValue,None)
        if hash is None:
            hash=OOBTree()
        
        
        for object in list:
            sortValue = object.get(filterValue).lower()
            if len(sortValue)>0:
                val = sortValue[0]
                if val=="[" and len(sortValue)>1:
                    val = sortValue[1]
            else:
                val=""    
                
            valList=hash.get(val,[])
            valList.append(object)
            hash.update({val:valList})
        
        caches.update({filterValue:hash})
           
        self._v_jsonCache.update({cacheName:caches}) 
        
        return hash.get(letter,[]), hash.keys()
            
def manage_addJSONClient(self,id,url,RESPONSE=None):
    """add a json client"""
    

    newObj=JSONClient(id,url)
    self._setObject(id,newObj)

   
    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')
        
def manage_addJSONClientForm(self):
    """form for adding JSONClient"""
    pt=zptFile(self, 'zpt/AddJSONClientForm.zpt')
    
    return pt()
    
def zptFile(self, path, orphaned=False):
    """returns a page template file from the product"""
    if orphaned:
        # unusual case
        pt=PageTemplateFile(os.path.join(package_home(globals()), path))
    else:
      
            pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self)
    return pt