📄 tacagent.java
字号:
private void handleRecoverBidIDs(TACMessage msg) { while (msg.nextTag()) { if (msg.isTag("auctionBidIDsTuple")) { int auctionID = -1; int bidID = -1; while (msg.nextTag()) { if (msg.isTag("auctionID")) { auctionID = msg.getValueAsInt(-1); } else if (msg.isTag("bidID")) { bidID = msg.getValueAsInt(-1); } else if (msg.isTag("/auctionBidIDsTuple")) { if (auctionID != -1 && bidID != -1) { int auction = getAuctionPos(auctionID); Bid bid = new Bid(auction); bid.setID(bidID); // Request information about this bid log.finer("recovering bid " + bidID + " for " + getAuctionTypeAsString(auction)); TACMessage msg2 = new TACMessage("bidInfo"); msg2.setParameter("bidID", bidID); msg2.setUserData(bid); sendMessage(msg2, this); } break; } } } else if (msg.isTag("commandStatus")) { int status = msg.getValueAsInt(NO_ERROR); if (status != NO_ERROR) { log.severe("could not recover bids for game " + nextGameID + ": status=" + commandStatusToString(status)); } } } } private void addOwn(int category, int type, int day, int quantity) { int pos = getAuctionFor(category, type, day); owns[pos] += quantity; } private void addAuction(int category, int type, int day, int id) { int pos = getAuctionFor(category, type, day); auctionIDs[pos] = id; log.finest("Auction " + pos + " (" + getAuctionTypeAsString(pos) + "): " + id); } private int getAuctionPos(int id) { for (int i = 0; i < NO_AUCTIONS; i++) { if (auctionIDs[i] == id) { return i; } } throw new IllegalArgumentException("auction " + id + " not found"); } private void setClient(int client, int arr, int dep, int hotel, int[] events) { int[] prefs = clientPrefs[client]; prefs[ARRIVAL] = arr; prefs[DEPARTURE] = dep; prefs[HOTEL_VALUE] = hotel; prefs[E1] = events[0]; prefs[E2] = events[1]; prefs[E3] = events[2]; } private void handleNextGame(TACMessage msg) { TACConnection connection = this.connection; if (connection == null) return; int status = NO_ERROR; int gameID = -1; long startTime = 0L; while (msg.nextTag()) { if (msg.isTag("gameID")) { gameID = msg.getValueAsInt(-1); } else if (msg.isTag("startTime")) { startTime = msg.getValueAsLong(-1); } else if (msg.isTag("commandStatus")) { status = mapCommandStatus(msg.getValueAsInt(NO_ERROR)); } } if ((gameID >= 0) && (startTime > 0)) { this.nextGameID = gameID; this.nextGameTime = startTime * 1000; long delay = this.nextGameTime - getServerTime(); log.fine("Next Game -> " + nextGameID + " (should wait " + (delay / 1000) + ')'); if (delay < 0) { // Game might have ended!!! FIX THIS!!!! if ((delay + 1000 + gameLength) < 0) { if (playingGame == gameID) { gameEnds(); } // Should not play this game again... request again later... this.nextGameID = -1; } else { nextGameStarts(connection); } } else { if (display != null) { display.setGameStatus(userName + ": Waiting for game: " + nextGameID); } if (delay > 50000) { long sleepTime = (long) (60 * (10000 + Math.random() * 2000)); reset(sleepTime < delay ? sleepTime : delay, connection); } else { TimeDispatcher.getDefault() .addTask(nextGameTime + 1000, "gameStarts", connection, this); } } } else if (status != NO_ERROR) { fatalError("Failed to get next game" + (gameType != null ? " with game type '" + gameType + '\'' : "") + ": status=" + commandStatusToString(status), 5000); } } private void handleServerTime(TACMessage msg) { while (msg.nextTag()) { if (msg.isTag("time")) { long serverTime = msg.getValueAsLong(-1) * 1000; long time = System.currentTimeMillis(); timeDiff = time - serverTime; log.fine("Setting server time diff to " + (timeDiff / 1000) + " seconds"); // Make sure the log formatter uses the server time instead of // local time logFormatter.setTimeDiff(timeDiff); TimeDispatcher.getDefault().setTimeDiff(timeDiff); } } } private static int mapCommandStatus(int status) { if (status == 9) { return GAME_FUTURE; } else { return status; } } // ------------------------------------------------------------------- // Logging handling // ------------------------------------------------------------------- private void initLogging(int consoleLevel, int fileLevel, boolean exitIfFileFails) { Level consoleLogLevel = LogFormatter.getLogLevel(consoleLevel); Level fileLogLevel = LogFormatter.getLogLevel(fileLevel); Level logLevel = consoleLogLevel.intValue() < fileLogLevel.intValue() ? consoleLogLevel : fileLogLevel; // Initialize the logging Logger root = Logger.getLogger("se"); root.setLevel(logLevel); LogFormatter.setConsoleLevel(consoleLogLevel);// LogFormatter.setLevelForAllHandlers(logLevel); if (fileLevel < 6) { try { this.rootFileHandler = new FileHandler(logPrefix + "%g.log", 1000000, 10); this.rootFileHandler.setLevel(fileLogLevel); root.addHandler(this.rootFileHandler); } catch (IOException ioe) { log.log(Level.SEVERE, "could not log to file", ioe); if (exitIfFileFails) { fatalError("could not log to file '" + logPrefix + "0.log'"); } } } this.logFormatter = new LogFormatter(); // Set shorter names for the log this.logFormatter.setAliasLevel(2); LogFormatter.setFormatterForAllHandlers(this.logFormatter); } private synchronized void enterGameLog(int gameID) { if (rootFileHandler != null) { exitGameLog(); LogFormatter.separator(log, Level.FINE, "Entering log for game " + gameID); try { Logger root = Logger.getLogger(""); String name = childLogPrefix + "_GAME_" + gameID + ".log"; childFileHandler = new FileHandler(name, true); childFileHandler.setFormatter(logFormatter); childFileHandler.setLevel(rootFileHandler.getLevel()); childFileName = name; root.addHandler(childFileHandler); root.removeHandler(rootFileHandler); LogFormatter.separator(log, Level.FINE, "Log for game " + gameID + " started"); } catch (Exception e) { log.log(Level.SEVERE, "could not open child log file for game " + gameID, e); } } } private synchronized void exitGameLog() { if (childFileHandler != null && rootFileHandler != null) { Logger root = Logger.getLogger(""); LogFormatter.separator(log, Level.FINE, "Game log complete"); root.addHandler(rootFileHandler); root.removeHandler(childFileHandler); childFileHandler.close(); childFileHandler = null; if (childFileName != null) { new File(childFileName + ".lck").delete(); childFileName = null; } } } // ------------------------------------------------------------------- // // ------------------------------------------------------------------- private class AgentTableModel extends AbstractTableModel { private final String[] columnName = new String[] { "ID", "Type", "Ask Price", "Bid Price", "Status", "PS", "BidString", "HQW", "Allocation", "Own", "Cost" }; public String getColumnName(int col) { return columnName[col]; } public int getRowCount() { return 28; } public int getColumnCount() { return columnName.length; } public Object getValueAt(int row, int col) { switch (col) { case 0: return Integer.toString(auctionIDs[row]); case 1: return getAuctionTypeAsString(row); case 2: return Float.toString(quotes[row].getAskPrice()); case 3: return Float.toString(quotes[row].getBidPrice()); case 4: return quotes[row].getAuctionStatusAsString(); case 5: Bid bd = bids[row]; return (bd != null) ? bd.getProcessingStateAsString() : "no bid"; case 6: Bid bid = bids[row]; if (bid != null) { return bid.getBidString(); } return "no bid"; case 7: { int hqw = quotes[row].getHQW(); return hqw >= 0 ? Integer.toString(hqw) : ""; } case 8: return Integer.toString(allocate[row]); case 9: return Integer.toString(owns[row]); case 10: return Float.toString(costs[row]); default: return "-"; } } } // ------------------------------------------------------------------- // Temporary fatal error handling // ------------------------------------------------------------------- void fatalError(String message) { log.severe("************************************************************"); log.severe("* FATAL ERROR: " + message); log.severe("************************************************************"); disconnect(500); System.exit(1); } void fatalError(String message, long delay) { log.severe("************************************************************"); log.severe("* FATAL ERROR: " + message); log.severe("************************************************************"); reset(delay, connection); } // ------------------------------------------------------------------- // Startup and argument handling // ------------------------------------------------------------------- public static void main(String[] args) { String usage = "Usage: tacagent.jar [-options]\n" + "where options include:\n" + " -config <configfile> set the config file to use\n" + " -agentimpl <className> set the agent implementation\n" + " -agent <agentname> set the agent name\n" + " -password <password> set the agent password\n" + " -host <host> set the TAC Info Server host\n" + " -port <port> set the TAC Info Server port\n"// + " -gameType <type> set the game type to play\n" + " -exitAfterGames <games> set the number of games to play\n" + " -connection <className> set the TAC connection handler\n" + " -consoleLogLevel <level> set the console log level\n" + " -fileLogLevel <level> set the file log level\n" + " -logPrefix <prefix> set the prefix to log files\n" + " -nogui do not show agent gui\n" + " -h show this help message\n"; ArgEnumerator a = new ArgEnumerator(args, usage, false); String configFile = a.getArgument("-config"); if (configFile == null) { configFile = "agent.conf"; } File configFP = new File(configFile); Properties config = getConfig(configFile, configFP); if (config == null) { config = new Properties(); } String agentClass = trim(a.getArgument("-agentimpl", config.getProperty("agentimpl", "se.sics.tac.aw.DummyAgent"))); // Try to create the agent AgentImpl agent; try { agent = (AgentImpl) Class.forName(agentClass).newInstance(); } catch (Exception e) { log.log(Level.SEVERE, "could not create AgentImpl object of class " + agentClass, e); new TACAgent(null).fatalError("no agent implementation available"); return; } // Add the agents own arguments usage = agent.getUsage(); if (usage != null) { a.setUsage(a.getUsage() + "\nOptions for agent implementation " + agentClass + '\n' + usage + '\n'); } a.checkHelp(); boolean gui = !(a.hasArgument("-nogui") || "true".equals(config.getProperty("nogui", null))); TACAgent agentWare = new TACAgent(agent, a, config); if (gui) { agentWare.showGUI(); } // Allow garbage usage usage = null; a = null; configFP = null; config = null; } // Returns the configuration from the specified configuration file // if that file exists. Otherwise NULL is returned. // If the config file could not be properly parsed the Java will // be terminated with an error message. public static Properties getConfig(String configFile) { return getConfig(configFile, new File(configFile)); } private static Properties getConfig(String configFile, File configFP) { try { if (configFP.exists()) { InputStream input = new BufferedInputStream(new FileInputStream(configFP)); try { Properties p = new Properties(); p.load(input); p.setProperty("CONFIG_FILE", configFile); return p; } finally { input.close(); } } } catch (Exception e) { System.err.println("could not read config file '" + configFile + "':"); e.printStackTrace(); System.exit(1); } return null; } private static int getInt(Properties p, String name, int defaultValue) { String v = trim(p.getProperty(name)); if (v != null) { try { return Integer.parseInt(v); } catch (Exception e) { System.err.println("Non-integer value for parameter '" + name + "'='" + v + "' in config file " + p.getProperty("CONFIG_FILE", "")); System.exit(1); } } return defaultValue; } private static String trim(String text) { return (text == null || (text = text.trim()).length() == 0) ? null : text; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -