/**
   * Check whether provided path must be excluded from evictions.
   *
   * @param path Path.
   * @return {@code True} in case non block of related file must be excluded.
   * @throws GridException In case of faulty patterns.
   */
  public boolean exclude(GridGgfsPath path) throws GridException {
    assert path != null;

    Collection<Pattern> excludePatterns0;

    if (excludeRecompile.compareAndSet(true, false)) {
      // Recompile.
      Collection<String> excludePaths0 = excludePaths;

      if (excludePaths0 != null) {
        excludePatterns0 = new HashSet<>(excludePaths0.size(), 1.0f);

        for (String excludePath : excludePaths0) {
          try {
            excludePatterns0.add(Pattern.compile(excludePath));
          } catch (PatternSyntaxException ignore) {
            throw new GridException("Invalid regex pattern: " + excludePath);
          }
        }

        excludePatterns = excludePatterns0;
      } else excludePatterns0 = excludePatterns = null;
    } else excludePatterns0 = excludePatterns;

    if (excludePatterns0 != null) {
      String pathStr = path.toString();

      for (Pattern pattern : excludePatterns0) {
        if (pattern.matcher(pathStr).matches()) return true;
      }
    }

    return false;
  }
  private static final class MessageFormatter {
    private static final Pattern variablePattern =
        Pattern.compile("(?i)\\$(\\{[a-z0-9_]{1,}\\}|[a-z0-9_]{1,})");
    private static final Pattern colorPattern = Pattern.compile("(?i)&[0-9A-FK-OR]");

    private final Map<String, String> variables;

    public MessageFormatter() {
      variables = new HashMap<String, String>();
    }

    public synchronized void setVariable(String variable, String value) {
      if (value == null) variables.remove(value);
      else variables.put(variable, value);
    }

    public synchronized String format(String message) {
      Matcher matcher = variablePattern.matcher(message);
      while (matcher.find()) {
        String variable = matcher.group();
        variable = variable.substring(1);
        if (variable.startsWith("{") && variable.endsWith("}"))
          variable = variable.substring(1, variable.length() - 1);
        String value = variables.get(variable);
        if (value == null) value = "";
        message =
            message.replaceFirst(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value));
      }
      matcher = colorPattern.matcher(message);
      while (matcher.find())
        message =
            message.substring(0, matcher.start()) + "\247" + message.substring(matcher.end() - 1);
      return message;
    }
  }
 public synchronized String format(String message) {
   Matcher matcher = variablePattern.matcher(message);
   while (matcher.find()) {
     String variable = matcher.group();
     variable = variable.substring(1);
     if (variable.startsWith("{") && variable.endsWith("}"))
       variable = variable.substring(1, variable.length() - 1);
     String value = variables.get(variable);
     if (value == null) value = "";
     message =
         message.replaceFirst(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value));
   }
   matcher = colorPattern.matcher(message);
   while (matcher.find())
     message =
         message.substring(0, matcher.start()) + "\247" + message.substring(matcher.end() - 1);
   return message;
 }
 private static List<String> loadAccounts(String fileName) {
   List<String> accounts = new ArrayList<String>();
   try {
     Pattern pattern = Pattern.compile("[\\w]{1,16}");
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) {
       Matcher matcher = pattern.matcher(line);
       if (!matcher.find()) continue;
       String username = matcher.group();
       if (!matcher.find()) continue;
       String password = matcher.group();
       accounts.add(username + ":" + password);
     }
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
   System.out.println("Loaded " + accounts.size() + " accounts.");
   return accounts;
 }
 @Override
 @EventHandler
 public void onChatReceived(ChatReceivedEvent event) {
   super.onChatReceived(event);
   String message = Util.stripColors(event.getMessage());
   if (message.startsWith("Please register with \"/register")) {
     String password = Util.generateRandomString(10 + random.nextInt(6));
     bot.say("/register " + password + " " + password);
   } else if (message.contains("You are not member of any faction.")
       && spamMessage != null
       && createFaction) {
     String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4));
     bot.say(msg);
   }
   for (String s : captchaList) {
     Matcher captchaMatcher = Pattern.compile(s).matcher(message);
     if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1));
   }
 }
  protected static ReplyType parseResponseHTML(String responseHTML) {
    ReplyType res = ReplyType.UNKNOWN_RESPONSE;
    String strres = null;

    Matcher matcher = resultParserPattern.matcher(responseHTML);

    if (matcher.find()) {
      strres = matcher.group(1);
    }

    if (strres != null) {
      for (ReplyType rt : ReplyType.values()) {
        if (strres.equalsIgnoreCase(rt.nativeReply)) {
          res = rt;
          break;
        }
      }
    }

    return res;
  }
 @EventHandler
 public void onPacketProcess(PacketProcessEvent event) {
   // System.out.println("Packet received: " + event.getPacket().getId()
   // + " (" + event.getPacket() + ")");
   Packet packet = event.getPacket();
   switch (packet.getId()) {
     case 0:
       connectionHandler.sendPacket(new Packet0KeepAlive(new Random().nextInt()));
       break;
     case 3:
       String message = ((Packet3Chat) packet).message;
       message = removeColors(message);
       System.out.println("[" + bot.getSession().getUsername() + "] " + message);
       String testMessage = "[MineCaptcha] To be unmuted answer this question: What is ";
       String testMessage2 = "Please type '";
       String testMessage3 = "' to continue sending messages/commands";
       if (message.contains(testMessage)) {
         try {
           String captcha = message.split(Pattern.quote(testMessage))[1].split("[ \\?]")[0];
           ScriptEngineManager mgr = new ScriptEngineManager();
           ScriptEngine engine = mgr.getEngineByName("JavaScript");
           String solved = engine.eval(captcha).toString();
           solved = solved.split("\\.")[0];
           connectionHandler.sendPacket(new Packet3Chat(solved));
         } catch (Exception exception) {
           exception.printStackTrace();
         }
       } else if (message.contains(testMessage2) && message.contains(testMessage3)) {
         try {
           String captcha =
               message.split(Pattern.quote(testMessage2))[1].split(Pattern.quote(testMessage3))[0];
           connectionHandler.sendPacket(new Packet3Chat(captcha));
         } catch (Exception exception) {
           exception.printStackTrace();
         }
       } else if (message.startsWith("Please register with \"/register")) {
         String password = "";
         for (int i = 0; i < 10 + random.nextInt(6); i++)
           password += alphas[random.nextInt(alphas.length)];
         bot.say("/register " + password + " " + password);
       } else if (message.startsWith("/uc ")) {
         connectionHandler.sendPacket(new Packet3Chat(message));
       } else if ((message.contains("do the crime") && message.contains("do the time"))
           || message.contains("You have been muted")) {
         connectionHandler.sendPacket(new Packet3Chat("\247Leaving!"));
       } else if (message.contains(owner + " has requested to teleport to you.")) {
         connectionHandler.sendPacket(new Packet3Chat("/tpaccept"));
       } else if (message.contains(owner)) {
         if (message.contains("Go ")) {
           spamMessage = message.substring(message.indexOf("Go ") + "Go ".length());
         } else if (message.contains("Stop")) {
           spamMessage = null;
           bot.getTaskManager().stopAll();
         } else if (message.contains("Die")) {
           die = true;
         } else if (message.contains("Say ")) {
           connectionHandler.sendPacket(
               new Packet3Chat(message.substring(message.indexOf("Say ") + "Say ".length())));
         } else if (message.contains("Leave")) {
           connectionHandler.sendPacket(new Packet255KickDisconnect("Quit"));
         } else if (message.contains("Tool")) {
           MainPlayerEntity player = bot.getPlayer();
           if (player == null) return;
           PlayerInventory inventory = player.getInventory();
           inventory.setCurrentHeldSlot(
               Integer.parseInt(
                   message.substring(message.indexOf("Tool ") + "Tool ".length()).split(" ")[0]));
         } else if (message.contains("DropId ")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           String substring =
               message.substring(message.indexOf("DropId ") + "DropId ".length()).split(" ")[0];
           int id = Integer.parseInt(substring);
           for (int slot = 0; slot < 40; slot++) {
             ItemStack item = inventory.getItemAt(slot);
             if (item != null && item.getId() == id) {
               inventory.selectItemAt(slot, true);
               inventory.dropSelectedItem();
             }
           }
           inventory.close();
         } else if (message.contains("Drop")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           if (message.contains("Drop ")) {
             String substring =
                 message.substring(message.indexOf("Drop ") + "Drop ".length()).split(" ")[0];
             try {
               int slot = Integer.parseInt(substring);
               if (slot < 0 || slot >= 40) return;
               if (inventory.getItemAt(slot) != null) {
                 inventory.selectItemAt(slot, true);
                 inventory.dropSelectedItem();
               }
               return;
             } catch (NumberFormatException e) {
             }
           }
           for (int slot = 0; slot < 40; slot++) {
             if (inventory.getItemAt(slot) != null) {
               inventory.selectItemAt(slot, true);
               inventory.dropSelectedItem();
             }
           }
           inventory.close();
         } else if (message.contains("Switch ")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           String substring = message.substring(message.indexOf("Switch ") + "Switch ".length());
           try {
             int slot1 = Integer.parseInt(substring.split(" ")[0]);
             int slot2 = Integer.parseInt(substring.split(" ")[1]);
             if (slot1 < 0 || slot1 >= 45 || slot2 < 0 || slot2 >= 45) return;
             inventory.selectItemAt(slot1);
             inventory.selectItemAt(slot2);
             inventory.selectItemAt(slot1);
           } catch (NumberFormatException e) {
           }
           // inventory.close();
         } else if (message.contains("Equip")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           boolean helmet = inventory.getArmorAt(0) != null;
           boolean chestplate = inventory.getArmorAt(1) != null;
           boolean leggings = inventory.getArmorAt(2) != null;
           boolean boots = inventory.getArmorAt(3) != null;
           boolean changed = false;
           for (int i = 0; i < 36; i++) {
             ItemStack item = inventory.getItemAt(i);
             if (item == null) continue;
             int armorSlot;
             int id = item.getId();
             if (!helmet
                 && (id == 86 || id == 298 || id == 302 || id == 306 || id == 310 || id == 314)) {
               armorSlot = 0;
               helmet = true;
             } else if (!chestplate
                 && (id == 299 || id == 303 || id == 307 || id == 311 || id == 315)) {
               armorSlot = 1;
               chestplate = true;
             } else if (!leggings
                 && (id == 300 || id == 304 || id == 308 || id == 312 || id == 316)) {
               armorSlot = 2;
               leggings = true;
             } else if (!boots
                 && (id == 301 || id == 305 || id == 309 || id == 313 || id == 317)) {
               armorSlot = 3;
               boots = true;
             } else if (helmet && chestplate && leggings && boots) break;
             else continue;
             inventory.selectItemAt(i);
             inventory.selectArmorAt(armorSlot);
             changed = true;
           }
           if (!changed) {
             for (int i = 0; i < 36; i++) {
               ItemStack item = inventory.getItemAt(i);
               if (item != null) continue;
               int armorSlot;
               if (helmet) {
                 armorSlot = 0;
                 helmet = false;
               } else if (chestplate) {
                 armorSlot = 1;
                 chestplate = false;
               } else if (leggings) {
                 armorSlot = 2;
                 leggings = false;
               } else if (boots) {
                 armorSlot = 3;
                 boots = false;
               } else if (!helmet && !chestplate && !leggings && !boots) break;
               else continue;
               inventory.selectArmorAt(armorSlot);
               inventory.selectItemAt(i);
             }
           }
           inventory.close();
           bot.say("Equipped armor.");
         } else if (message.contains("Owner ")) {
           String name =
               message.substring(message.indexOf("Owner ") + "Owner ".length()).split(" ")[0];
           owner = name;
           bot.say("Set owner to " + name);
         }
       } else if (message.contains("You are not member of any faction.")
           && spamMessage != null
           && createFaction) {
         String msg = "/f create ";
         for (int i = 0; i < 7 + random.nextInt(3); i++)
           msg += alphas[random.nextInt(alphas.length)];
         bot.say(msg);
       }
       if (message.matches("[\\*]*SPQR [\\w]{1,16} invited you to SPQR")) {
         bot.say("/f join SPQR");
         bot.say("\247asdf");
       }
       break;
     case 8:
       Packet8UpdateHealth updateHealth = (Packet8UpdateHealth) packet;
       if (updateHealth.healthMP <= 0) connectionHandler.sendPacket(new Packet205ClientCommand(1));
       break;
     case 9:
       TaskManager taskManager = bot.getTaskManager();
       taskManager.stopAll();
       break;
   }
 }
