Example #1
0
def handleBankTip(owner, window, eventType, returnList):
    core = NGECore.getInstance()
    chatSvc = core.chatService
    actorGlobal = core.objectService.getObject(actorID)
    targetGlobal = core.objectService.getObject(targetID)
    actorFunds = actorGlobal.getBankCredits()
    totalLost = int(tipAmountBank) + bankSurcharge
    
    if eventType == 0:
        if int(totalLost) > actorFunds:
            actorGlobal.sendSystemMessage('You do not have ' + str(totalLost) + ' credits (surcharge included) to tip the desired amount to ' + targetGlobal.getCustomName() + '.', 0)
            return
        if int(tipAmount) > 0 and int(actorFunds) >= int(totalLost):
            date = Date()
            targetName = targetGlobal.getCustomName()

            targetMail = Mail()
            targetMail.setMailId(chatSvc.generateMailId())
            targetMail.setTimeStamp((int) (date.getTime() / 1000))
            targetMail.setRecieverId(targetID)
            targetMail.setStatus(Mail.NEW)
            targetMail.setMessage(tipAmount + ' credits from ' + actorGlobal.getCustomName() + ' have been successfully delivered from escrow to your bank account')
            targetMail.setSubject('@base_player:wire_mail_subject')
            targetMail.setSenderName('bank')

            actorMail = Mail()
            actorMail.setMailId(chatSvc.generateMailId())
            actorMail.setRecieverId(actorID)
            actorMail.setStatus(Mail.NEW)
            actorMail.setTimeStamp((int) (date.getTime() / 1000))
            actorMail.setMessage('An amount of ' + tipAmount + ' credits have been transfered from your bank to escrow. It will be delivered to ' + 
                             targetGlobal.getCustomName() + ' as soon as possible.')
            actorMail.setSubject('@base_player:wire_mail_subject')
            actorMail.setSenderName('bank')
            
            targetGlobal.setBankCredits(int(tipAmount) + int(targetGlobal.getBankCredits()))
            actorGlobal.setBankCredits(int(actorFunds) - int(totalLost))
            actorGlobal.sendSystemMessage('You have successfully sent ' + tipAmount + ' bank credits to ' + targetGlobal.getCustomName(), 0)
            targetGlobal.sendSystemMessage('You have successfully received ' + tipAmount + ' bank credits from ' + actorGlobal.getCustomName(), 0)
            
            chatSvc.storePersistentMessage(actorMail)
            chatSvc.storePersistentMessage(targetMail)
            chatSvc.sendPersistentMessageHeader(actorGlobal.getClient(), actorMail)
            chatSvc.sendPersistentMessageHeader(targetGlobal.getClient(), targetMail)
            return
        
    else:
        actorGlobal.sendSystemMessage('You lack the bank funds to wire ' + tipAmount + ' bank funds to ' + targetGlobal.getCustomName() + '.', 0)
        return
    return
Example #2
0
 def handleBankTip(core, owner, eventType, returnList):
     bankSurcharge = int(math.ceil(0.05 * float(transferTotal))) 
     core = NGECore.getInstance()
     chatSvc = core.chatService
     actorGlobal = tipFrom
     targetGlobal = tipTo
     actorFunds = actorGlobal.getBankCredits()
     totalLost = int(transferTotal) + bankSurcharge
     
     if eventType == 0:
         if int(totalLost) > actorFunds:
             actorGlobal.sendSystemMessage('You do not have ' + str(totalLost) + ' credits (surcharge included) to tip the desired amount to ' + targetGlobal.getCustomName() + '.', 0)
             return
         if int(transferTotal) > 0 and int(actorFunds) >= int(totalLost):
             date = Date()
             targetName = targetGlobal.getCustomName()
  
             targetMail = Mail()
             targetMail.setMailId(chatSvc.generateMailId())
             targetMail.setTimeStamp((int) (date.getTime() / 1000))
             targetMail.setRecieverId(targetGlobal.getObjectId())
             targetMail.setStatus(Mail.NEW)
             targetMail.setMessage(`transferTotal` + ' credits from ' + actorGlobal.getCustomName() + ' have been successfully delivered from escrow to your bank account')
             targetMail.setSubject('@base_player:wire_mail_subject')
             targetMail.setSenderName('bank')
  
             actorMail = Mail()
             actorMail.setMailId(chatSvc.generateMailId())
             actorMail.setRecieverId(actorGlobal.getObjectId())
             actorMail.setStatus(Mail.NEW)
             actorMail.setTimeStamp((int) (date.getTime() / 1000))
             actorMail.setMessage('An amount of ' + `transferTotal` + ' credits have been transfered from your bank to escrow. It will be delivered to ' + targetGlobal.getCustomName() + ' as soon as possible.')
             actorMail.setSubject('@base_player:wire_mail_subject')
             actorMail.setSenderName('bank')
              
             targetGlobal.addBankCredits(int(transferTotal))
             actorGlobal.deductBankCredits(int(totalLost))
             actorGlobal.sendSystemMessage('You have successfully sent ' + `transferTotal` + ' bank credits to ' + targetGlobal.getCustomName(), 0)
             targetGlobal.sendSystemMessage('You have successfully received ' + `transferTotal` + ' bank credits from ' + actorGlobal.getCustomName(), 0)
              
             chatSvc.storePersistentMessage(actorMail)
             chatSvc.storePersistentMessage(targetMail)
             chatSvc.sendPersistentMessageHeader(actorGlobal.getClient(), actorMail)
             chatSvc.sendPersistentMessageHeader(targetGlobal.getClient(), targetMail)
             return             
     else:
         actorGlobal.sendSystemMessage('You lack the bank funds to wire ' + `transferTotal` + ' bank funds to ' + targetGlobal.getCustomName() + '.', 0)
         return        
     return
Example #3
0
def runTests():
    print "Configuring tests"
#   propsFile = File("ALSBTest.properties")
#   props=getProps(propsFile)
#    print "Running tests agains this URL: " , props.get("alsb.url")
    testsCreated=0
    testSuite = TestSuite()
    aggregator= PerfTestResultsAggregator("c:/temp/ALSBTestErrors/perf.csv");
    aggregator.initialize()
    for test in tests :
        validatorList = ArrayList()
        for v in test[3]:
            validatorList.add(validators[v])
        testsCreated = testsCreated +1
        testCase = ALSBTestCase(test[0],test[1], test[2], validatorList,testsCreated);
        testCase.setAggregator(aggregator)
        testSuite.addTest(testCase)
        
    
    print testsCreated, ' tests were configured to run'
    
    testResult = TestResult()
    print 'running test suite'
    print 'test cases: ',  testSuite.countTestCases()
    startTime = Date();
    testSuite.run(testResult)
    aggregator.dispose()
    endTime = Date();
    seconds = (endTime.getTime()/1000) - (startTime.getTime() / 1000);
    averageInvTime = seconds / testSuite.countTestCases();
    minutes = seconds / 60
    seconds = seconds % 60
    
    print 'test suite run in ', minutes,':',seconds, '(',averageInvTime,' secs / test)'
    if testResult.wasSuccessful() :
        print '#########################        OKAY! :-)        ############################\n'
        print testResult.runCount(), 'tests were run'
        
    else:
        print '#########################        FAIL! :-(        ############################\n'
        print 'failures (',testResult.failureCount(),')'
        print '___________________________________________\n'
        for failure in testResult.failures():
            print failure
        print '\nerrors (',testResult.errorCount(),')'
        print '___________________________________________\n'
        for error in testResult.errors():
            print error
Example #4
0
def processCertInfo():
    certInfo = {}
    dtFormat = SimpleDateFormat("E MMM dd HH:mm:ss yyyy")
    logFile = open("logs/cert.log", "w")
    for line in open('logs/expiringCerts.txt'):
        if 'App Stripe' in line:
            certInfo['appStripe'] = line.split('=')[1].strip()
        if 'Keystore' in line:
            certInfo['keystore'] = line.split('=')[1].strip()
        if 'Alias' in line:
            certInfo['alias'] = line.split('=')[1].strip()
        if 'Certificate status' in line:
            certInfo['status'] = line.split('=')[1].strip()
        if 'Expiration Date' in line:  #Expiration Date record marks the end of certificate info. Below block processes currrent cert.
            certInfo['expiryDt'] = line.split('=')[1].strip()
            expiryDtFmtd = str(certInfo['expiryDt']).replace(
                "UTC ",
                "")  # Removes UTC from date string to build date object.
            expiryDtObj = dtFormat.parse(expiryDtFmtd)
            currDtObj = Date()  #Get current date.
            timeDiff = expiryDtObj.getTime() - currDtObj.getTime()
            daysBetween = (timeDiff / (1000 * 60 * 60 * 24))
            if daysBetween >= 0 and daysBetween <= int(
                    alertDays
            ) and certInfo['keystore'] in keystoresList and certInfo[
                    'alias'] not in certAliasExcptList:  #Only concerned about keystores mentioned in the properties file.
                logFile.write("Certificate in app stripe \"" +
                              certInfo['appStripe'] + "\" and keystore \"" +
                              certInfo['keystore'] + "\" with alias name \"" +
                              certInfo['alias'] + "\" is expiring on " +
                              certInfo['expiryDt'] + "\n")
                logFile.write("\n")

            certInfo = {}
    logFile.close()
Example #5
0
    def test(self):
        expectedHwm = Date()

        #inject syncfile info for user
        um = self.mc.getUserManager()
        user = um.getUser('*****@*****.**')
        uid = user.getUserID()
        syncfile = SyncFile()
        syncfile.setCustomerId(user.getCustomerID())
        syncfile.setUserId(uid)
        syncfile.setFileName("dummy.xml")
        syncfile.setFileSize(200)
        syncfile.setFhsSuccesses(1)
        syncfile.setFinishedDate(expectedHwm)
        syncfile.setFisSuccesses(1)
        syncfile.setProcessingTime(1)
        syncfile.setReceivedDate(expectedHwm)
        syncfile.setRootFolderId("rootfolderid")
        syncfile.setSequenceId(1)
        syncfile.setState(SyncFileState.Finished)
        sfToken = self.fsm.createSyncFileToken(syncfile)
        syncfile.setToken(sfToken)
        self.fsm.saveSyncFile(syncfile)

        #query service and see if the value matches

        status, outHeaders, outContent = hwmCall(self.url, self.authToken)
        assertEqual('wrong rc', "0", outHeaders["x-m1-ems-error-code"])
        assertEqual('wrong msg', "Success", outHeaders["x-m1-ems-error-message"])
        assertEqual('wrong msg', str(expectedHwm.getTime()), outContent)
Example #6
0
 def __init__(self):
     """@RETURN: """
     dt = Date()
     self.m_temp_file = File.createTempFile(str(dt.getTime()), ".ood")
     self.m_temp_file.deleteOnExit()
     self.m_temp_file_writer = FileWriter(self.m_temp_file)
     self.m_line_count = 1
Example #7
0
 def __init__(self):
     '''@RETURN: '''
     dt = Date()
     self.m_temp_file = File.createTempFile(str(dt.getTime()), '.ood')
     self.m_temp_file.deleteOnExit()
     self.m_temp_file_writer = FileWriter(self.m_temp_file)
     self.m_line_count = 1
 def expiration_in_days(self):
     """
     Return the number of days until the certificate expires.
     If the certificate is already expired a negative number is returned.
     """
     now = Date()
     diff = self.__not_after.getTime() - now.getTime()
     return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)
Example #9
0
def minDiff(date):
    now = Date()

    cal = Calendar.getInstance()
    now = cal.getTime()

    dbDataTime = date.getTime()  #in ms
    nowTime = now.getTime()  #in ms
    diff = nowTime - dbDataTime
    min = ((diff / (1000 * 60)) % 60)
    hr = ((diff / (1000 * 60 * 60)) % 24)
    days = (diff / (1000 * 60 * 60 * 24))

    tot_min = (days * 24) * 60 + hr * 60 + min

    return min
def minDiff(date):
	now = Date()
		
	cal = Calendar.getInstance()
	now = cal.getTime()
	
	dbDataTime = date.getTime() 	#in ms
	nowTime = now.getTime()			#in ms
	diff = nowTime - dbDataTime
	min = ((diff / (1000 * 60)) % 60)
	hr = ((diff / (1000 * 60 * 60)) % 24)
	days = (diff / (1000 * 60 * 60 * 24))
	
	tot_min = (days * 24) * 60 + hr * 60 + min
	
	return min
Example #11
0
class Job:
	def __init__( self, desc, tz = TimeZone.getDefault() ):
		self.id = desc.getString( "id" )
		self.tz = tz
		self.last = None
		self.next = None
		self.scheds = []
		a = desc.getJSONArray( "scheds" )
		for i in range( a.length() ):
			self.scheds.append( Sched( a.getJSONObject( i ) ) )
		self.cmd = desc.getString( "cmd" )

	def dump( self, prefix = "", headprefix = "" ):
		print headprefix + "id:   \t" + self.id
		print headprefix + "tz:   \t" + self.tz.getID()
		if self.last != None:
			print headprefix + "last: \t" + self.last.toString()
		if self.next != None:
			print headprefix + "next: \t" + self.next.toString()
		for i in self.scheds:
			print headprefix + "sched:\t+"
			i.dump( prefix + "      \t|- " )
		print headprefix + "cmd:  \t" + self.cmd

	def setState( self, data ):
		self.last = None
		self.next = None
		if data.has( "last" ):
			self.last = Date( data.getInt( "last" ) * 1000 )
		if data.has( "next" ):
			self.next = Date( data.getInt( "next" ) * 1000 )

	def getState( self ):
		res = JSONObject()
		if self.last != None:
			res.put( "last", self.last.getTime() / 1000 )
		if self.next != None:
			res.put( "next", self.next.getTime() / 1000 )
		return res

	def pending( self ):
		if self.next == None:
			return False
		else:
			return not Date().before( self.next )

	def start( self ):
		self.next = Date()

	def stop( self ):
		self.next = None

	def resume( self ):
		if self.last == None:
			return
		next = None
		for i in self.scheds:
			tmp = i.next( self.last, self.tz )
			if tmp != None:
				if next == None:
					next = tmp
				elif tmp.before( next ):
					next = tmp
		self.next = next

	def done( self ):
		self.last = Date()
		self.resume()
Example #12
0
json = importlib.import_module(sys.argv[1])

try:
    from java.util import Date
    start = Date()
    jython = True
except ImportError:
    from datetime import datetime
    start = datetime.now()
    jython = False

f = sys.stdin

bytes_read = 0

while True:
    oline = f.readline()
    l = len(oline)
    if l == 0:
        break
    bytes_read += l
    json.loads(oline)

if jython:
    ms = (Date().getTime() - start.getTime())
else:
    delta = (datetime.now() - start)
    ms = delta.seconds * 1000 + delta.microseconds/1000

