本文整理汇总了Python中java.lang.String类的典型用法代码示例。如果您正苦于以下问题:Python String类的具体用法?Python String怎么用?Python String使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了String类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: checkInbox
def checkInbox():
for message in voice.sms().messages:
if not message.isRead:
n=message.phoneNumber
msgtxt = str(message.messageText)
txtarray = msgtxt.split(" ")
print txtarray
if len(txtarray) > 2:
e = String(txtarray[0])
#print e
key = txtarray[1]
#print key
code = ' '.join([str(x) for x in txtarray[2:len(txtarray)]])
#print code
if e.equalsIgnoreCase("encode"):
coded = encrypt(code, key)
#print "Coded message"
if len(coded) < 140:
postToTwitter(coded)
returnText(n, "Posted to Twitter: "+coded)
else:
returnText(n, "Coded message too long")
elif e.equalsIgnoreCase("decode"):
uncoded = decrypt(code, key)
#print "Decoded message"
returnText(n, "Uncoded text: "+uncoded)
else:
returnText(n, "Unable to parse input text message")
message.delete()
time.sleep(10)
示例2: __activate__
def __activate__(self, context):
# Prepare variables
self.index = context["fields"]
self.object = context["object"]
self.payload = context["payload"]
self.params = context["params"]
self.utils = context["pyUtils"]
self.config = context["jsonConfig"]
self.wfSecurityExceptions = None
self.message_list = None
# Because the workflow messaging system wants access to this data
# BEFORE it actual hits the index we are going to cache it into an
# object payload too.
self.directIndex = JsonSimple()
# Common data
self.__newDoc()
#print "+++ direct-files.py - itemType='%s'" % self.itemType
# Real metadata
if self.itemType == "object":
self.__previews()
self.__basicData()
self.__metadata()
# Update the 'direct.index' payload - BEFORE messages are sent
directString = String(self.directIndex.toString())
inStream = ByteArrayInputStream(directString.getBytes("UTF-8"))
try:
StorageUtils.createOrUpdatePayload(self.object, "direct.index", inStream)
except StorageException, e:
print " * direct-files.py : Error updating direct payload"
self.__messages()
self.__displayType()
示例3: test_store_creation
def test_store_creation(self):
from com.hp.hpl.jena.tdb import TDBFactory
from java.io import ByteArrayInputStream
from java.lang import String
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'OAC-testing.tdb')
dataset = TDBFactory.createDataset(db_path)
# Make sure the store was created
assert os.path.isdir(db_path)
# Make InputStream triples
rdf_text = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="info:fedora/changeme:651"><rdf:type rdf:resource="oa:Annotation"></rdf:type><oa:hasBody xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:resource="info:fedora/changeme:650"></oa:hasBody><oa:modelVersion xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:resource="http://www.openannotation.org/spec/core/20120509.html"></oa:modelVersion><oa:generated xmlns:oa="http://www.w3.org/ns/openannotation/core/">2012-06-07T03:50:55.993000Z</oa:generated></rdf:Description><rdf:Description rdf:about="info:fedora/changeme:650"><rdf:type rdf:resource="oa:Body"></rdf:type><dc:format xmlns:dc="http://purl.org/dc/elements/1.1/">text/xml</dc:format></rdf:Description></rdf:RDF>'
rdfxml = String(rdf_text)
input_stream = ByteArrayInputStream(rdfxml.getBytes())
model = dataset.getDefaultModel()
model.begin()
model.read(input_stream, None)
model.commit()
model.close()
# Were all of the triples added?
assert model.size() == 6
shutil.rmtree(db_path)
# Was the store removed?
assert not os.path.isdir(db_path)
示例4: test_null_pointer_exception
def test_null_pointer_exception(self):
try:
# throws http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception
String.valueOf(None)
except Exception as ex:
# because it's not a checked exception, mapped exceptions doesn't apply here (all Runtime)
self.assertIn('java.lang.NullPointerException', str(ex.message))
示例5: getDistributors
def getDistributors(self,oshv,sqlServerId):
#is there is a chance that we have more than one distributor?
rs = self.connection.doCall(Queries.SERVER_DIST_CALL)
distributor = None
databaseName = None
while rs.next():
name = rs.getString('distributor')
if(name is None):
rs.close()
return None
databaseName = rs.getString('distribution database')
max = int(rs.getInt('max distrib retention'))
min = int(rs.getInt('min distrib retention'))
history = int(rs.getInt('history retention'))
cleanup = String(rs.getString('history cleanup agent'))
idx = cleanup.indexOf('Agent history clean up:')
if(idx>=0):
cleanup=cleanup.substring(len("Agent history clean up:"))
distributor = ObjectStateHolder('sqlserverdistributor')
sqlServer = self.createSqlServer(name,oshv,sqlServerId)
distributor.setContainer(sqlServer)
distributor.setAttribute(Queries.DATA_NAME,name)
distributor.setIntegerAttribute('maxTxRetention',max)
distributor.setIntegerAttribute('minTxRetention',min)
distributor.setIntegerAttribute('historyRetention',history)
distributor.setAttribute('cleanupAgentProfile',cleanup)
oshv.add(sqlServer)
oshv.add(distributor)
database = self.getDatabase(sqlServer,databaseName)
oshv.add(database)
oshv.add(modeling.createLinkOSH('use',distributor,database))
rs.close()
if(distributor!=None):
logger.debug('we got a distributor')
return [distributor,databaseName]
示例6: __saveManifest
def __saveManifest(self, oid):
object = self.services.getStorage().getObject(oid)
sourceId = object.getSourceId()
manifestStr = String(self.__manifest.toString())
object.updatePayload(sourceId,
ByteArrayInputStream(manifestStr.getBytes("UTF-8")))
object.close()
示例7: __formData
def __formData(self):
# Find our workflow form data
packagePid = None
try:
self.pidList = self.object.getPayloadIdList()
for pid in self.pidList:
if pid.endswith(self.packagePidSuffix):
packagePid = pid
except StorageException:
self.log.error("Error accessing object PID list for object '{}' ", self.oid)
return
if packagePid is None:
self.log.debug("Object '{}' has no form data", self.oid)
return
# Retrieve our form data
workflowData = None
try:
payload = self.object.getPayload(packagePid)
try:
workflowData = JsonSimple(payload.open())
except Exception:
self.log.error("Error parsing JSON '{}'", packagePid)
finally:
payload.close()
except StorageException:
self.log.error("Error accessing '{}'", packagePid)
return
# Test our version data
self.version = workflowData.getString("{NO VERSION}", ["redbox:formVersion"])
oldData = String(workflowData.toString(True))
if self.version != self.redboxVersion:
self.log.info("OID '{}' requires an upgrade: '{}' => '{}'", [self.oid, self.version, self.redboxVersion])
# The version data is old, run our upgrade
# function to see if any alterations are
# required. Most likely at least the
# version number will change.
newWorkflowData = self.__upgrade(workflowData)
else:
newWorkflowData = self.__hotfix(workflowData)
if newWorkflowData is not None:
self.log.debug("OID '{}' was hotfixed for v1.2 'dc:type' bug", self.oid)
else:
self.log.debug("OID '{}' requires no work, skipping", self.oid)
return
# Backup our data first
backedUp = self.__backup(oldData)
if not backedUp:
self.log.error("Upgrade aborted, data backup failed!")
return
# Save the newly modified data
jsonString = String(newWorkflowData.toString(True))
inStream = ByteArrayInputStream(jsonString.getBytes("UTF-8"))
try:
self.object.updatePayload(packagePid, inStream)
except StorageException, e:
self.log.error("Error updating workflow payload: ", e)
示例8: __init__
def __init__(self, Framework):
Netlinks_Service.NetlinksService.__init__(self, Framework)
shouldIgnoreLocal = self.getParameterValue('ignoreLocalConnections')
if shouldIgnoreLocal == None:
shouldIgnoreLocal = 'false'
self.ignoreLocalConnections = Boolean.parseBoolean(shouldIgnoreLocal)
self.dependencyNameIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_name')
self.dependencySourceIsKey = modeling.checkIsKeyAttribute('dependency', 'dependency_source')
ignoredIpsList = self.getParameterValue('ignoredIps')
self.ignoredIps = None
if ignoredIpsList != None:
ipPatterns = ignoredIpsList.split(',')
if (len(ipPatterns) > 0) and (ipPatterns[0] != ''):
for ipPattern in ipPatterns:
pattern = String(ipPattern)
pattern = String(pattern.replaceAll("\.", "\\\."))
pattern = String(pattern.replaceAll("\*", "\\\d+"))
try:
m = Pattern.compile(pattern)
if self.ignoredIps == None:
self.ignoredIps = ArrayList()
self.ignoredIps.add(m)
except:
logger.debug('Failed to compile ip pattern:', ipPattern)
self.initializeServices()
示例9: __call__
def __call__(self):
"""
A Python object is callable if it defines a __call__ method. Each worker thread performs a
number of runs of the test script, as configured by the property grinder.runs. For each run,
the worker thread calls its TestRunner; thus the __call__ method can be thought of as the
definition of a run.
"""
# Normally test results are reported automatically when the test returns. If you want to
# alter the statistics after a test has completed, you must set delayReports = 1 to delay
# the reporting before performing the test. This only affects the current worker thread.
grinder.statistics.delayReports = 1
msg = te_message.Message(
"1.0", "20111020153610", 200, None, "GPE-111", 111, "OPERATOR-111", "00000000001", None, request_msgbody
)
# print("******hello" + str(type(msg)))
# print("msg.raw_body" + msg.raw_body)
# print("des:" + msg.encrypted_body)
body = String(msg.encrypted_body)
response = request.POST(CONF_url, body.getBytes(), msg.assemble_nvpairs())
code = int(response.getHeader("X-Response-Code"))
# verify response status
if 200 != code:
print("------------------------------------ERROR: %d" % code)
# Set success = 0 to mark the test as a failure.
grinder.statistics.forLastTest.setSuccess(0)
else:
print("------------------------------------PASS!")
示例10: getTFPackagePid
def getTFPackagePid(self,oid):
digitalObject = StorageUtils.getDigitalObject(self.storage,oid)
for pid in digitalObject.getPayloadIdList():
pidString = String(pid)
if pidString.endsWith("tfpackage"):
return pid
return None
示例11: read_methods
def read_methods(file):
names = {}
for line in file:
nline = line.strip()
jstr = String(nline)
hcode = jstr.hashCode()
names[hcode] = nline
return names
示例12: test_null_pointer_exception
def test_null_pointer_exception(self):
try:
# throws http://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception
String.valueOf(None)
except Exception as ex:
# because it's not a checked exception, mapped exceptions doesn't apply here (all Runtime)
if not jep.USE_MAPPED_EXCEPTIONS:
self.assertEquals(ex.java_name, 'java.lang.NullPointerException')
示例13: sortResultsByCode
def sortResultsByCode(self):
tempMap = HashMap()
for result in self.__results:
uri = String(self.getValue(result, "dc_identifier"))
lastIndex = uri.lastIndexOf('/') + 1
code = uri.substring(lastIndex)
tempMap.put(code, result)
self.resultsByCode = TreeMap(tempMap)
示例14: _getXmlRootFromString
def _getXmlRootFromString(self, xmlString):
"""
Parses string xml representation and returns root element
str->Element
@raise JavaException: XML parsing failed
"""
xmlString = ''.join([line.strip() for line in xmlString.split('\n') if line])
strContent = String(xmlString)
return SAXBuilder().build(ByteArrayInputStream(strContent.getBytes('utf-8'))).getRootElement()
示例15: __saveWorkflowMetadata
def __saveWorkflowMetadata(self, oid):
object = self.services.getStorage().getObject(oid)
manifestStr = String(self.__workflowMetadata.toString())
object.updatePayload("workflow.metadata",
ByteArrayInputStream(manifestStr.getBytes("UTF-8")))
object.close()
self.__indexer.index(oid)
self.__indexer.commit()