public abstract class AbstractHTTPKeyServerClient extends AbstractRetryingKeyServerClient {

  private static final Pattern resultParserPattern =
      Pattern.compile("Result:\\s*(.*?)\\r?\\n", Pattern.CASE_INSENSITIVE);

  public String createKey(String hostName, KeyServerClient.Usage usage) {
    String res = null;

    if (hostName != null) {
      switch (usage) {
        case SNMP:
          {
            res = hostName + "-" + "adsl";
            break;
          }
        default:
          {
            throw new IllegalArgumentException();
          }
      }
    }
    return res;
  }

  /*
   * Parse the response HTML
   */

  protected static ReplyType parseResponseHTML(String responseHTML) {
    ReplyType res = ReplyType.UNKNOWN_RESPONSE;
    String strres = null;

    Matcher matcher = resultParserPattern.matcher(responseHTML);

    if (matcher.find()) {
      strres = matcher.group(1);
    }

    if (strres != null) {
      for (ReplyType rt : ReplyType.values()) {
        if (strres.equalsIgnoreCase(rt.nativeReply)) {
          res = rt;
          break;
        }
      }
    }

    return res;
  }

  /**
   * Builds the actual string that is POSTed to the KeyServer
   *
   * @param localhostname Local Hostname
   * @param request KeyServer request
   * @param key Key to allocate/deallocate
   * @return String to POST
   */
  protected static String buildRequestString(
      String localhostname, RequestType request, String key) {
    return buildRequestString(localhostname, request.getNativeRequest(), key);
  }

