Example #1
0
 private static Strategy createStrategy(SubnodeConfiguration strategyConfig) {
   Strategy result;
   String desc = "?";
   try {
     String className = strategyConfig.getString("/@class");
     desc = strategyConfig.getString("/@desc", className);
     String fullClassName = Strategy.class.getPackage().getName() + "." + className;
     result = (Strategy) Class.forName(fullClassName).newInstance();
   } catch (Exception e) {
     throw new FatalException("Invalid strategy \"" + desc + "\"", e);
   }
   return result;
 }
Example #2
0
 public Server(SubnodeConfiguration serverConfig, ConfigManager configManager, Console console)
     throws InvalidConfigurationException {
   // Put here only values that don't need config refresh
   this.enabled = serverConfig.getBoolean("/@enabled", true);
   this.loginUrl = serverConfig.getString("/loginUrl");
   this.user = serverConfig.getString("/user");
   this.villages = new HashMap<String, Village>();
   this.util = new Util(serverConfig, configManager, console);
   this.serverStrategies = new HashMap<String, Strategy>();
   this.serverStrategyList = new ArrayList<Strategy>();
   // All other attributes must be fetched in updateConfig
   updateConfig(serverConfig);
 }
Example #3
0
 private void setTribeType(SubnodeConfiguration serverConfig) {
   String tribeString = serverConfig.getString("@tribe", null);
   if (tribeString == null) {
     String desc = serverConfig.getString("@desc", "");
     String msg = Util.getLocalMessage("msg.noTribe", this.getClass());
     String message = MessageFormatter.format(msg, desc);
     throw new FatalException(message);
   }
   //		String tribeKey = util.getTranslator().getKeyword(tribeString);
   try {
     this.util.setTribeType(TribeType.fromLanguageValue(tribeString, util.getTranslator()));
   } catch (InvalidConfigurationException e) {
     throw new FatalException(e);
   }
 }
  /** @param config */
  public GrSimNetworkCfg(SubnodeConfiguration config) {
    ip = config.getString("ip", "127.0.0.1");
    port = config.getInt("port", 20011);
    teamYellow = config.getBoolean("teamYellow", false);

    key = config.getInt("[@id]");
  }
Example #5
0
 public String getPluginPath() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   String pluginPath = sObj.getString("pluginpath");
   if (!pluginPath.endsWith("/")) {
     pluginPath = pluginPath + "/";
   }
   return pluginPath;
 }
Example #6
0
 public String getLogPath() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   String logPath = sObj.getString("logpath");
   if (logPath == null) logPath = "./logs";
   if (logPath.endsWith("/") || logPath.endsWith("\\\\"))
     logPath = logPath.substring(0, logPath.length() - 1);
   return new File(logPath).getAbsolutePath();
 }
Example #7
0
 public boolean getGenerateName() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   int value = Integer.parseInt(sObj.getString("generatename"));
   if (value == 1) {
     return true;
   } else {
     return false;
   }
 }
Example #8
0
 public String getStringParams(String section, String param) {
   String return_param = null;
   try {
     SubnodeConfiguration sObj = iniConfObj.getSection(section);
     return_param = sObj.getString(param);
   } catch (Exception ex) {
     System.out.println("AgentEngine : Config : Error : " + ex.toString());
   }
   return return_param;
 }
Example #9
0
 public int getIntParams(String section, String param) {
   int return_param = -1;
   try {
     SubnodeConfiguration sObj = iniConfObj.getSection(section);
     return_param = Integer.parseInt(sObj.getString(param));
   } catch (Exception ex) {
     System.out.println("AgentEngine : Config : Error : " + ex.toString());
   }
   return return_param;
 }