print str(1000*bytes_read/1024/1024/ms) + " MB/s %dbytes in %sseconds" % (bytes_read, ms/1000)
Example #13
0
 reportsched.setValue("LANGCODE", userinfo.getLangCode())
 print "About to work with REPORTSCHEDULE cron task"
 crontaskdef = reportsched.getMboSet(
     "$parent", "crontaskdef",
     "crontaskname='REPORTSCHEDULE'").getMbo(0)
 if crontaskdef is not None:
     crontaskinstset = crontaskdef.getMboSet(
         "CRONTASKINSTANCE")
     if crontaskinstset is not None:
         print "About to work with Cron task instance of REPORTSCHEDULE cron task"
         crontaskinst = crontaskinstset.add(
             MboConstants.NOACCESSCHECK
             | MboConstants.NOVALIDATION_AND_NOACTION)
         if crontaskinst is not None:
             d = Date()
             crontaskinstname = str(d.getTime())
             crontaskinst.setValue(
                 "CRONTASKNAME", "REPORTSCHEDULE",
                 MboConstants.NOACCESSCHECK
                 | MboConstants.NOVALIDATION_AND_NOACTION)
             crontaskinst.setValue(
                 "INSTANCENAME", crontaskinstname,
                 MboConstants.NOACCESSCHECK
                 | MboConstants.NOVALIDATION_AND_NOACTION)
             crontaskinst.setValue(
                 "SCHEDULE", schedule,
                 MboConstants.NOACCESSCHECK
                 | MboConstants.NOVALIDATION_AND_NOACTION)
             crontaskinst.setValue(
                 "ACTIVE", 1, MboConstants.NOACCESSCHECK
                 | MboConstants.NOVALIDATION_AND_NOACTION)
Example #14
0
def collectJDBCSQL():
	global wlsInstance
	global wlsVersion
	global rptStart
	global rptEnd
	try:
		wlsVersion = version
		info('Weblogic Version:', wlsVersion)

		info('Note:', 'You must run this script on the Weblogic Managed Server which you connect.')
		info('', '')

		connect()
		edit()
		startEdit()
		serverNames=cmo.getServers()
		allServers = []
		for name in serverNames:
			curServerName = name.getName()
			allServers.append(curServerName)
		#allServers.append('agile-server2')
		#allServers.append('agile-server3')
		#allServers.append('agile-server4')
		info('Find following Weblogic instance(s):', len(allServers))
		info('', '')
		for i in range(len(allServers)):
			srv = allServers[i]
			info('    ' + str(i) + ':', srv)
		info('', '')	
		info('Type the number to select the correct Weblogic instance to connect, or type x to exit.', '')
		user_sel = ''
		while user_sel == '':
			user_sel = raw_input(__prompt_cur + ' Your choice: ')
		if user_sel.lower()=='x':
			save()
			activate()
			disconnect()
			info('User quits.', 'Bye')
			exit()
		
		wlsInstance = allServers[int(user_sel)]
		cd('/Servers/'+ wlsInstance + '/Log/' + wlsInstance)
		#ls()
		sqlLogFile = get('FileName')	
		info('Get log file:', sqlLogFile)
		sqlLogOrigSize = get('FileMinSize')
		info('Get log size:', str(sqlLogOrigSize))
		logDTFormatStr = get('DateFormatPattern')
		info('Get log date format:', str(logDTFormatStr))
		
		set('FileMinSize', __fileSize)
		info('Set log size:', str(__fileSize))
		set('DateFormatPattern', __dt_format)
		info('Set log date format:', __dt_format)
		cd('/Servers/' + wlsInstance + '/ServerDebug/' + wlsInstance)
		set('DebugJDBCSQL','true')
		info('Set DebugJDBCSQL:', 'true')
		save()
		activate()

		sqlLogFilePath = os.getcwd() + '/../servers/' + wlsInstance + '/' + sqlLogFile
		
		rptStart = dfLogTimestamp.format(Date())
		info('It is collecting SQL data. Press Enter after collected.', '')
		raw_input(__prompt_cur + ' ')
		dtRpt = Date()
		rptEnd = dfLogTimestamp.format(dtRpt)
		
		##
		info(__script_name + ' is waiting for Weblogic to flush log, please hold on...', '')
		#pytime.sleep(__sleep)
		jfile = File(sqlLogFilePath)
		
		showProgress(__prompt_cur + ' ')
		while True:
			jfmodifiedUnix = jfile.lastModified()
			rpt_endtime_unix = dtRpt.getTime()
			dtCurrent = Date()
			if (flushed(rpt_endtime_unix, jfmodifiedUnix)):
				break
			showProgress('.')
			Thread.sleep(__sleep * 1000)
			
		showProgress('\n')
		sqlLogFilePathCopy = sqlLogFilePath + '.' + __script_name
		shutil.copyfile(sqlLogFilePath, sqlLogFilePathCopy) # copy jdbc log file
		info('Copy ' + sqlLogFile + ' to', sqlLogFilePathCopy)
		
		##
		## revert back to original setting
		edit()
		startEdit()
		info('Get server:', wlsInstance)
		cd('/Servers/'+ wlsInstance + '/Log/' + wlsInstance)
		set('FileMinSize', sqlLogOrigSize)
		info('Reset log size:', str(sqlLogOrigSize))
		set('DateFormatPattern', logDTFormatStr)
		info('Reset log date format:', str(logDTFormatStr))
		cd('/Servers/' + wlsInstance + '/ServerDebug/' + wlsInstance)
		set('DebugJDBCSQL','false')
		info('Reset DebugJDBCSQL:', 'false')
		save()
		activate()
		disconnect()
		return sqlLogFilePathCopy
		#rpt_endtime = pytime.strftime(__dt_format, pytime.localtime()) 
	except Exception:
		save()
		activate()
		disconnect()
		raise
Example #15
0
File: Match.py Project: hobson/ggpy
class Match(object):
    """ generated source for class Match """
    matchId = str()
    randomToken = str()
    spectatorAuthToken = str()
    playClock = int()
    startClock = int()
    previewClock = int()
    startTime = Date()
    theGame = Game()
    moveHistory = List()
    stateHistory = List()
    errorHistory = List()
    stateTimeHistory = List()
    isCompleted = bool()
    isAborted = bool()
    goalValues = List()
    numRoles = int()
    theCryptographicKeys = EncodedKeyPair()
    thePlayerNamesFromHost = List()
    isPlayerHuman = List()
    theGdlScrambler = NoOpGdlScrambler()

    @overloaded
    def __init__(self, matchId, previewClock, startClock, playClock, theGame):
        """ generated source for method __init__ """
        self.matchId = matchId
        self.previewClock = previewClock
        self.startClock = startClock
        self.playClock = playClock
        self.theGame = theGame
        self.startTime = Date()
        self.randomToken = getRandomString(32)
        self.spectatorAuthToken = getRandomString(12)
        self.isCompleted = False
        self.isAborted = False
        self.numRoles = Role.computeRoles(theGame.getRules()).size()
        self.moveHistory = ArrayList()
        self.stateHistory = ArrayList()
        self.stateTimeHistory = ArrayList()
        self.errorHistory = ArrayList()
        self.goalValues = ArrayList()

    @__init__.register(object, str, Game, str)
    def __init___0(self, theJSON, theGame, authToken):
        """ generated source for method __init___0 """
        theMatchObject = JSONObject(theJSON)
        self.matchId = theMatchObject.getString("matchId")
        self.startClock = theMatchObject.getInt("startClock")
        self.playClock = theMatchObject.getInt("playClock")
        if theGame == None:
            self.theGame = RemoteGameRepository.loadSingleGame(theMatchObject.getString("gameMetaURL"))
            if self.theGame == None:
                raise RuntimeException("Could not find metadata for game referenced in Match object: " + theMatchObject.getString("gameMetaURL"))
        else:
            self.theGame = theGame
        if theMatchObject.has("previewClock"):
            self.previewClock = theMatchObject.getInt("previewClock")
        else:
            self.previewClock = -1
        self.startTime = Date(theMatchObject.getLong("startTime"))
        self.randomToken = theMatchObject.getString("randomToken")
        self.spectatorAuthToken = authToken
        self.isCompleted = theMatchObject.getBoolean("isCompleted")
        if theMatchObject.has("isAborted"):
            self.isAborted = theMatchObject.getBoolean("isAborted")
        else:
            self.isAborted = False
        self.numRoles = Role.computeRoles(self.theGame.getRules()).size()
        self.moveHistory = ArrayList()
        self.stateHistory = ArrayList()
        self.stateTimeHistory = ArrayList()
        self.errorHistory = ArrayList()
        theMoves = theMatchObject.getJSONArray("moves")
        i = 0
        while i < len(theMoves):
            while j < len(moveElements):
                theMove.add(GdlFactory.createTerm(moveElements.getString(j)))
                j += 1
            self.moveHistory.add(theMove)
            i += 1
        theStates = theMatchObject.getJSONArray("states")
        i = 0
        while i < len(theStates):
            while j < len(stateElements):
                theState.add(GdlFactory.create("( true " + stateElements.get(j).__str__() + " )"))
                j += 1
            self.stateHistory.add(theState)
            i += 1
        theStateTimes = theMatchObject.getJSONArray("stateTimes")
        i = 0
        while i < len(theStateTimes):
            self.stateTimeHistory.add(Date(theStateTimes.getLong(i)))
            i += 1
        if theMatchObject.has("errors"):
            while i < len(theErrors):
                while j < len(errorElements):
                    theMoveErrors.add(errorElements.getString(j))
                    j += 1
                self.errorHistory.add(theMoveErrors)
                i += 1
        self.goalValues = ArrayList()
        try:
            while i < len(theGoalValues):
                self.goalValues.add(theGoalValues.getInt(i))
                i += 1
        except JSONException as e:
            pass
        #  TODO: Add a way to recover cryptographic public keys and signatures.
        #  Or, perhaps loading a match into memory for editing should strip those?
        if theMatchObject.has("playerNamesFromHost"):
            self.thePlayerNamesFromHost = ArrayList()
            while i < len(thePlayerNames):
                self.thePlayerNamesFromHost.add(thePlayerNames.getString(i))
                i += 1
        if theMatchObject.has("isPlayerHuman"):
            self.isPlayerHuman = ArrayList()
            while i < len(isPlayerHumanArray):
                self.isPlayerHuman.add(isPlayerHumanArray.getBoolean(i))
                i += 1

    #  Mutators 
    def setCryptographicKeys(self, k):
        """ generated source for method setCryptographicKeys """
        self.theCryptographicKeys = k

    def enableScrambling(self):
        """ generated source for method enableScrambling """
        self.theGdlScrambler = MappingGdlScrambler(Random(self.startTime.getTime()))
        for rule in theGame.getRules():
            self.theGdlScrambler.scramble(rule)

    def setPlayerNamesFromHost(self, thePlayerNames):
        """ generated source for method setPlayerNamesFromHost """
        self.thePlayerNamesFromHost = thePlayerNames

    def getPlayerNamesFromHost(self):
        """ generated source for method getPlayerNamesFromHost """
        return self.thePlayerNamesFromHost

    def setWhichPlayersAreHuman(self, isPlayerHuman):
        """ generated source for method setWhichPlayersAreHuman """
        self.isPlayerHuman = isPlayerHuman

    def appendMoves(self, moves):
        """ generated source for method appendMoves """
        self.moveHistory.add(moves)

    def appendMoves2(self, moves):
        """ generated source for method appendMoves2 """
        #  NOTE: This is appendMoves2 because it Java can't handle two
        #  appendMove methods that both take List objects with different
        #  templatized parameters.
        theMoves = ArrayList()
        for m in moves:
            theMoves.add(m.getContents())
        self.appendMoves(theMoves)

    def appendState(self, state):
        """ generated source for method appendState """
        self.stateHistory.add(state)
        self.stateTimeHistory.add(Date())

    def appendErrors(self, errors):
        """ generated source for method appendErrors """
        self.errorHistory.add(errors)

    def appendNoErrors(self):
        """ generated source for method appendNoErrors """
        theNoErrors = ArrayList()
        i = 0
        while i < self.numRoles:
            theNoErrors.add("")
            i += 1
        self.errorHistory.add(theNoErrors)

    def markCompleted(self, theGoalValues):
        """ generated source for method markCompleted """
        self.isCompleted = True
        if theGoalValues != None:
            self.goalValues.addAll(theGoalValues)

    def markAborted(self):
        """ generated source for method markAborted """
        self.isAborted = True

    #  Complex accessors 
    def toJSON(self):
        """ generated source for method toJSON """
        theJSON = JSONObject()
        try:
            theJSON.put("matchId", self.matchId)
            theJSON.put("randomToken", self.randomToken)
            theJSON.put("startTime", self.startTime.getTime())
            theJSON.put("gameMetaURL", getGameRepositoryURL())
            theJSON.put("isCompleted", self.isCompleted)
            theJSON.put("isAborted", self.isAborted)
            theJSON.put("states", JSONArray(renderArrayAsJSON(renderStateHistory(self.stateHistory), True)))
            theJSON.put("moves", JSONArray(renderArrayAsJSON(renderMoveHistory(self.moveHistory), False)))
            theJSON.put("stateTimes", JSONArray(renderArrayAsJSON(self.stateTimeHistory, False)))
            if len(self.errorHistory) > 0:
                theJSON.put("errors", JSONArray(renderArrayAsJSON(renderErrorHistory(self.errorHistory), False)))
            if len(self.goalValues) > 0:
                theJSON.put("goalValues", self.goalValues)
            theJSON.put("previewClock", self.previewClock)
            theJSON.put("startClock", self.startClock)
            theJSON.put("playClock", self.playClock)
            if self.thePlayerNamesFromHost != None:
                theJSON.put("playerNamesFromHost", self.thePlayerNamesFromHost)
            if self.isPlayerHuman != None:
                theJSON.put("isPlayerHuman", self.isPlayerHuman)
            theJSON.put("scrambled", self.theGdlScrambler.scrambles() if self.theGdlScrambler != None else False)
        except JSONException as e:
            return None
        if self.theCryptographicKeys != None:
            try:
                SignableJSON.signJSON(theJSON, self.theCryptographicKeys.thePublicKey, self.theCryptographicKeys.thePrivateKey)
                if not SignableJSON.isSignedJSON(theJSON):
                    raise Exception("Could not recognize signed match: " + theJSON)
                if not SignableJSON.verifySignedJSON(theJSON):
                    raise Exception("Could not verify signed match: " + theJSON)
            except Exception as e:
                System.err.println(e)
                theJSON.remove("matchHostPK")
                theJSON.remove("matchHostSignature")
        return theJSON.__str__()

    def toXML(self):
        """ generated source for method toXML """
        try:
            theXML.append("<match>")
            for key in JSONObject.getNames(theJSON):
                if isinstance(value, (JSONObject, )):
                    raise RuntimeException("Unexpected embedded JSONObject in match JSON with tag " + key + "; could not convert to XML.")
                elif not (isinstance(value, (JSONArray, ))):
                    theXML.append(renderLeafXML(key, theJSON.get(key)))
                elif key == "states":
                    theXML.append(renderStateHistoryXML(self.stateHistory))
                elif key == "moves":
                    theXML.append(renderMoveHistoryXML(self.moveHistory))
                elif key == "errors":
                    theXML.append(renderErrorHistoryXML(self.errorHistory))
                else:
                    theXML.append(renderArrayXML(key, value))
            theXML.append("</match>")
            return theXML.__str__()
        except JSONException as je:
            return None

    def getMostRecentMoves(self):
        """ generated source for method getMostRecentMoves """
        if len(self.moveHistory) == 0:
            return None
        return self.moveHistory.get(len(self.moveHistory) - 1)

    def getMostRecentState(self):
        """ generated source for method getMostRecentState """
        if len(self.stateHistory) == 0:
            return None
        return self.stateHistory.get(len(self.stateHistory) - 1)

    def getGameRepositoryURL(self):
        """ generated source for method getGameRepositoryURL """
        return getGame().getRepositoryURL()

    def __str__(self):
        """ generated source for method toString """
        return self.toJSON()

    #  Simple accessors 
    def getMatchId(self):
        """ generated source for method getMatchId """
        return self.matchId

    def getRandomToken(self):
        """ generated source for method getRandomToken """
        return self.randomToken

    def getSpectatorAuthToken(self):
        """ generated source for method getSpectatorAuthToken """
        return self.spectatorAuthToken

    def getGame(self):
        """ generated source for method getGame """
        return self.theGame

    def getMoveHistory(self):
        """ generated source for method getMoveHistory """
        return self.moveHistory

    def getStateHistory(self):
        """ generated source for method getStateHistory """
        return self.stateHistory

    def getStateTimeHistory(self):
        """ generated source for method getStateTimeHistory """
        return self.stateTimeHistory

    def getErrorHistory(self):
        """ generated source for method getErrorHistory """
        return self.errorHistory

    def getPreviewClock(self):
        """ generated source for method getPreviewClock """
        return self.previewClock

    def getPlayClock(self):
        """ generated source for method getPlayClock """
        return self.playClock

    def getStartClock(self):
        """ generated source for method getStartClock """
        return self.startClock

    def getStartTime(self):
        """ generated source for method getStartTime """
        return self.startTime

    def isCompleted(self):
        """ generated source for method isCompleted """
        return self.isCompleted

    def isAborted(self):
        """ generated source for method isAborted """
        return self.isAborted

    def getGoalValues(self):
        """ generated source for method getGoalValues """
        return self.goalValues

    def getGdlScrambler(self):
        """ generated source for method getGdlScrambler """
        return self.theGdlScrambler

    #  Static methods 
    @classmethod
    def getRandomString(cls, nLength):
        """ generated source for method getRandomString """
        theGenerator = Random()
        theString = ""
        i = 0
        while i < nLength:
            if nVal < 26:
                theString += str(('a' + nVal))
            elif nVal < 52:
                theString += str(('A' + (nVal - 26)))
            elif nVal < 62:
                theString += str(('0' + (nVal - 52)))
            i += 1
        return theString

    #  JSON rendering methods 
    @classmethod
    def renderArrayAsJSON(cls, theList, useQuotes):
        """ generated source for method renderArrayAsJSON """
        s = "["
        i = 0
        while i < len(theList):
            #  AppEngine-specific, not needed yet: if (o instanceof Text) o = ((Text)o).getValue();
            if isinstance(o, (Date, )):
                o = (o).getTime()
            if useQuotes:
                s += "\""
            s += o.__str__()
            if useQuotes:
                s += "\""
            if i < len(theList) - 1:
                s += ", "
            i += 1
        return s + "]"

    @classmethod
    def renderStateHistory(cls, stateHistory):
        """ generated source for method renderStateHistory """
        renderedStates = ArrayList()
        for aState in stateHistory:
            renderedStates.add(renderStateAsSymbolList(aState))
        return renderedStates

    @classmethod
    def renderMoveHistory(cls, moveHistory):
        """ generated source for method renderMoveHistory """
        renderedMoves = ArrayList()
        for aMove in moveHistory:
            renderedMoves.add(cls.renderArrayAsJSON(aMove, True))
        return renderedMoves

    @classmethod
    def renderErrorHistory(cls, errorHistory):
        """ generated source for method renderErrorHistory """
        renderedErrors = ArrayList()
        for anError in errorHistory:
            renderedErrors.add(cls.renderArrayAsJSON(anError, True))
        return renderedErrors

    @classmethod
    def renderStateAsSymbolList(cls, theState):
        """ generated source for method renderStateAsSymbolList """
        #  Strip out the TRUE proposition, since those are implied for states.
        s = "( "
        for sent in theState:
            s += sentString.substring(6, 2 - len(sentString)).trim() + " "
        return s + ")"

    #  XML Rendering methods -- these are horribly inefficient and are included only for legacy/standards compatibility 
    @classmethod
    def renderLeafXML(cls, tagName, value):
        """ generated source for method renderLeafXML """
        return "<" + tagName + ">" + value.__str__() + "</" + tagName + ">"

    @classmethod
    def renderMoveHistoryXML(cls, moveHistory):
        """ generated source for method renderMoveHistoryXML """
        theXML = StringBuilder()
        theXML.append("<history>")
        for move in moveHistory:
            theXML.append("<move>")
            for action in move:
                theXML.append(cls.renderLeafXML("action", renderGdlToXML(action)))
            theXML.append("</move>")
        theXML.append("</history>")
        return theXML.__str__()

    @classmethod
    def renderErrorHistoryXML(cls, errorHistory):
        """ generated source for method renderErrorHistoryXML """
        theXML = StringBuilder()
        theXML.append("<errorHistory>")
        for errors in errorHistory:
            theXML.append("<errors>")
            for error in errors:
                theXML.append(cls.renderLeafXML("error", error))
            theXML.append("</errors>")
        theXML.append("</errorHistory>")
        return theXML.__str__()

    @classmethod
    def renderStateHistoryXML(cls, stateHistory):
        """ generated source for method renderStateHistoryXML """
        theXML = StringBuilder()
        theXML.append("<herstory>")
        for state in stateHistory:
            theXML.append(renderStateXML(state))
        theXML.append("</herstory>")
        return theXML.__str__()

    @classmethod
    def renderStateXML(cls, state):
        """ generated source for method renderStateXML """
        theXML = StringBuilder()
        theXML.append("<state>")
        for sentence in state:
            theXML.append(renderGdlToXML(sentence))
        theXML.append("</state>")
        return theXML.__str__()

    @classmethod
    def renderArrayXML(cls, tag, arr):
        """ generated source for method renderArrayXML """
        theXML = StringBuilder()
        i = 0
        while i < len(arr):
            theXML.append(cls.renderLeafXML(tag, arr.get(i)))
            i += 1
        return theXML.__str__()

    @classmethod
    def renderGdlToXML(cls, gdl):
        """ generated source for method renderGdlToXML """
        rval = ""
        if isinstance(gdl, (GdlConstant, )):
            return c.getValue()
        elif isinstance(gdl, (GdlFunction, )):
            if f.__name__.__str__() == "true":
                return "<fact>" + cls.renderGdlToXML(f.get(0)) + "</fact>"
            else:
                rval += "<relation>" + f.__name__ + "</relation>"
                while i < f.arity():
                    pass
                    i += 1
                return rval
        elif isinstance(gdl, (GdlRelation, )):
            if relation.__name__.__str__() == "true":
                while i < relation.arity():
                    pass
                    i += 1
                return rval
            else:
                rval += "<relation>" + relation.__name__ + "</relation>"
                while i < relation.arity():
                    pass
                    i += 1
                return rval
        else:
            System.err.println("gdlToXML Error: could not handle " + gdl.__str__())
            return None