  protected static String buildRequestString(String localhostname, String requesttype, String key) {
    return "remote_address=" + localhostname + "&reqtype=" + requesttype + "&dslam-key=" + key;
  }

  /** Possible replies from the KeyServer */
  protected static enum ReplyType {
    /** Attempt to get/allocate key successful */
    KEY_GRANTED("Key_Granted"),
    /** Attempt to get/allocate key failed - Key allocated elsewhere */
    KEY_BUSY("Key Busy"),
    /** Attempt to return/deallocate key successful */
    KEY_RETURNED("Key_Returned"),
    /** Attempt to get/allocate key failed - Key blocked by other party */
    KEY_BLOCKED("Key_Blocked"),
    /** Attempt to block entire DSLAM successful */
    KEY_BLOCK_OK("KeyServer_BLOCK Ok"),
    /** Attempt to unblock entire DSLAM successful */
    KEY_UNBLOCK_OK("KeyServer UNBLOCK Ok"),
    UNKNOWN_RESPONSE("UNKNOWN_RESPONSE"), // not a direct reply
    KEYSERVER_ERROR("KEYSERVER_ERROR"), // not a direct reply
    KEY_NOT_RETURNED("KEY_NOT_RETURNED"); // not a direct reply

    private String nativeReply;

    ReplyType(String reply) {
      this.nativeReply = reply;
    }