Example #10
0
 public String getPluginConfigString() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   // final Map<String,String> result=new TreeMap<String,String>();
   StringBuilder sb = new StringBuilder();
   final Iterator it = sObj.getKeys();
   while (it.hasNext()) {
     final Object key = it.next();
     final String value = sObj.getString(key.toString());
     // result.put(key.toString(),value);
     sb.append(key.toString() + "=" + value + ",");
   }
   return sb.toString().substring(0, sb.length() - 1);
   // return result;
 }
  public ConfigKey generateByPropertiesKey(String key) {
    SubnodeConfiguration configurationAt = null;
    try {
      if (Character.isLetter(key.charAt(0))) {
        configurationAt = keysConfig.configurationAt(key);
      }
    } catch (IllegalArgumentException e) {
      // Can't find a key. maybe its an alternate key.
    }
    if (configurationAt == null || configurationAt.isEmpty()) {
      key = alternateKeysMap.get(key);
      configurationAt = keysConfig.configurationAt(key);
    }

    String type = configurationAt.getString("type");
    if (StringUtils.isBlank(type)) {
      type = "String";
    }
    String[] validValues = configurationAt.getStringArray("validValues");

    // Description containing the list delimiter *will* be broken into an array, so rejoin it using
    // that delimiter.
    // We pad the separator because the strings in the array are trimmed automatically.
    String description =
        StringUtils.join(
            configurationAt.getStringArray("description"),
            configurationAt.getListDelimiter() + " ");
    String alternateKey = keysConfig.getString("/" + key + "/" + "alternateKey");

    // If the isReloadable attribute isn't specified - assume it is false
    boolean reloadable = configurationAt.getBoolean("isReloadable", false);
    ConfigKey configKey =
        new ConfigKey(
            type,
            description,
            alternateKey,
            key,
            "",
            validValues,
            "",
            getHelperByType(type),
            reloadable,
            isDeprecated(key));
    configKey.setParser(parser);
    return configKey;
  }
Example #12
0
  public static void populateConfiguration(OGraphDatabase db)
      throws IOException, ConfigurationException {
    Logger.info("Load initial configuration...");
    InputStream is;
    if (Play.application().isProd())
      is = Play.application().resourceAsStream(CONFIGURATION_FILE_NAME);
    else is = new FileInputStream(Play.application().getFile("conf/" + CONFIGURATION_FILE_NAME));
    HierarchicalINIConfiguration c = new HierarchicalINIConfiguration();
    c.setEncoding("UTF-8");
    c.load(is);
    CharSequence doubleDot = "..";
    CharSequence dot = ".";

    Set<String> sections = c.getSections();
    for (String section : sections) {
      Class en = PropertiesConfigurationHelper.configurationSections.get(section);
      if (en == null) {
        Logger.warn(section + " is not a valid configuration section, it will be skipped!");
        continue;
      }
      SubnodeConfiguration subConf = c.getSection(section);
      Iterator<String> it = subConf.getKeys();
      while (it.hasNext()) {
        String key = (it.next());
        Object value = subConf.getString(key);
        key =
            key.replace(
                doubleDot,
                dot); // bug on the Apache library: if the key contain a dot, it will be doubled!
        try {
          PropertiesConfigurationHelper.setByKey(en, key, value);
        } catch (Exception e) {
          Logger.warn(
              "Error loading initial configuration: Section "
                  + section
                  + ", key: "
                  + key
                  + ", value: "
                  + value,
              e);
        }
      }
    }
    is.close();
    Logger.info("...done");
  }
Example #13
0
 public String getAgentName() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("agentname");
 }
Example #14
0
 public String getServerDesc() {
   // When "desc" is not set, use the server url instead
   return config.getString("/@desc", getServerId());
 }
Example #15
0
 public String getRegion() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("regionname");
 }
Example #16
0
 public String getAMPQControlHost() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("ampq_control_host");
 }
Example #17
0
 public String getAMPQControlUser() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("ampq_control_username");
 }
Example #18
0
 private void updateConfig(SubnodeConfiguration newServerConfig)
     throws InvalidConfigurationException {
   log.debug("Updating server config for " + getServerId());
   this.config = newServerConfig;
   this.util.setServerConfig(newServerConfig);
   this.util.setServer(this);
   this.util.setServerId(user, getServerId()); // set server id for use in report processing
   // check if reading reports from overall server
   reportMode = newServerConfig.getString("/reports", null); // simple format to just read
   reportMode =
       newServerConfig.getString(
           "/reports/@enabled", reportMode); // complex config with processing
   if (reportMode != null) {
     SubnodeConfiguration reportConfig = newServerConfig.configurationAt("/reports");
     reportMode =
         reportConfig.getString("/output/@format", reportMode); // complex config with processing
     EventLog.log(loginUrl + " reportMode=" + reportMode);
     reportReader.setReportsMode(reportMode, reportConfig);
   }
   messageMode = newServerConfig.getString("/messages", null);
   messageMode = newServerConfig.getString("/messages/@enabled", messageMode);
   // note once enabled have to turn off by setting false or will not call to disable
   if (messageMode != null) {
     SubnodeConfiguration messageConfig = newServerConfig.configurationAt("/messages");
     String messageText = messageConfig.getString("/@commands", null);
     EventLog.log(
         loginUrl + " messageMode=" + messageMode + " Command Text (" + messageText + ")");
     // use same as mode or a separate param?
     messageReader.setMessagesMode(messageMode, messageConfig);
   }
   setTribeType(newServerConfig);
   //
   // Update villages
   // When a village is disabled or removed from the configuration, it is deleted from
   // this.villages
   List<Village> deletableVillages = new ArrayList<Village>(villages.values());
   // Loop all enabled villages
   List<SubnodeConfiguration> villageConfigs =
       newServerConfig.configurationsAt("/village[@enabled='true']");
   for (SubnodeConfiguration villageConfig : villageConfigs) {
     String id = Village.getIdFromConfig(villageConfig); // Either uid or url
     Village village = this.villages.get(id);
     if (village == null) {
       // New village
       village = new Village(util, villageConfig, strategyStatus);
       this.villages.put(id, village);
     } else {
       // Village already exists
       village.updateConfig(villageConfig, util);
       deletableVillages.remove(village); // This village is still enabled	
     }
   }
   // Removing deleted or disabled villages
   for (Village village : deletableVillages) {
     this.villages.remove(village.getId());
     village.terminate();
   }
   //
   // Update server strategies
   serverStrategyList =
       updateStrategies(
           "/serverStrategy[@enabled='true']", newServerConfig, serverStrategies, null);
 }