Example #16
0
# update an existing index (adding a new document).

from java.net import URL
from java.util import Date

# from de.nava.informa.impl.basic import ChannelBuilder
# from de.nava.informa.utils import ChannelRegistry
from de.nava.informa.impl.basic import Item
from de.nava.informa.search import ItemDocument

from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriter

# update (3rd arg) index writer in directory (first arg)
start_time = Date()
writer = IndexWriter("index", StandardAnalyzer(), 0)

# create new (dummy) item
item = Item("Informa released", "blubb", URL("http://nava.de/news/2002/06/25"))
item.setFound(Date())

# add new item to index
writer.addDocument(ItemDocument.makeDocument(item))

writer.optimize()
writer.close()
end_time = Date()

print "updating the index took %d milliseconds in total." \
      % (end_time.getTime() - start_time.getTime())
from java.net import URL
from java.util import Date

# from de.nava.informa.impl.basic import ChannelBuilder
# from de.nava.informa.utils import ChannelRegistry
from de.nava.informa.impl.basic import Item
from de.nava.informa.search import ItemDocument

from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriter


# update (3rd arg) index writer in directory (first arg)
start_time = Date()
writer = IndexWriter("index", StandardAnalyzer(), 0)

# create new (dummy) item
item = Item("Informa released", "blubb",
            URL("http://nava.de/news/2002/06/25"))
item.setFound(Date())
	    
# add new item to index
writer.addDocument(ItemDocument.makeDocument(item))

writer.optimize()
writer.close()
end_time = Date()

print "updating the index took %d milliseconds in total." \
      % (end_time.getTime() - start_time.getTime())
Example #18
0
f = sys.stdin

bytes_read = 0

loads = getattr(json, JSON_DECODE_FUNC)

dumps = None

if len(sys.argv) > 2:
    dumps = getattr(json, sys.argv[2])

while True:
    oline = f.readline()
    l = len(oline)
    if l == 0:
        break
    bytes_read += l
    obj = loads(oline)
    if dumps != None:
        dumps(obj)

if jython:
    ms = (Date().getTime() - start.getTime())
else:
    delta = (datetime.now() - start)
    ms = delta.seconds * 1000 + delta.microseconds / 1000

print str(1000 * bytes_read / 1024 / 1024 /
          ms) + " MB/s %dbytes in %sseconds" % (bytes_read, ms / 1000)