def _save_results(self): results_json = JSONValue.toJSONString(self.results) access_key = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) if self.db.queryValue("SELECT task_id FROM {mt_analysis} WHERE task_id=?", self.task_id) == None: self.db.update("INSERT INTO {mt_analysis}(task_id, results_json, access_key, updated) VALUE(?,?,?,?)", self.task_id, results_json, access_key, self.timestamp) else: self.db.update("UPDATE {mt_analysis} SET results_json=?, updated=? WHERE task_id=?", results_json, self.timestamp, self.task_id)
def _get_answer(self, answer_json): o = JSONObject() answer_json = dict(o.getClass().cast(JSONValue.parse(answer_json))) if self.main_question != None and self.main_question in answer_json: # here we use the 'main question' setting. return answer_json[self.main_question] elif self.main_question == None and len(answer_json) > 0: # if main_question not set, use the first answer return answer_json.values()[0] return None
def __init__(self, messageBody): messageObject = JSONValue.parse(str(String(messageBody, "UTF-8"))) if isLogEnabled: log("parsed json to " + JSONValue.toJSONString(messageObject)) lines = messageObject.get("changes").split("\n") gameIdAndStartIncrementAndPlayers = lines[0].split("\t") self.gameId = int(gameIdAndStartIncrementAndPlayers[0]) self.gameStartIncrement = int(gameIdAndStartIncrementAndPlayers[1]) self.players = gameIdAndStartIncrementAndPlayers[2:] if lines[1]: self.currentBalance = float(lines[1]) self.increment = int(lines[2]) self.allowedActions = lines[3].split("\t") # TODO make it a set nextTimeoutLine = lines[4].split("\t") if len(nextTimeoutLine) == 3: self.nextTimeout = (str(nextTimeoutLine[0]), long(nextTimeoutLine[1]), long(nextTimeoutLine[2])) self.changes = [] for i in range(5, len(lines)): self.changes.append(GameStatusChange(lines[i].split("\t"))) self.warnings = messageObject.get("warnings")
def parse_answer_xml(self, assignment_id, answer_xml): ''' Return json string ''' json = {} answers = self.service.parseAnswers(answer_xml) for answer in answers.getAnswer(): answer_str = self.service.getAnswerValue(assignment_id, answer, True) # according to the implementation of RequesterService.getAnswerValue(), '\t' is the delimeter for question and answer strings. delim_pos = answer_str.find('\t') q, a = answer_str[:delim_pos], answer_str[delim_pos+1:] json[q] = a return JSONValue.toJSONString(json)
def run(self): self.record.setStart(self.timestamp) # execute the command, output should be a dict status, message, output = self.execute() # finish up. self.record.setEnd(int(time.time())) self.record.setStatus(status) self.record.setMessage(message) if output != None: self.record.setOutput(DrupalUtils.convertStringToBlog(JSONValue.toJSONString(output)))
def json_to_dict_proc (str_json): dict_aa = {} obj_aa = JSONValue.parse (str_json) # set_aaa = obj_aa.keySet () # for key in set_aaa: # print key + "\t", unit_aa = obj_aa.get (key) dict_aa[key] = unit_aa # return dict_aa
def result(context): response = httpPost(baseUrl + "/social/friendsSummary") if isLogEnabled: log("friends command response " + response.text) if response is None: fail("Publish friends summary returned no response") elif response.statusCode != 200: fail("Publish friends summary returned unexpected status code: %d" % (response.statusCode)) else: responseObject = JSONValue.parse(response.text) if responseObject is None: fail("Publish friends summary returned an unparsable response: %s" % (response.text)) if responseObject.get("result") != "ok": fail("Publish friends summary failed: %s" % (str(responseObject)))
def retrieve(playerIds, infoTypes): response = httpGet(baseUrl + "/social/players", [ NVPair("gameType", "SLOTS"), NVPair("playerIds", ",".join(map(str, playerIds))), NVPair("fields", ",".join(infoTypes)) ]) if response is None: fail("Player details returned no response for player IDs %s" % (",".join(map(str, playerIds)))) elif response.statusCode != 200: fail("Player details returned status code %d for player IDs %s" % (response.statusCode, ",".join(map(str, playerIds)))) else: result = JSONValue.parse(str(String(response.text, "UTF-8"))) if result.get("result") != "ok": fail("Player details retrieval failed for %s" % (str(playerIds)))
def getNextTournamentDetails(): result = TournamentDetails() response = httpPost(baseUrl + "tournaments/next", [NVPair("gameType", "TEXAS_HOLDEM")]) if response is None: fail("Next tournament returned an empty response") elif response.statusCode != 200: fail("Next tournament returned status: %d" % (response.statusCode)) else: responseObject = JSONValue.parse(response.text) if responseObject: result.tournamentId = responseObject.get("tournamentId") result.registeredPlayers = responseObject.get("registeredPlayers") result.millisToStart = responseObject.get("millisToStart") result.amIRegistered = responseObject.get("playerRegistered") else: fail("Unable to parse next tournament response %s" % (response.text)) return result
def __init__(self): sessionDuration = grinder.properties.getInt( "player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url") passwordHash = URLEncoder.encode( grinder.properties.getProperty("player.passwordHash"), "UTF-8") workers = grinder.properties.getInt("grinder.processes", 0) threads = grinder.properties.getInt("grinder.threads", 0) workerIndex = grinder.processNumber - grinder.firstProcessNumber threadsPerAgent = workers * threads agentIndex = grinder.agentNumber start = agentIndex * threadsPerAgent + workerIndex * threads if isLogEnabled: log("Worker will handle %s players starting from %d" % (threads, start)) playerRange = (start, threads) self.workerPlayers = [] params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % ( passwordHash, str(sessionDuration / 5), str( playerRange[0]), str(threads)) urlStr = players_url + "?" + params try: data = StringBuffer() url = URL(urlStr) conn = url.openConnection() rd = BufferedReader(InputStreamReader(conn.getInputStream())) line = rd.readLine() while line is not None: data.append(line) line = rd.readLine() rd.close() if isLogEnabled: log(data.toString()) message = JSONValue.parse(str(String(data.toString(), "UTF-8"))) for entry in message: self.workerPlayers.append((entry.get(0), entry.get(1))) except Exception: raise Exception("Couldn't fetch players from %s: %s" % (urlStr, traceback.format_exc())) if isLogEnabled: log(str(self.workerPlayers))
def result(context): response = httpPost(baseUrl + "/social/friendsSummary") if isLogEnabled: log("friends command response " + response.text) if response is None: fail("Publish friends summary returned no response") elif response.statusCode != 200: fail( "Publish friends summary returned unexpected status code: %d" % (response.statusCode)) else: responseObject = JSONValue.parse(response.text) if responseObject is None: fail( "Publish friends summary returned an unparsable response: %s" % (response.text)) if responseObject.get("result") != "ok": fail("Publish friends summary failed: %s" % (str(responseObject)))
def retrieve(playerIds, infoTypes): response = httpGet( baseUrl + "/social/players", [ NVPair("gameType", "SLOTS"), NVPair("playerIds", ",".join(map(str, playerIds))), NVPair("fields", ",".join(infoTypes)), ], ) if response is None: fail("Player details returned no response for player IDs %s" % (",".join(map(str, playerIds)))) elif response.statusCode != 200: fail( "Player details returned status code %d for player IDs %s" % (response.statusCode, ",".join(map(str, playerIds))) ) else: result = JSONValue.parse(str(String(response.text, "UTF-8"))) if result.get("result") != "ok": fail("Player details retrieval failed for %s" % (str(playerIds)))
def __init__(self): sessionDuration = grinder.properties.getInt("player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url") passwordHash = URLEncoder.encode(grinder.properties.getProperty("player.passwordHash"), "UTF-8") workers = grinder.properties.getInt("grinder.processes", 0) threads = grinder.properties.getInt("grinder.threads", 0) workerIndex = grinder.processNumber - grinder.firstProcessNumber threadsPerAgent = workers * threads agentIndex = grinder.agentNumber start = agentIndex * threadsPerAgent + workerIndex * threads if isLogEnabled: log("Worker will handle %s players starting from %d" % (threads, start)) playerRange = (start, threads) self.workerPlayers = [] params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % ( passwordHash, str(sessionDuration / 5), str(playerRange[0]), str(threads), ) urlStr = players_url + "?" + params try: data = StringBuffer() url = URL(urlStr) conn = url.openConnection() rd = BufferedReader(InputStreamReader(conn.getInputStream())) line = rd.readLine() while line is not None: data.append(line) line = rd.readLine() rd.close() if isLogEnabled: log(data.toString()) message = JSONValue.parse(str(String(data.toString(), "UTF-8"))) for entry in message: self.workerPlayers.append((entry.get(0), entry.get(1))) except Exception: raise Exception("Couldn't fetch players from %s: %s" % (urlStr, traceback.format_exc())) if isLogEnabled: log(str(self.workerPlayers))
def uploadImage(self, aFile, projectID, storageID): ''' Upload an image to the server. The image will be associated to a project and a storage. ''' host = self.biaflows.getUploadURL() client = HttpClient(self.biaflows.getPublicKey(), self.biaflows.getPrivateKey(), host) url = "/upload?idStorage=" + storageID + "&cytomine=" + self.biaflows.getHost( ) + "&idProject=" + projectID entity = MultipartEntity() entity.addPart("files[]", FileBody(File(aFile))) client.authorize("POST", url, entity.getContentType().getValue(), "application/json,*/*") client.connect(host + url) code = client.post(entity) response = client.getResponseData() client.disconnect() obj = JSONValue.parse(response) return code, obj
def result(context): if context.tableId: try: botStrategy = context.botStrategy gotGameStatusMessage = False def handleReceivedMessage(contentType, messageBody): def strMessageBody(messageBody): return str(String(messageBody, "UTF-8")).replace( "\\n", "\n").replace("\\t", "\t") if contentType in [ "GAME_STATUS", "INITIAL_GAME_STATUS" ]: log("processing doc: " + strMessageBody(messageBody)) gameStatusChanges = GameStatusChanges(messageBody) processChanges(botStrategy, gameStatusChanges, context) context.lastReceivedIncrement = max( context.lastReceivedIncrement, gameStatusChanges.increment) else: log("Not processing doc of type %s with content: %s" % (contentType, strMessageBody(messageBody))) def checkForRabbitMessage(): rabbitMessage = context.consumer.nextDelivery(0) if rabbitMessage is not None: log("RabbitMQ delivery received") return rabbitMessage.properties.contentType, retrieveBody( rabbitMessage) else: log("No RabbitMQ delivery available") return None, None def checkForLightstreamerMessage(): try: with context.gameLightstreamerMessageQueueLock: lsMessage = context.gameLightstreamerMessageQueue.popleft( ) log("LS delivery received") return lsMessage[0], lsMessage[1] except IndexError: log("No LS delivery available") return None, None checkHandler = checkForLightstreamerMessage if context.consumer: checkHandler = checkForRabbitMessage while True: contentType, messageBody = checkHandler() if contentType is not None: handleReceivedMessage(contentType, messageBody) else: break if gotGameStatusMessage: if botStrategy.isTableFull and not botStrategy.isPlayer: context.botStrategy = botStrategyClass() context.tableId = None gotGameStatusMessage = False return if time( ) < botStrategy.tsLastCommand + botStrategy.commandCooldown: return if botStrategy.isPlayer: if botStrategy.canLeave: command = context.botStrategy.getNextCommand() if command is not None: sendGameCommand(context.tableId, command.commandType, command.args, context.lastReceivedIncrement) botStrategy.tsLastCommand = time() else: command = context.botStrategy.getJoin() sendJoin(context.tableId, command.commandType, command.args, context.lastReceivedIncrement) botStrategy.tsLastCommand = time() if time() > botStrategy.tsLastCommand + 10 and time( ) > botStrategy.tsLastGetStatusCommand + 10: sendTimeoutGetStatus(context.tableId, "GetStatus", [], context.lastReceivedIncrement) botStrategy.tsLastGetStatusCommand = time() except Exception: fail("Message processing failed for %s: %s" % (context.playerId, traceback.format_exc())) else: try: response = httpGet(baseUrl + ( "lobbyCommand/mobile/tableLocator?gameType=%s&clientId=%s&variationName=%s" % (definition.gameType, definition.client, definition.variation))) responseObject = JSONValue.parse(response.text) if response is None: fail("Table location failed with response %s" % (response.text)) elif response.statusCode != 200: fail("Table location failed with status code: %d" % (responseObject.statusCode)) elif responseObject.get("tableId") is None: fail( "Table location failed with missing table ID in response %s" % (str(responseObject))) else: tableId = str(responseObject.get("tableId")).rstrip( '0').rstrip('.') log("tableId = " + tableId) def connectToRabbit(playerId, tableId, rabbitConnection): if rabbitConnection: rabbitConnection.close() rabbitConnectionFactory = getRabbitConnectionFactory( playerId) rabbitConnection = rabbitConnectionFactory.newConnection( ) channel = rabbitConnection.createChannel() queueName = channel.queueDeclare().getQueue() channel.queueBind( queueName, "player-direct", "PLAYERTABLE." + playerId + "." + tableId) channel.queueBind(queueName, "player-direct", "PLAYER." + playerId) consumer = QueueingConsumer(channel) channel.basicConsume(queueName, True, consumer) return (rabbitConnection, consumer) def connectToLightstreamer(playerId, tableId, messageHandler): lsClient = createLightstreamerConnection( grinder.properties.getProperty( "lightstreamer.host")) subscribeTo([ "PLAYER." + playerId, "PLAYERTABLE." + playerId + "." + tableId ], lsClient, messageHandler) return lsClient def handleLightstreamerMessage(contentType, messageBody): with context.gameLightstreamerMessageQueueLock: context.gameLightstreamerMessageQueue.append( (contentType, messageBody)) if useRabbitForGameMessages: log("Using RabbitMQ connection for player " + context.playerId) if context.rabbitConnection: context.rabbitConnection.close() context.rabbitConnection, context.consumer = connectToRabbit( context.playerId, tableId, context.rabbitConnection) else: log("Using LightStreamer connection for player " + context.playerId) context.gameLightstreamerConnection = closeLighstreamerConnection( context.gameLightstreamerConnection) context.gameLightstreamerConnection = connectToLightstreamer( context.playerId, tableId, handleLightstreamerMessage) sendInitialGetStatus(tableId, "GetStatus", [], context.lastReceivedIncrement) context.tableId = tableId context.botStrategy = botStrategyClass() context.botStrategy.tsLastGetStatusCommand = time() except Exception: fail("Table connection failed for %s: %s" % (context.playerId, traceback.format_exc()))
import re import sys try: H = open(sys.argv[1], 'rb') json_string = "" for buf in H: json_string = json_string + buf H.close() except EnvironmentError, err: print "Failed opening " + sys.argv[1] print str(err) usage() sys.exit(3) config=JSONValue.parse(json_string); user = config.get("username") pwd = config.get("password") url = config.get("url") localHome = weblogic.management.Helper.getAdminMBeanHome( user, pwd, url ); remote = localHome.getMBeanServer() print(remote) objectList = localHome.getAllMBeans(); mbeanIterator = objectList.iterator(); while (mbeanIterator.hasNext()): print "==============================================" mbean = mbeanIterator.next() print (mbean) name = mbean.getObjectName()
from array import array import sys try: H = open(sys.argv[1], 'rb') json_string = "" for buf in H: json_string = json_string + buf H.close() except EnvironmentError, err: print "Failed opening " + sys.argv[1] print str(err) usage() sys.exit(3) config = JSONValue.parse(json_string) user = config.get("username") pwd = config.get("password") url = config.get("url") factory = config.get("factory") print factory ad = array(java.lang.String, [user, pwd]) n = java.util.HashMap() n.put(javax.management.remote.JMXConnector.CREDENTIALS, ad) n.put(javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, factory) n.put(javax.naming.InitialContext.SECURITY_PRINCIPAL, user) n.put(javax.naming.InitialContext.SECURITY_CREDENTIALS, pwd) jmxurl = javax.management.remote.JMXServiceURL(url) localHome = javax.management.remote.JMXConnectorFactory.connect(jmxurl, n)
def handle(self, messageType, messageBody): log("Received message of type " + str(messageType)) if messageType in self.handlers: handler = self.handlers[messageType] message = JSONValue.parse(str(String(messageBody, "UTF-8"))) handler(message)
def result(context): if context.tableId: try: botStrategy = context.botStrategy gotGameStatusMessage = False def handleReceivedMessage(contentType, messageBody): def strMessageBody(messageBody): return str(String(messageBody, "UTF-8")).replace("\\n", "\n").replace("\\t", "\t") if contentType in ["GAME_STATUS", "INITIAL_GAME_STATUS"]: log("processing doc: " + strMessageBody(messageBody)) gameStatusChanges = GameStatusChanges(messageBody) processChanges(botStrategy, gameStatusChanges, context) context.lastReceivedIncrement = max( context.lastReceivedIncrement, gameStatusChanges.increment ) else: log( "Not processing doc of type %s with content: %s" % (contentType, strMessageBody(messageBody)) ) def checkForRabbitMessage(): rabbitMessage = context.consumer.nextDelivery(0) if rabbitMessage is not None: log("RabbitMQ delivery received") return rabbitMessage.properties.contentType, retrieveBody(rabbitMessage) else: log("No RabbitMQ delivery available") return None, None def checkForLightstreamerMessage(): try: with context.gameLightstreamerMessageQueueLock: lsMessage = context.gameLightstreamerMessageQueue.popleft() log("LS delivery received") return lsMessage[0], lsMessage[1] except IndexError: log("No LS delivery available") return None, None checkHandler = checkForLightstreamerMessage if context.consumer: checkHandler = checkForRabbitMessage while True: contentType, messageBody = checkHandler() if contentType is not None: handleReceivedMessage(contentType, messageBody) else: break if gotGameStatusMessage: if botStrategy.isTableFull and not botStrategy.isPlayer: context.botStrategy = botStrategyClass() context.tableId = None gotGameStatusMessage = False return if time() < botStrategy.tsLastCommand + botStrategy.commandCooldown: return if botStrategy.isPlayer: if botStrategy.canLeave: command = context.botStrategy.getNextCommand() if command is not None: sendGameCommand( context.tableId, command.commandType, command.args, context.lastReceivedIncrement ) botStrategy.tsLastCommand = time() else: command = context.botStrategy.getJoin() sendJoin(context.tableId, command.commandType, command.args, context.lastReceivedIncrement) botStrategy.tsLastCommand = time() if time() > botStrategy.tsLastCommand + 10 and time() > botStrategy.tsLastGetStatusCommand + 10: sendTimeoutGetStatus(context.tableId, "GetStatus", [], context.lastReceivedIncrement) botStrategy.tsLastGetStatusCommand = time() except Exception: fail("Message processing failed for %s: %s" % (context.playerId, traceback.format_exc())) else: try: response = httpGet( baseUrl + ( "lobbyCommand/mobile/tableLocator?gameType=%s&clientId=%s&variationName=%s" % (definition.gameType, definition.client, definition.variation) ) ) responseObject = JSONValue.parse(response.text) if response is None: fail("Table location failed with response %s" % (response.text)) elif response.statusCode != 200: fail("Table location failed with status code: %d" % (responseObject.statusCode)) elif responseObject.get("tableId") is None: fail("Table location failed with missing table ID in response %s" % (str(responseObject))) else: tableId = str(responseObject.get("tableId")).rstrip("0").rstrip(".") log("tableId = " + tableId) def connectToRabbit(playerId, tableId, rabbitConnection): if rabbitConnection: rabbitConnection.close() rabbitConnectionFactory = getRabbitConnectionFactory(playerId) rabbitConnection = rabbitConnectionFactory.newConnection() channel = rabbitConnection.createChannel() queueName = channel.queueDeclare().getQueue() channel.queueBind(queueName, "player-direct", "PLAYERTABLE." + playerId + "." + tableId) channel.queueBind(queueName, "player-direct", "PLAYER." + playerId) consumer = QueueingConsumer(channel) channel.basicConsume(queueName, True, consumer) return (rabbitConnection, consumer) def connectToLightstreamer(playerId, tableId, messageHandler): lsClient = createLightstreamerConnection( grinder.properties.getProperty("lightstreamer.host") ) subscribeTo( ["PLAYER." + playerId, "PLAYERTABLE." + playerId + "." + tableId], lsClient, messageHandler, ) return lsClient def handleLightstreamerMessage(contentType, messageBody): with context.gameLightstreamerMessageQueueLock: context.gameLightstreamerMessageQueue.append((contentType, messageBody)) if useRabbitForGameMessages: log("Using RabbitMQ connection for player " + context.playerId) if context.rabbitConnection: context.rabbitConnection.close() context.rabbitConnection, context.consumer = connectToRabbit( context.playerId, tableId, context.rabbitConnection ) else: log("Using LightStreamer connection for player " + context.playerId) context.gameLightstreamerConnection = closeLighstreamerConnection( context.gameLightstreamerConnection ) context.gameLightstreamerConnection = connectToLightstreamer( context.playerId, tableId, handleLightstreamerMessage ) sendInitialGetStatus(tableId, "GetStatus", [], context.lastReceivedIncrement) context.tableId = tableId context.botStrategy = botStrategyClass() context.botStrategy.tsLastGetStatusCommand = time() except Exception: fail("Table connection failed for %s: %s" % (context.playerId, traceback.format_exc()))