Example #19
0
 public static String idFromConfig(SubnodeConfiguration serverConfig) {
   String loginUrl = serverConfig.getString("/loginUrl", null);
   String user = serverConfig.getString("/user", null);
   return user + "@" + loginUrl;
 }
Example #20
0
 private TimeWhenRunnable processVillages() throws InvalidConfigurationException {
   TimeWhenRunnable firstTimeWhenRunnable = null;
   try {
     List<SubnodeConfiguration> villageConfigs =
         config.configurationsAt("/village[@enabled='true']");
     for (SubnodeConfiguration villageConfig : villageConfigs) {
       // If configuration changed, abort current loop, update config and restart
       if (isConfigurationChanged()) {
         log.debug("Exiting village loop for configuration update");
         break;
       }
       String id = Village.getIdFromConfig(villageConfig);
       Village village = villages.get(id);
       if (village == null) {
         log.warn(
             "Configuration file not aligned to village map; ignoring village "
                 + villageConfig.getString("/@desc", "")
                 + " "
                 + villageConfig.getString("/url", ""));
         continue;
       }
       try {
         // getTimeWhenRunnable may update to check for triggering resources so can change page
         TimeWhenRunnable currentTimeWhenRunnable = village.getTimeWhenRunnable();
         // log.debug("currentTimeWhenRunnnable:"+currentTimeWhenRunnable);
         if (currentTimeWhenRunnable.before(new Date())) {
           EventLog.log("Processing village \"" + village.getDesc() + "\"");
           village.execute(); // Execute strategies
           currentTimeWhenRunnable = village.getTimeWhenRunnable();
           // log.debug("currentTimeWhenRunnnable after execute:"+currentTimeWhenRunnable);
         } else {
           EventLog.log(
               "Village \"" + village.getDesc() + "\" sleeping until " + currentTimeWhenRunnable);
         }
         // use current here and only reread after execute, then use new below
         if ((firstTimeWhenRunnable == null)
             || firstTimeWhenRunnable.after(currentTimeWhenRunnable)) {
           log.trace("Earlier Village " + village.getDesc() + " " + currentTimeWhenRunnable);
           firstTimeWhenRunnable = currentTimeWhenRunnable;
         }
         // check for earliest sharp strategy in village, return NEVER if none- if is store
         // earliest sharp one
         TimeWhenRunnable newTimeWhenRunnable = village.getTimeWhenSharp();
         if (newTimeWhenRunnable.isSharp()) {
           if (sharpTimeWhenRunnable == null || sharpTimeWhenRunnable.after(newTimeWhenRunnable)) {
             // log.trace("Earlier Village "+village.getDesc()+" "+newTimeWhenRunnable);
             sharpTimeWhenRunnable = newTimeWhenRunnable;
             log.trace(
                 "Earlier sharp Village is " + village.getDesc() + " " + sharpTimeWhenRunnable);
           }
         }
       } catch (SkipVillageRequested e) {
         log.debug("Village skipped");
         continue;
       } catch (SkipRequested e) {
         // Just keep going
         log.debug("Action skipped");
       } catch (ServerFatalException e) {
         throw e; // Will catch below
       } catch (Exception e) {
         String s = "Village \"" + village.getDesc() + "\" error (retrying later): ";
         log.error(s, e);
         EventLog.log(s + e.getMessage());
         util.shortestPause(false); // Just to be safe
         firstTimeWhenRunnable = null; // Retry after userPause
       }
     }
   } catch (ConcurrentModificationException e) {
     // This shouldn't happen anymore
     // Just ignore
     log.debug(
         "Village list was modified while server running (ConcurrentModificationException): skipping and repeating");
   }
   // log.debug("returning firstTimeWhenRunnable:"+firstTimeWhenRunnable);
   return firstTimeWhenRunnable;
 }
  public TimeWhenRunnable execute() throws ConversationException {
    // <strategy class="Farmizzator" desc="DESCRIPTION" enabled="true">
    //   <target x="XCOORD" y="YCOORD" village="TARGET_VILLAGE" movement="REINFORCE|RAID|ATTACK"
    // spy="RESOURCES|DEFENSES" rate="RATE" item="CATA_TARGET1, CATA_TARGET2"/>
    //   <troops type="TROOP_NAME" allowLess="ALLOWLESS" min="MINIMUM_TROOPS" randomise="RANDOMISE"
    // enabled="true">TROOP_AMOUNT</troops>
    //   <minPauseMinutes>MIN_PAUSE</minPauseMinutes>
    // </strategy>
    log.info("Executing strategy " + super.getDesc());
    NDC.push(super.getDesc());

    // TODO Per le volte successive:
    // TODO Controlla il report dell'attacco (difficile!)
    // TODO Se sono state perse troppe truppe, cancella questa strategy

    try {
      // EventLog.log("checking reports for 92,-95 d=396988&c=50 = " +
      // util.getMapIdFromPosition("92","-95"));
      // ReportMessageReader.getInstance().getAverageBounty(util.getMapIdFromPosition("92","-95"));
      // EventLog.log("Bounty
      // "+ReportMessageReader.getInstance().getLastBounty(util.getServerId(),util.getMapIdFromPosition("92","-95")));
      // EventLog.log("Average Bounty "+ReportMessageReader.getInstance().getAverageBounty(util,
      // "92","-95"));
      // EventLog.log("Last Bounty
      // "+ReportMessageReader.getInstance().getLastBounty(util.getServerId(),util.getMapIdFromPosition("92","-95")));
      // System.exit(0);

      RallyPoint rallyPoint = village.getRallyPoint();
      if (rallyPoint == null) {
        log.debug("No rally point");
        int minPauseMinutes = super.config.getInt("/minPauseMinutes", 25);
        minPauseMinutes =
            super.config.getInt(
                "/@minPauseMinutes", minPauseMinutes); // support on strategy line as well
        return new TimeWhenRunnable(
            System.currentTimeMillis() + minPauseMinutes * Util.MILLI_MINUTE); // Try again later
      }
      TroopTypeMap availablePerType = rallyPoint.fetchSendableTroops(super.util, false);
      TroopTypeMap toSend = new TroopTypeMap();
      boolean sendable = true;
      int totTroops = 0;

      List<SubnodeConfiguration> troopsNodes = super.config.configurationsAt("/troops");
      for (SubnodeConfiguration troopsNode : troopsNodes) {
        boolean enabled = troopsNode.getBoolean("/@enabled", true); // Enabled by default
        if (!enabled) {
          continue;
        }
        String type = troopsNode.getString("/@type", null);
        if (type == null) {
          log.error("Missing \"type\" attribute in strategy \"" + super.getDesc() + "\"");
          continue;
        }
        String fullkey = util.getTranslator().getKeyword(type); // romans.troop1
        String typeKey = fullkey.substring(fullkey.indexOf(".") + 1);
        TroopType troopType = TroopType.fromString(typeKey);
        int val = troopsNode.getInt("/", 0);
        boolean allowLess = troopsNode.getBoolean("/@allowLess", false);
        Integer available = availablePerType.get(troopType);
        // Check if we have enough troops
        if (val > available && !allowLess) {
          sendable = false;
          break;
        }
        // Check if we can send at least min troops
        String minimum = troopsNode.getString("/@min", "0");
        int min = 0;
        boolean percent = false;
        if (minimum.endsWith("%")) {
          percent = true;
          minimum = minimum.replace("%", "");
        }
        try {
          min = Integer.parseInt(minimum);
        } catch (NumberFormatException e) {
          throw new FatalException(
              String.format("Invalid numeric value for %s: \"%s\"", type, minimum));
        }
        if (percent) {
          min = (val * min) / 100;
        }
        if (available < min) {
          sendable = false;
          break;
        }
        // Randomise
        // Accept both "randomise" and "randomize", with "true" as default
        boolean randomise =
            troopsNode.getBoolean("/@randomise", troopsNode.getBoolean("/@randomize", true));
        if (randomise) {
          int maxDelta = (int) (val * RANDOMISE_RATIO);
          if (!allowLess) {
            // value can't be less than what specified
            val = val + random.nextInt(maxDelta + 1);
          } else {
            // value can be +- randVal
            val = val - maxDelta + random.nextInt(2 * maxDelta + 1);
          }
        }
        // Add troops to send
        val = val > available ? available : val; // Upper limit
        val = val < min ? min : val; // Lower limit
        toSend.put(troopType, val);
        totTroops += val;
      }
      int minPauseMinutes = super.config.getInt("/minPauseMinutes", 5);
      minPauseMinutes =
          super.config.getInt(
              "/@minPauseMinutes", minPauseMinutes); // support on strategy line as well
      if (sendable == false || totTroops == 0) {
        EventLog.log("Not enough troops");
        return new TimeWhenRunnable(
            System.currentTimeMillis() + minPauseMinutes * Util.MILLI_MINUTE); // Try again later
      }
      Coordinates coord = new Coordinates(config, "target"); // Handles "travian style" coords
      String x = coord.getX();
      String y = coord.getY();
      String village = super.config.getString("/target/@village", "");
      String movement = super.config.getString("/target/@movement", "attack");
      String fullkey = "movement." + translator.getKeyword(movement, "movement"); // movement.attack
      TroopTransferType transferType = TroopTransferType.fromKey(fullkey);
      String itemString1 = super.config.getString("/target/@item[1]", null);
      String itemString2 = super.config.getString("/target/@item[2]", null);
      TroopTransferType spyType = null;
      String spyTypeString = super.config.getString("/target/@spy", null);
      if (spyTypeString != null) {
        fullkey =
            "movement."
                + translator.getKeyword(spyTypeString, "movement"); // movement.spy.resources
        spyType = TroopTransferType.fromKey(fullkey);
      } // check for previous bounty if not spying
      else if ((!x.equals("")) && (!y.equals(""))) {
        // log.debug("checking reports for " + x + "," + y + " id " +
        // util.getMapIdFromPosition(x,y));
        // ReportMessageReader.getInstance().getAverageBounty(util.getServerId(),util.getMapIdFromPosition(x,y));
        // log.debug("Average Bounty " + ReportMessageReader.getInstance().getAverageBounty(util, x,
        // y));
        Valley v = new Valley(util, x, y);
        log.debug("Average Bounty " + v.getAverageBounty());
        // EventLog.log("Last Bounty
        // "+ReportMessageReader.getInstance().getLastBounty(util.getServerId(),util.getMapIdFromPosition( x, y)));
      }

      super.village
          .gotoMainPage(); // Ensure you do it from the right village (someone might have clicked to
      // a different village meanwhile)
      int secondsToArrive;
      try {
        secondsToArrive =
            rallyPoint.sendTroops(
                util,
                x,
                y,
                village,
                toSend,
                transferType,
                new String[] {itemString1, itemString2},
                spyType);
        totErrors = 0;
      } catch (ConversationException e) {
        log.error(e);
        totErrors++;
        if (totErrors <= MAX_ERRORS) {
          EventLog.log(
              String.format(
                  "Strategy has error; retrying later (%s left)", MAX_ERRORS - totErrors));
          util.shortestPause(false); // Just to be safe
          return new TimeWhenRunnable(
              System.currentTimeMillis() + minPauseMinutes * Util.MILLI_MINUTE); // Try again later
        } else {
          log.error("Strategy has too many errors; disabling", e);
          EventLog.log("Strategy has too many errors; disabling");
          return TimeWhenRunnable.NEVER;
        }
      }
      if (secondsToArrive > 0) {
        log.info(String.format("Strategy %s done for now", getDesc()));
        double rate = Math.max(super.config.getDouble("/target/@rate", 1), Double.MIN_VALUE);
        double raidTime = (2 * secondsToArrive * Util.MILLI_SECOND);
        long waitMillis = (long) (raidTime / rate);
        long timeTemp = waitMillis / 60000;
        EventLog.log(
            String.format(
                "Strategy %s done for now: Next run in %s minutes at rate %s",
                getDesc(), Long.toString(timeTemp), Double.toString(rate)));
        long MyTimeToRun = System.currentTimeMillis() + waitMillis;
        return new TimeWhenRunnable(MyTimeToRun);
      } else {
        log.error("Error in Farmizzator");
        EventLog.log(String.format("Strategy %s disabled on error", getDesc()));
        return new TimeWhenRunnable(false);
      }
    } finally {
      NDC.pop();
    }
  }
Example #22
0
 public String getAMPQControlPassword() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("ampq_control_password");
 }
Example #23
0
 public String getPluginConfigFile() {
   SubnodeConfiguration sObj = iniConfObj.getSection("general");
   return sObj.getString("plugin_config_file");
 }