📄 input.py
字号:
## Copyright (c) 2005, John Mettraux, OpenWFE.org# All rights reserved.# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met:# # . Redistributions of source code must retain the above copyright notice, this# list of conditions and the following disclaimer. # # . Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution.# # . Neither the name of the "OpenWFE" nor the names of its contributors may be# used to endorse or promote products derived from this software without# specific prior written permission.# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.## $Id: input.py,v 1.27 2005/07/27 18:58:08 jmettraux Exp $#""" [java] python classes for web attribute input handling $Id: input.py,v 1.27 2005/07/27 18:58:08 jmettraux Exp $"""#jython = (osName == 'java')#jython = globals().has_key('jython')## reminding java packages to jython# (needed when running in a webappserver like Tomcat)#import syssys.add_package('org.apache.log4j')sys.add_package('org.apache.commons.fileupload')sys.add_package('openwfe.org')sys.add_package('openwfe.org.input')sys.add_package('openwfe.org.engine.workitem')#print 'sys.path : %s' % sys.pathfrom java.io import Filefrom java.net import URLEncoder, URLDecoderfrom java.lang import Stringfrom org.apache.log4j import Loggerfrom org.apache.commons.fileupload import FileItemfrom org.apache.commons.fileupload import FileUploadfrom org.apache.commons.fileupload import DiskFileUploadfrom openwfe.org import Utilsfrom openwfe.org.engine.workitem import Attributefrom openwfe.org.engine.workitem import StringAttributefrom openwfe.org.engine.workitem import IntegerAttributefrom openwfe.org.engine.workitem import LongAttributefrom openwfe.org.engine.workitem import DoubleAttributefrom openwfe.org.engine.workitem import BooleanAttributefrom openwfe.org.engine.workitem import MapAttributefrom openwfe.org.engine.workitem import StringMapAttributefrom openwfe.org.engine.workitem import ListAttribute#from openwfe.org.input import InputHelperfrom openwfe.org.input import OwfeRequest, Uploaddef quote (s): return URLEncoder.encode(s, "UTF-8")def unquote (s): return URLDecoder.decode(s, "UTF-8")log = Logger.getLogger('input.py')_oldlen = lendef len (seq): if isinstance(seq, ListAttribute) or isinstance(seq, MapAttribute): return seq.size() return _oldlen(seq)UPLOAD_PATH = '/tmp'if File.separator != '/': UPLOAD_PATH = 'c:\\temp'## SOME CONSTANTSNONE = "---"POINT = '.'#POINT_REGEX = '\\.'DOUBLE_POINT = '..'#DOUBLE_POINT_REGEX = '\\.\\.'OWFE = 'owfe' + DOUBLE_POINTDELETE_SUFFIX = '__delete__'P_DELETE_PREFIX = 'deleteprefix'P_DELETE_FIELD = 'deletefield'P_MOVE_UP = 'moveup'P_MOVE_DOWN = 'movedown'P_NEW_FIELD_NAME = 'newfieldname'SIZE = 'size'MAXLENGTH = 'maxlength'PREFIX_FOR_NEW_ELEMENT = 'prefixfornewelement'## some web constantsMSG_EMPTY_LIST = '<i>--empty list--</i>'MSG_EMPTY_MAP = '<i>--empty map--</i>'MSG_KEY = '<font size=-1 color=blue>Key :</font>'MSG_VALUE = '<font size=-1 color=blue>Value :</font>'ACT_UPDATE = '/webclient/update.action'IMG_OK = '<img src=/webclient/images/ok.png border=0 alt="validate choice">'IMG_UP = '<img src=/webclient/images/up.png border=0 alt="move item up">'IMG_DOWN = '<img src=/webclient/images/down.png border=0 alt="move item down">'IMG_LINK = '<img src=/webclient/images/link.png border=0 alt="display link in new window" align=right>'IMG_PLUS = '<img src=/webclient/images/plus.png border=0 alt="add item">'IMG_MINUS = '<img src=/webclient/images/minus.png border=0 alt="remove item">'## THE METHODSdef _neutralize (s): s = s.replace('>', '>') s = s.replace('<', '<') return sdef startsWith (s, start): """ same as java.lang.String.startsWith(String s); """ if s == None: return 0 if start == None: return 1 return s[0:len(start)] == startdef indent (i): """ return as many ' ' as i """ s = '' for j in xrange(i): s = s + ' ' return sdef _hasToBeRemoved (req, prefix): toBeRemoved = req.getParameter(P_DELETE_PREFIX) #log.debug('toBeRemoved : %s' % toBeRemoved) #log.debug('prefix : %s' % prefix) return toBeRemoved and toBeRemoved == prefixdef _hasToMoveUp (req, prefix): return _hasToMove(req, prefix, P_MOVE_UP)def _hasToMoveDown (req, prefix): return _hasToMove(req, prefix, P_MOVE_DOWN)def _hasToMove (req, prefix, direction): toMove = req.getParameter(direction) return toMove and toMove == prefixdef _getFilter (wi): if not _hasMethod(wi, 'getFilter'): return None return wi.getFilter()def displayInputTag (viewOnly, req, writer, wi, fieldName): """ a 'public' method, directly called by the client webapplication """ prefix = OWFE + quote(fieldName) + DOUBLE_POINT #log.debug('fieldName is "%s"' % fieldName) value = _getAttribute(wi, fieldName) #log.debug('value is of class %s' % value.__class__) type = TYPE_MAP[value.__class__] input = INPUT_MAP[type] #if input == None: input = INPUT_MAP['_default'] input = input() prefix = prefix + ("0" + POINT + type) filter = _getFilter(wi) if filter != None: viewOnly = viewOnly or (not filter.allowWrite(fieldName)) input.displayInputTag(viewOnly, 0, writer, value, prefix)def _displayButton (writer, prefix, parameter, image, title=None): writer.write('<a href="" ') if title: writer.write('title="%s" ' % title) writer.write('onClick="submitForm(\'%s' % ACT_UPDATE) writer.write('?%s=%s\'); ' % (parameter, prefix)) writer.write('return false;">') writer.write(image) writer.write('</a>')def displayDeleteTag (writer, wi, fieldName): filter = _getFilter(wi) if filter != None: if not filter.allowRemove(fieldName): return _displayButton(writer, quote(fieldName), P_DELETE_FIELD, IMG_MINUS, 'Delete element')def _displayAddElement (indentation, writer, prefix): writer.write(indent(indentation+1)) _displayButton(writer, prefix, PREFIX_FOR_NEW_ELEMENT, IMG_PLUS, 'Add element')def _displayDeleteElement (writer, subPrefix): _displayButton(writer, subPrefix, P_DELETE_PREFIX, IMG_MINUS, 'Remove element')def _displayUpDownButtons (writer, subPrefix, index, listLength): if index > 0: _displayButton(writer, subPrefix, P_MOVE_UP, IMG_UP, 'Move element one step up') if index < listLength-1: _displayButton(writer, subPrefix, P_MOVE_DOWN, IMG_DOWN, 'Move element one step down')class Couple: def __init__ (self, sCouple): ss = sCouple.split(POINT) self.index = ss[0] self.type = ss[1] self.input = INPUT_MAP[self.type] self.input = self.input() def getIntIndex (self): return int(self.index) def __str__ (self): return self.index + POINT + self.typedef _hasMethod (instance, methodName): return hasattr(instance, methodName)def _getAttribute (wi, attName): if _hasMethod(wi, 'getAttribute'): return wi.getAttribute(attName) if isinstance(wi, MapAttribute): return wi.get(attName) raise TypeError, 'cannot handle class %s' % wi.__class__def _setAttribute (wi, attName, attValue): if _hasMethod(wi, 'getAttributes'): _setAttribute(wi.getAttributes(), attName, attValue) return if isinstance(wi, MapAttribute): wi.put(attName, attValue) return raise TypeError, 'cannot handle class %s' % wi.__class__def _removeAttribute (wi, attName): log.debug(' ~~~~~~~~~~~~~~~~~~~~~~~~~ _removeAttribute()') if _hasMethod(wi, 'removeAttribute'): #log.debug(' ~~ removing attribute "%s"' % attName) #log.debug(' ~~ contains att ? %s' % wi.containsAttribute(attName)) wi.removeAttribute(attName) return if isinstance(wi, MapAttribute): wi.remove(attName) return raise TypeError, 'cannot handle class %s' % wi.__class__def _getFieldName (paramName): ss = paramName.split(DOUBLE_POINT) return ss[1]def _getFirstCouple (paramName): ss = paramName.split(DOUBLE_POINT) return Couple(ss[2])def _getNextCouple (paramName, prefix): suffix = paramName[len(prefix):] if len(suffix) < 1: return None ss = suffix.split(DOUBLE_POINT) return Couple(ss[0])def parseRequest (wi, req): #req = _newOwfeRequest(req) req = OwfeRequest(req, UPLOAD_PATH) log.debug("parseRequest() switched to OwfeRequest") #for pn in req.getParameterNames(): # log.debug("\n === %s --> %s" % (pn, req.getParameter(pn))) # intercept 'delete field' requests deleteField = req.getParameter(P_DELETE_FIELD) if deleteField != None: deleteField = unquote(deleteField) _removeAttribute(wi, deleteField) #else: # log.debug("parseRequest() no %s" % P_DELETE_FIELD) # intercept 'new field' newFieldName = req.getParameter(P_NEW_FIELD_NAME) if newFieldName and newFieldName.strip() != '': _setAttribute(wi, newFieldName, NewFieldInput()) # # parse other params alreadyParsed = [] for paramName in req.getParameterNames(): #log.debug("parseRequest() paramName '%s'" % paramName) if not startsWith(paramName, OWFE): continue fieldName = _getFieldName(paramName) fieldName = unquote(fieldName) if fieldName == deleteField: continue if fieldName in alreadyParsed: continue couple = _getFirstCouple(paramName) input = INPUT_MAP[couple.type] input = input() prefix = OWFE + quote(fieldName) + DOUBLE_POINT + str(couple) value = input.parseRequest(req, prefix) _setAttribute(wi, fieldName, value) alreadyParsed.append(fieldName)## THE CLASSESclass Input: """ All input classes are children of this class """ def __init__ (self): self.params = None # METHODS def outputHtmlAttributes (self, writer): if self.params == None: return for attName in self.params.keys(): writer.write(' %s="%s"' % (attName, self.params[attName])) # 'ABSTRACT' METHODS def parseRequest (self, req, prefix): pass def displayInputTag (self, viewOnly, indentation, writer, attValue, prefix): pass def getEmptyValue (self): pass## NONE VALUEclass NoneValue (Attribute): pass# # NEW FIELD INPUT#lastGivenHashCode = 0;class NewFieldInput (Input, Attribute): """ a kind of place holder, awaits to be given an attribute type """ def __init__ (self): Input.__init__(self) global lastGivenHashCode lastGivenHashCode = lastGivenHashCode + 1 self.hashCode = lastGivenHashCode def parseRequest (self, req, prefix): type = req.getParameter(prefix) if type == NONE: return NoneValue() input = INPUT_MAP[type] input = input() return input.getEmptyValue() def displayInputTag (self, viewOnly, indentation, writer, value, prefix): #writer.write(indent(indentation+1)) writer.write(indent(indentation)) writer.write('<select name=%s>\n' % prefix) # 'none' option writer.write('<option>%s</option>\n' % NONE) # the options for type in TYPES: writer.write('<option>%s</option>\n' % type) writer.write('</select>') writer.write(' ') writer.write('<a href="" ') writer.write('onClick="submitForm(\'%s\'); ' % ACT_UPDATE) writer.write('return false;">') writer.write(IMG_OK) writer.write('</a>') def getEmptyValue (self): return None
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -