Mercurial > hg > ISMI_JSONClient
changeset 0:e8640aa396cd
initial
author | dwinter |
---|---|
date | Thu, 13 Oct 2011 10:51:54 +0200 |
parents | |
children | 0ed5ecf36693 |
files | .project .pydevproject JSONClient.py SrvTxtUtils.py __init__.py zpt/AddJSONClientForm.zpt |
diffstat | 6 files changed, 223 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.project Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>ISMI_JSONClient</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.python.pydev.PyDevBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.python.pydev.pythonNature</nature> + </natures> +</projectDescription>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.pydevproject Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?eclipse-pydev version="1.0"?> + +<pydev_project> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property> +<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property> +</pydev_project>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/JSONClient.py Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,95 @@ +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 + +class JSONClient(SimpleItem): + meta_type="JSONClient" + + def __init__(self,id,url): + """init""" + self.id=id + self.url=url + + def json(self,method,params={}): + """json aufruf""" + + paramString=urllib.urlencode(params) + callUrl = self.url%(method,paramString) + txt=SrvTxtUtils.getHttpData(callUrl) + logging.debug(txt) + obj= json.loads(txt) + 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): + obj=self.json("getEntity", {'entId':entId}) + return obj.get('entity').get('ownValue') + + 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 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 +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SrvTxtUtils.py Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,83 @@ +"""Utility methods for handling XML, reading HTTP, etc""" + +import sys +import urllib +import urllib2 +import logging + + +srvTxtUtilsVersion = "1.0" + +def getInt(number, default=0): + """returns always an int (0 in case of problems)""" + try: + return int(number) + except: + return int(default) + +def getText(node): + """returns all text content of a node and its subnodes""" + if node is None: + return "" + # ElementTree: + text = node.text or "" + for e in node: + text += getText(e) + if e.tail: + text += e.tail + + # 4Suite: + #nodelist=node.childNodes + #text = "" + #for n in nodelist: + # if n.nodeType == node.TEXT_NODE: + # text = text + n.data + + return text + + + +def getHttpData(url, data=None, num_tries=3, timeout=10): + """returns result from url+data HTTP request""" + # we do GET (by appending data to url) + if isinstance(data, str) or isinstance(data, unicode): + # if data is string then append + url = "%s?%s"%(url,data) + elif isinstance(data, dict) or isinstance(data, list) or isinstance(data, tuple): + # urlencode + url = "%s?%s"%(url,urllib.urlencode(data)) + + response = None + errmsg = None + for cnt in range(num_tries): + try: + logging.debug("getHttpData(#%s %ss) url=%s"%(cnt+1,timeout,url)) + if sys.version_info < (2, 6): + # set timeout on socket -- ugly :-( + import socket + socket.setdefaulttimeout(float(timeout)) + response = urllib2.urlopen(url) + else: + # timeout as parameter + response = urllib2.urlopen(url,timeout=float(timeout)) + # check result? + break + except urllib2.HTTPError, e: + logging.error("getHttpData: HTTP error(%s): %s"%(e.code,e)) + errmsg = str(e) + # stop trying + break + except urllib2.URLError, e: + logging.error("getHttpData: URLLIB error(%s): %s"%(e.reason,e)) + errmsg = str(e) + # stop trying + #break + + if response is not None: + data = response.read() + response.close() + return data + + raise IOError("ERROR fetching HTTP data from %s: %s"%(url,errmsg)) + #return None +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/__init__.py Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,11 @@ +import JSONClient + +def initialize(context): + """initialize ImageCollection""" + context.registerClass( + JSONClient.JSONClient, + constructors = ( + JSONClient.manage_addJSONClientForm, + JSONClient.manage_addJSONClient + ) + )
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/zpt/AddJSONClientForm.zpt Thu Oct 13 10:51:54 2011 +0200 @@ -0,0 +1,10 @@ +<h1 tal:replace="structure here/manage_page_header">Header</h1> +<h2>Add a JSONClient</h2> +<form action="manage_addJSONClient" method="POST"> +<div>ID : <input type="text" size="30" name="id"></div> +<div>URL String:<input type="text" size="30" name="url"></div> +<div>example: (cgi-like) http://neruda.mpiwg-berlin.mpg.de:8080/ismi-server/jsonInterface?method=%s&%s</div> +<div>example: (RESTLIKE) <div>example: (cgi-like) http://neruda.mpiwg-berlin.mpg.de:8080/ismi-server/jsonInterface/%s?%s</div></div> +<div> first %s ist for the method name second %s for the parameter </div> +<div><input type="submit"></div> +</form> \ No newline at end of file