    public String getNativeReply() {
      return this.nativeReply;
    }
  }

  /** Possible KeyServer requests */
  protected static enum RequestType {
    /** Get/Allocate Key Request */
    GET_KEY("get_dslamkey", ReplyType.KEY_GRANTED),
    /** Return/Deallocate Key Request */
    RETURN_KEY("return_dslamkey", ReplyType.KEY_RETURNED);

    private String nativeRequest;
    private ReplyType successReply;

    RequestType(String request, ReplyType success) {
      this.nativeRequest = request;
      this.successReply = success;
    }

    public String getNativeRequest() {
      return this.nativeRequest;
    }

    public ReplyType getSuccessReply() {
      return this.successReply;
    }
  }

  /** KeyServer returned {@link ReplyType} does not match expected {@link ReplyType} */
  protected static class OperationFailedException extends Exception {
    public OperationFailedException(String message) {
      super(message);
    }

    /** */
    private static final long serialVersionUID = -7363443310028754594L;
  }

  public static AtomicLong httpBeginCount = new AtomicLong();
  public static AtomicLong httpEndCount = new AtomicLong();
  public static AtomicLong httpRunningCount = new AtomicLong();
  public static AtomicLong httpRunningCountMax = new AtomicLong();

  public static FrequencyCounter httpBeginFrequencyCounter =
      new CountLimitedFrequencyCounter(8640, 10 * 1000L * 1000L * 1000L); // 8640*(10 sec)=24 hours

  public static FrequencyCounter httpEndFrequencyCounter =
      new CountLimitedFrequencyCounter(8640, 10 * 1000L * 1000L * 1000L); // 8640*(10 sec)=24 hours
}
 private void putPattern(String name, Pattern p) {
   _put(REGEX, name);
   _put(p.pattern());
   _put(regexFlags(p.flags()));
 }