Exemplo n.º 1
1
 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
     throws BadLocationException {
   StringBuilder builder = new StringBuilder(string);
   for (int i = builder.length() - 1; i >= 0; i--) {
     int cp = builder.codePointAt(i);
     if (!Character.isDigit(cp) && cp != '-') {
       builder.deleteCharAt(i);
       if (Character.isSupplementaryCodePoint(cp)) {
         i--;
         builder.deleteCharAt(i);
       }
     }
   }
   super.insertString(fb, offset, builder.toString(), attr);
 }
Exemplo n.º 2
1
Arquivo: Macro.java Projeto: bramk/bnd
  int process(CharSequence org, int index, char begin, char end, StringBuilder result, Link link) {
    StringBuilder line = new StringBuilder(org);
    int nesting = 1;

    StringBuilder variable = new StringBuilder();
    outer:
    while (index < line.length()) {
      char c1 = line.charAt(index++);
      if (c1 == end) {
        if (--nesting == 0) {
          result.append(replace(variable.toString(), link));
          return index;
        }
      } else if (c1 == begin) nesting++;
      else if (c1 == '\\' && index < line.length() - 1 && line.charAt(index) == '$') {
        // remove the escape backslash and interpret the dollar
        // as a
        // literal
        index++;
        variable.append('$');
        continue outer;
      } else if (c1 == '$' && index < line.length() - 2) {
        char c2 = line.charAt(index);
        char terminator = getTerminator(c2);
        if (terminator != 0) {
          index = process(line, index + 1, c2, terminator, variable, link);
          continue outer;
        }
      } else if (c1 == '.' && index < line.length() && line.charAt(index) == '/') {
        // Found the sequence ./
        if (index == 1 || Character.isWhitespace(line.charAt(index - 2))) {
          // make sure it is preceded by whitespace or starts at begin
          index++;
          variable.append(domain.getBase().getAbsolutePath());
          variable.append('/');
          continue outer;
        }
      }
      variable.append(c1);
    }
    result.append(variable);
    return index;
  }
Exemplo n.º 3
0
  /**
   * Gets the information about an element's handlers in the current router configuration.
   *
   * @param el The element name.
   * @return Vector of HandlerInfo structures.
   * @exception NoSuchElementException If there is no such element in the current configuration.
   * @exception HandlerErrorException If the handler returned an error.
   * @exception PermissionDeniedException If the router would not let us access the handler.
   * @exception IOException If there was some other error accessing the handler (e.g., there was a
   *     stream or socket error, the ControlSocket returned an unknwon unknown error code, or the
   *     response could otherwise not be understood).
   * @see #HandlerInfo
   * @see #getConfigElementNames
   * @see #getRouterConfig
   * @see #getRouterFlatConfig
   */
  public Vector getElementHandlers(String elementName) throws ClickException, IOException {
    Vector v = new Vector();
    Vector vh;

    try {
      char[] buf = read(elementName, "handlers");
      vh = StringUtils.split(buf, 0, '\n');
    } catch (ClickException.NoSuchHandlerException e) {
      return v;
    }

    for (int i = 0; i < vh.size(); i++) {
      String s = (String) vh.elementAt(i);
      int j;
      for (j = 0; j < s.length() && !Character.isWhitespace(s.charAt(j)); j++)
        ; // find record split
      if (j == s.length())
        throw new ClickException.HandlerFormatException(elementName + ".handlers");
      HandlerInfo hi = new HandlerInfo(elementName, s.substring(0, j).trim());
      while (j < s.length() && Character.isWhitespace(s.charAt(j))) j++;
      for (; j < s.length(); j++) {
        char c = s.charAt(j);
        if (Character.toLowerCase(c) == 'r') hi.canRead = true;
        else if (Character.toLowerCase(c) == 'w') hi.canWrite = true;
        else if (Character.isWhitespace(c)) break;
      }
      v.addElement(hi);
    }
    return v;
  }
Exemplo n.º 4
0
  private boolean checkHandlerWorkaround(
      String elementName, String handlerName, boolean writeHandler)
      throws ClickException, IOException {
    // If talking to an old ControlSocket, try the "handlers" handler
    // instead.
    String s = readString(elementName, "handlers");
    int pos = 0;

    // Find handler with same name.
    while (true) {
      pos = s.indexOf(handlerName, pos);
      if (pos < 0) // no such handler
      return false;
      if ((pos == 0 || s.charAt(pos - 1) == '\n')
          && Character.isWhitespace(s.charAt(pos + handlerName.length()))) break;
      pos++;
    }

    // we have a matching handler: will it be read/write suitable?
    char wantType = (writeHandler ? 'w' : 'r');
    for (pos += handlerName.length();
        pos < s.length() && Character.isWhitespace(s.charAt(pos));
        pos++) /* nada */ ;
    for (; pos < s.length(); pos++) {
      char c = s.charAt(pos);
      if (Character.toLowerCase(c) == wantType) return true;
      else if (Character.isWhitespace(c)) break;
    }
    return false;
  }
Exemplo n.º 5
0
 public static boolean isFormat(String str, String... format) {
   if (str.length() == 0) return format.length == 1 && format[0].equals("");
   char[] charset = str.toCharArray();
   int c = 0;
   for (int i = 0; i < format.length; i++) {
     String form = format[i];
     if (form.equals(NUMBERS)) {
       if (c >= charset.length) return false;
       if (!Character.isDigit(charset[c])) {
         if (charset[c] == '.') {
           if (c + 1 >= charset.length || !Character.isDigit(charset[c + 1])) return false;
         } else return false;
       }
       while (c < charset.length - 1
           && (Character.isDigit(charset[c + 1]) || charset[c + 1] == '.')) c++;
       c++;
     } else if (form.equals(LETTERS)) {
       if (c >= charset.length || !Character.isLetter(charset[c])) return false;
       while (c < charset.length - 1 && Character.isLetter(charset[c + 1])) c++;
       c++;
     } else {
       char[] formchars = form.toCharArray();
       if (formchars.length > charset.length - c) return false;
       for (int ch = 0; ch < formchars.length; ch++) {
         if (formchars[ch] != charset[c]) return false;
         c++;
       }
     }
   }
   return c == charset.length;
 }
Exemplo n.º 6
0
 /**
  * Helper routine to get the scheme part of a URI. The scheme part is "http:" or "file:" or "ftp:"
  * most commonly. This functions searches for the first ':' that doesn't follow a '/'.
  *
  * @return The length of the scheme component, not counting the colon, (or alternatively the index
  *     of the colon), or -1 if the is no scheme.
  */
 public static int uriSchemeLength(String uri) {
   int len = uri.length();
   for (int i = 0; i < len; i++) {
     char ch = uri.charAt(i);
     if (ch == ':') return i;
     if (i == 0
         ? !Character.isLetter(ch)
         : (!Character.isLetterOrDigit(ch) && ch != '+' && ch != '-' && ch != '.')) return -1;
   }
   return -1;
 }
Exemplo n.º 7
0
 /**
  * Modtager værtens svar, der godt kan løbe over flere linjer. Sidste linje er en svarkode på tre
  * cifre, uden en bindestreg '-' på plads nummer 4
  */
 private String læsSvar() throws IOException {
   while (true) {
     String s = ind.readLine();
     System.out.println("modt: " + s);
     if (s.length() >= 3
         && s.charAt(3) != '-'
         && Character.isDigit(s.charAt(0))
         && Character.isDigit(s.charAt(1))
         && Character.isDigit(s.charAt(2)))
       return s; // afslut løkken og returner sidste linje med statuskode
   }
 }
Exemplo n.º 8
0
  private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
Exemplo n.º 9
0
 public static String getDigits(String s) {
   String str = "";
   for (int i = 0; i < s.length(); i++) {
     if (Character.isDigit(s.charAt(i))) str += s.charAt(i);
   }
   return str;
 }
Exemplo n.º 10
0
 /**
  * ** Returns true if the specified character should be hex-encoded in a URL ** @param ch The
  * character to test ** @return True if the specified character should be hex-encoded in a URL
  */
 private static boolean shouldEncodeArgChar(char ch) {
   if (Character.isLetterOrDigit(ch)) {
     return false;
   } else if ((ch == '_') || (ch == '-') || (ch == '.')) {
     return false;
   } else {
     return true;
   }
 }
 /**
  * Gets the next token from a tokenizer and converts it to a long.
  *
  * @return The next token in the stream, as a long.
  * @throws TextParseException The input was invalid or not a long.
  * @throws IOException An I/O error occurred.
  */
 public long getLong() throws IOException {
   String next = _getIdentifier("an integer");
   if (!Character.isDigit(next.charAt(0))) throw exception("expected an integer");
   try {
     return Long.parseLong(next);
   } catch (NumberFormatException e) {
     throw exception("expected an integer");
   }
 }
Exemplo n.º 12
0
 /**
  * Codage d'une chaine pour servir en tant que nom de fichier. Remplace tous ce qui n'est ni
  * lettre ni chiffre en code hexa préfixé par _
  */
 private static String codage(String s) {
   StringBuffer r = new StringBuffer();
   char a[] = s.toCharArray();
   for (int i = 0; i < a.length; i++) {
     char c = a[i];
     if (!Character.isLetterOrDigit(c)) r.append(PREFIX + Util.hex(c));
     else r.append(c);
   }
   return r.toString();
 }
Exemplo n.º 13
0
    public void checkLineOfAction(
        ArrayList<Cam> cameras, ArrayList<Character> characters, int selectedIdx) {
      if (cameras == null || cameras.isEmpty()) {
        println("No cameras in the scene!");
      }

      if (characters.size() != 2) {
        println("Only two characters supported for now");
        // TODO (sanjeet): Hack! Fix this once more characters are allowed
      }

      Cam selectedCamera = cameras.get(selectedIdx);

      // TODO The characters.get results in a runtime error because there aren't currently any
      // characters allocated in the input file.
      Character ch1 = characters.get(0);
      Character ch2 = characters.get(1);

      // Obtaining (x,y,z) for characters and selected camera
      PVector ch1Location = ch1.getTranslation();
      PVector ch2Location = ch2.getTranslation();

      line(
          ch1Location.x, ch1Location.y, ch1Location.z, ch2Location.x, ch2Location.y, ch2Location.z);

      PVector selectedCameraLocation = selectedCamera.getTranslation();

      // Iterate through other cameras in the scene and check for line of action rule
      for (int i = 0; i < cameras.size(); i++) {
        if (i == selectedIdx) {
          continue;
        }
        PVector currCamLocation = cameras.get(i).getTranslation();
        if (!isInSameHalfPlane(selectedCameraLocation, currCamLocation, ch1Location, ch2Location)) {
          // If the Selected Camera and current camera are not in the same half plane its a
          // violation
          cameras.get(i).setColor(255, 0, 0);
        } else {
          cameras.get(i).setColor(0, 0, 255);
        }
      }
    }
Exemplo n.º 14
0
 private int getDataLength(String s) {
   int i;
   for (i = 0; i < s.length() && !Character.isDigit(s.charAt(i)); i++) ; // do it
   if (i == s.length()) return -1;
   String len_str = s.substring(i);
   try {
     return Integer.parseInt(len_str);
   } catch (NumberFormatException ex) {
     return -1;
   }
 }
Exemplo n.º 15
0
  // get signs using an additional arg for a target rel
  private Collection<Sign> getSignsFromPredAndTargetRel(String pred, String targetRel) {

    Collection<Word> words = (Collection<Word>) _predToWords.get(pred);
    String specialTokenConst = null;

    // for robustness, when using supertagger, add words for pred sans sense index
    int dotIndex = -1;
    if (_supertagger != null
        && !Character.isDigit(pred.charAt(0))
        && // skip numbers
        (dotIndex = pred.lastIndexOf('.')) > 0
        && pred.length() > dotIndex + 1
        && pred.charAt(dotIndex + 1) != '_') // skip titles, eg Mr._Smith
    {
      String barePred = pred.substring(0, dotIndex);
      Collection<Word> barePredWords = (Collection<Word>) _predToWords.get(barePred);
      if (words == null) words = barePredWords;
      else if (barePredWords != null) {
        Set<Word> unionWords = new HashSet<Word>(words);
        unionWords.addAll(barePredWords);
        words = unionWords;
      }
    }

    if (words == null) {
      specialTokenConst = tokenizer.getSpecialTokenConstant(tokenizer.isSpecialToken(pred));
      if (specialTokenConst == null) return null;
      // lookup words with pred = special token const
      Collection<Word> specialTokenWords = (Collection<Word>) _predToWords.get(specialTokenConst);
      // replace special token const with pred
      if (specialTokenWords == null) return null;
      words = new ArrayList<Word>(specialTokenWords.size());
      for (Iterator<Word> it = specialTokenWords.iterator(); it.hasNext(); ) {
        Word stw = it.next();
        Word w = Word.createSurfaceWord(stw, pred);
        words.add(w);
      }
    }

    List<Sign> retval = new ArrayList<Sign>();
    for (Iterator<Word> it = words.iterator(); it.hasNext(); ) {
      Word w = it.next();
      try {
        SignHash signs = getSignsFromWord(w, specialTokenConst, pred, targetRel);
        retval.addAll(signs.asSignSet());
      }
      // shouldn't happen
      catch (LexException exc) {
        System.err.println("Unexpected lex exception for word " + w + ": " + exc);
      }
    }
    return retval;
  }
Exemplo n.º 16
0
Arquivo: Macro.java Projeto: bramk/bnd
  String version(Version version, String mask) {
    if (version == null) {
      String v = domain.getProperty("@");
      if (v == null) {
        domain.error(
            "No version specified for ${version} or ${range} and no implicit version ${@} either, mask=%s",
            mask);
        v = "0";
      }
      version = new Version(v);
    }

    StringBuilder sb = new StringBuilder();
    String del = "";

    for (int i = 0; i < mask.length(); i++) {
      char c = mask.charAt(i);
      String result = null;
      if (c != '~') {
        if (i == 3) {
          result = version.getQualifier();
        } else if (Character.isDigit(c)) {
          // Handle masks like +00, =+0
          result = String.valueOf(c);
        } else {
          int x = version.get(i);
          switch (c) {
            case '+':
              x++;
              break;
            case '-':
              x--;
              break;
            case '=':
              break;
          }
          result = Integer.toString(x);
        }
        if (result != null) {
          sb.append(del);
          del = ".";
          sb.append(result);
        }
      }
    }
    return sb.toString();
  }
  /**
   * This method gets called when a property we're interested in is about to change. In case we
   * don't like the new value we throw a PropertyVetoException to prevent the actual change from
   * happening.
   *
   * @param evt a <tt>PropertyChangeEvent</tt> object describing the event source and the property
   *     that will change.
   * @exception PropertyVetoException if we don't want the change to happen.
   */
  public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
    if (evt.getPropertyName().equals(PROP_STUN_SERVER_ADDRESS)) {
      // make sure that we have a valid fqdn or ip address.

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String host = evt.getNewValue().toString();
      if (host.trim().length() == 0) return;

      boolean ipv6Expected = false;
      if (host.charAt(0) == '[') {
        // This is supposed to be an IPv6 litteral
        if (host.length() > 2 && host.charAt(host.length() - 1) == ']') {
          host = host.substring(1, host.length() - 1);
          ipv6Expected = true;
        } else {
          // This was supposed to be a IPv6 address, but it's not!
          throw new PropertyVetoException("Invalid address string" + host, evt);
        }
      }

      for (int i = 0; i < host.length(); i++) {
        char c = host.charAt(i);
        if (Character.isLetterOrDigit(c)) continue;

        if ((c != '.' && c != ':') || (c == '.' && ipv6Expected) || (c == ':' && !ipv6Expected))
          throw new PropertyVetoException(host + " is not a valid address nor host name", evt);
      }

    } // is prop_stun_server_address
    else if (evt.getPropertyName().equals(PROP_STUN_SERVER_PORT)) {

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String port = evt.getNewValue().toString();
      if (port.trim().length() == 0) return;

      try {
        Integer.valueOf(evt.getNewValue().toString());
      } catch (NumberFormatException ex) {
        throw new PropertyVetoException(port + " is not a valid port! " + ex.getMessage(), evt);
      }
    }
  }
Exemplo n.º 18
0
 /**
  * ** Returns true if the URL starts with a protocol definition (ie. "http://...") ** @param url
  * The URL to test ** @return True if the URL starts with a protocol definition
  */
 public static boolean isAbsoluteURL(String url) {
   if (url == null) {
     return false;
   } else {
     // per "http://en.wikipedia.org/wiki/URI_scheme" all URL "schemes" contain only
     // alphanumeric or "." characters, and appears to be < 16 characters in length.
     for (int i = 0; (i < 16) && (i < url.length()); i++) {
       char ch = url.charAt(i);
       if (ch == ':') {
         return true; // A colon is the first non-alphanumeric we ran in to
       } else if (!Character.isLetterOrDigit(ch) && (ch != '.')) {
         return false;
       }
     }
     return false;
   }
 }
Exemplo n.º 19
0
  public void keyReleased(KeyEvent e) {
    char ch = e.getKeyChar();
    if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch)) return;
    int pos = m_editor.getCaretPosition();
    String str = m_editor.getText();
    if (str.length() == 0) return;

    for (int k = 0; k < m_comboBox.getItemCount(); k++) {
      String item = m_comboBox.getItemAt(k).toString();
      if (item.startsWith(str)) {
        m_editor.setText(item);
        m_editor.setCaretPosition(item.length());
        m_editor.moveCaretPosition(pos);
        m_comboBox.setSelectedItem(item);
        break;
      }
    }
  }
Exemplo n.º 20
0
 private boolean stranger(String myName) {
   // tty.println("=+= " + (myName.getBytes()[0])+" =" );
   // tty.println("=+= " + Character.isISOControl(myName.charAt(0)));
   if (Character.isISOControl(myName.charAt(0))) myName = "QUIT";
   if (myName.equals("QUIT")) {
     writeLine("! Thank you for coming!");
   }
   if (myName == null || myName.equals("QUIT")) {
     tty.println(" --- from " + remoteAddr + " at " + now.toString());
     return true;
   } // "QUIT" is not allowed as a nick name
   if (myName.equals(SECRET_NAME)) {
     tty.println("GiGi  from " + remoteAddr + " at " + now.toString());
     doList();
     return true;
   }
   return false; // a usual user name
 }
Exemplo n.º 21
0
  @EventHandler
  public void onTick(TickEvent event) {
    if (!bot.hasSpawned() || !bot.isConnected()) return;
    if (tickDelay > 0) {
      tickDelay--;
      return;
    }

    MainPlayerEntity player = bot.getPlayer();
    if (player == null || !bot.hasSpawned() || spamMessage == null) return;
    if (nextMessage > 0) {
      nextMessage--;
      return;
    }
    try {
      String message = spamMessage;
      MessageFormatter formatter = new MessageFormatter();
      synchronized (bots) {
        if (bots.size() > 0) {
          DarkBotMCSpambot bot = bots.get(++nextBot >= bots.size() ? nextBot = 0 : nextBot);
          if (bot != null && bot.bot != null && bot.bot.getSession() != null)
            formatter.setVariable("bot", bot.bot.getSession().getUsername());
        }
      }
      if (spamList.length > 0) {
        formatter.setVariable(
            "spamlist",
            spamList[++nextSpamList >= spamList.length ? nextSpamList = 0 : nextSpamList]);
      }
      formatter.setVariable("rnd", Util.generateRandomString(15 + random.nextInt(6)));
      formatter.setVariable(
          "msg",
          Character.toString(
              msgChars[++nextMsgChar >= msgChars.length ? nextMsgChar = 0 : nextMsgChar]));
      message = formatter.format(message);
      bot.say(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
    nextMessage = messageDelay;
  }
Exemplo n.º 22
0
 public static boolean isDigits(String s) {
   for (int i = 0; i < s.length(); i++) {
     if (!Character.isDigit(s.charAt(i))) return false;
   }
   return true;
 }
Exemplo n.º 23
0
  public static File[] getHighestJarVersions(
      File[] files,
      String[] version_out,
      String[] id_out, // currently the version of last versioned jar found...
      boolean discard_non_versioned_when_versioned_found) {
    // WARNING!!!!
    // don't use Debug/lglogger here as we can be called before AZ has been initialised

    List res = new ArrayList();
    Map version_map = new HashMap();

    for (int i = 0; i < files.length; i++) {

      File f = files[i];

      String name = f.getName().toLowerCase();

      if (name.endsWith(".jar")) {

        int cvs_pos = name.lastIndexOf("_cvs");

        int sep_pos;

        if (cvs_pos <= 0) sep_pos = name.lastIndexOf("_");
        else sep_pos = name.lastIndexOf("_", cvs_pos - 1);

        if (sep_pos == -1
            || sep_pos == name.length() - 1
            || !Character.isDigit(name.charAt(sep_pos + 1))) {

          // not a versioned jar

          res.add(f);

        } else {

          String prefix = name.substring(0, sep_pos);

          String version =
              name.substring(sep_pos + 1, (cvs_pos <= 0) ? name.length() - 4 : cvs_pos);

          String prev_version = (String) version_map.get(prefix);

          if (prev_version == null) {

            version_map.put(prefix, version);

          } else {

            if (PluginUtils.comparePluginVersions(prev_version, version) < 0) {

              version_map.put(prefix, version);
            }
          }
        }
      }
    }

    // If any of the jars are versioned then the assumption is that all of them are
    // For migration purposes (i.e. on the first real introduction of the update versioning
    // system) we drop all non-versioned jars from the set

    if (version_map.size() > 0 && discard_non_versioned_when_versioned_found) {

      res.clear();
    }

    // fix a problem we had with the rating plugin. It went out as rating_x.jar when it should
    // have been azrating_x.jar. If there are any azrating entries then we remove any rating ones
    // to avoid load problems

    if (version_map.containsKey("azrating")) {

      version_map.remove("rating");
    }

    Iterator it = version_map.keySet().iterator();

    while (it.hasNext()) {

      String prefix = (String) it.next();
      String version = (String) version_map.get(prefix);

      String target = prefix + "_" + version;

      version_out[0] = version;
      id_out[0] = prefix;

      for (int i = 0; i < files.length; i++) {

        File f = files[i];

        String lc_name = f.getName().toLowerCase();

        if (lc_name.equals(target + ".jar") || lc_name.equals(target + "_cvs.jar")) {

          res.add(f);

          break;
        }
      }
    }

    File[] res_array = new File[res.size()];

    res.toArray(res_array);

    return (res_array);
  }
Exemplo n.º 24
0
  private DarkBotMCSpambot(
      DarkBot darkBot,
      String server,
      String username,
      String password,
      String sessionId,
      String loginProxy,
      String proxy,
      String owner) {
    synchronized (bots) {
      bots.add(this);
      // slotsTaken.incrementAndGet();
      synchronized (slotsTaken) {
        slotsTaken.notifyAll();
      }
    }
    MinecraftBotData.Builder builder = MinecraftBotData.builder();
    // botData.nickname = "";
    // for(int i = 0; i < 10; i++)
    // botData.nickname += alphas[random.nextInt(alphas.length)];
    if (proxy != null && !proxy.isEmpty()) {
      int port = 80;
      ProxyType type = ProxyType.SOCKS;
      if (proxy.contains(":")) {
        String[] parts = proxy.split(":");
        proxy = parts[0];
        port = Integer.parseInt(parts[1]);
        if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1];
      }
      builder.withSocksProxy(new ProxyData(proxy, port, type));
      this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port));
    }
    if (loginProxy != null && !loginProxy.isEmpty()) {
      int port = 80;
      if (loginProxy.contains(":")) {
        String[] parts = loginProxy.split(":");
        loginProxy = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP));
      this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port));
    }
    builder.withUsername(username);
    if (sessionId != null) builder.withSessionId(sessionId);
    else builder.withPassword(password);
    if (server != null && !server.isEmpty()) {
      int port = 25565;
      if (server.contains(":")) {
        String[] parts = server.split(":");
        server = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withServer(server).withPort(port);
    } else throw new IllegalArgumentException("Unknown server!");

    this.owner = owner;
    MinecraftBotData botData = builder.build();
    System.setProperty("socksProxyHost", "");
    System.setProperty("socksProxyPort", "");
    System.out.println("[" + username + "] Connecting...");
    bot = new MinecraftBot(darkBot, botData);
    bot.setMovementDisabled(true);
    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    // System.gc();
    System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")");
    bot.getEventManager().registerListener(this);
    bot.getGameHandler().registerListener(this);

    long lastShoutTime = System.currentTimeMillis();
    while (bot.isConnected()) {
      if (die) {
        connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye"));
        return;
      }
      try {
        Thread.sleep(3000 + random.nextInt(1000));
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
      if (!bot.hasSpawned()) continue;
      connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt()));
      if (spamMessage == null || !canSpam) continue;
      String message = spamMessage;
      if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]);
      if (nextSkill >= skills.length) nextSkill = 0;
      if (message.contains("%bot")) {
        synchronized (bots) {
          message =
              message.replace(
                  "%bot",
                  bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++)
                      .bot
                      .getSession()
                      .getUsername());
        }
      }
      if (message.contains("%spamlist"))
        message = message.replace("%spamlist", spamList[nextSpamList++]);
      if (nextSpamList >= spamList.length) nextSpamList = 0;
      if (message.contains("%rnd")) {
        int length = 1;
        int index = message.indexOf("%rnd") + "%rnd".length();
        int lastIndex;
        for (lastIndex = index; lastIndex < message.length(); lastIndex++)
          if (Character.isDigit(message.charAt(lastIndex))) lastIndex++;
          else break;
        if (lastIndex > message.length()) lastIndex--;
        try {
          System.out.println(index + "," + lastIndex + "," + message.length());
          length = Integer.parseInt(message.substring(index, lastIndex));
        } catch (Exception exception) {
        }

        String randomChars = "";
        for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)];
        message = message.replace("%rnd", randomChars);
      }
      if (message.contains("%msg"))
        message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", "");
      if (message.contains("%ernd")) {
        message = message.replace("%ernd", "");
        int extraMessageLength = 15 + random.nextInt(6);
        message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " [";
        extraMessageLength -= 3;
        for (int i = 0; i < extraMessageLength; i++)
          message += alphas[random.nextInt(alphas.length)];
        message += "]";
      } else message = message.substring(0, Math.min(100, message.length()));
      connectionHandler.sendPacket(new Packet3Chat(message));
    }
    synchronized (bots) {
      bots.remove(this);
    }
    amountJoined.decrementAndGet();
    slotsTaken.decrementAndGet();
    synchronized (slotsTaken) {
      slotsTaken.notifyAll();
    }
  }
Exemplo n.º 25
0
 /** Retourne la valeur décimale corresondant à un digit hexadécimal */
 private static int code(char c) {
   return HEX.indexOf(Character.toUpperCase(c));
 }
Exemplo n.º 26
0
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }
  // [Issue#381]
  public void testSingleElementArray() throws Exception {
    final int intTest = 932832;
    final double doubleTest = 32.3234;
    final long longTest = 2374237428374293423L;
    final short shortTest = (short) intTest;
    final float floatTest = 84.3743f;
    final byte byteTest = (byte) 43;
    final char charTest = 'c';

    final ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);

    final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE);
    assertEquals(intTest, intValue);
    final Integer integerWrapperValue =
        mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class);
    assertEquals(Integer.valueOf(intTest), integerWrapperValue);

    final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class);
    assertEquals(doubleTest, doubleValue);
    final Double doubleWrapperValue =
        mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class);
    assertEquals(Double.valueOf(doubleTest), doubleWrapperValue);

    final long longValue = mapper.readValue(asArray(longTest), Long.TYPE);
    assertEquals(longTest, longValue);
    final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class);
    assertEquals(Long.valueOf(longTest), longWrapperValue);

    final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE);
    assertEquals(shortTest, shortValue);
    final Short shortWrapperValue =
        mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class);
    assertEquals(Short.valueOf(shortTest), shortWrapperValue);

    final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE);
    assertEquals(floatTest, floatValue);
    final Float floatWrapperValue =
        mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class);
    assertEquals(Float.valueOf(floatTest), floatWrapperValue);

    final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE);
    assertEquals(byteTest, byteValue);
    final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class);
    assertEquals(Byte.valueOf(byteTest), byteWrapperValue);

    final char charValue =
        mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.TYPE);
    assertEquals(charTest, charValue);
    final Character charWrapperValue =
        mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.class);
    assertEquals(Character.valueOf(charTest), charWrapperValue);

    final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE);
    assertTrue(booleanTrueValue);

    final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE);
    assertFalse(booleanFalseValue);

    final Boolean booleanWrapperTrueValue =
        mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class);
    assertEquals(Boolean.TRUE, booleanWrapperTrueValue);
  }
Exemplo n.º 28
0
    public void checkThirtyDegreeRule(
        ArrayList<Cam> cameras, ArrayList<Character> characters, int selectedIdx) {
      if (cameras == null || cameras.isEmpty()) {
        println("No cameras in the scene!");
      }

      if (characters.size() != 2) {
        println("Only two characters supported for now");
        // TODO (sanjeet): Hack! Fix this once more characters are allowed
      }

      Cam selectedCamera = cameras.get(selectedIdx);

      // TODO The characters.get results in a runtime error because there aren't currently any
      // characters allocated in the input file.
      Character ch1 = characters.get(0);
      Character ch2 = characters.get(1);

      // Obtaining (x,y,z) for characters and selected camera
      PVector ch1Location = ch1.getTranslation();
      PVector ch2Location = ch2.getTranslation();
      PVector selectedCameraLocation = selectedCamera.getTranslation();

      PVector cameraPoint = new PVector();
      cameraPoint.add(selectedCameraLocation);
      for (int i = 0; i < 100; i++) {
        cameraPoint.add(selectedCamera.getZAxis());
      }
      PVector intersection =
          getTwoLinesIntersection(
              new PVector(ch1Location.x, ch1Location.z),
              new PVector(ch2Location.x, ch2Location.z),
              new PVector(selectedCameraLocation.x, selectedCameraLocation.z),
              new PVector(cameraPoint.x, cameraPoint.z));

      PVector diff = PVector.sub(selectedCameraLocation, intersection);
      diff.normalize();
      FloatBuffer fb = selectedCamera.modelViewMatrix;
      float[] mat = fb.array();
      float[] fbMatrix = new float[mat.length];
      for (int i = 0; i < fbMatrix.length; i++) {
        fbMatrix[i] = mat[i];
      }
      fbMatrix[0] = -diff.x;
      fbMatrix[1] = diff.y;
      fbMatrix[2] = -diff.z;
      fbMatrix[9] = diff.x;
      fbMatrix[10] = diff.y;
      fbMatrix[11] = diff.z;
      fbMatrix[13] = intersection.x;
      fbMatrix[14] = intersection.y;
      fbMatrix[15] = intersection.z;
      PMatrix3D matrix = new PMatrix3D();
      matrix.set(fbMatrix);
      matrix.transpose();
      pushMatrix();
      applyMatrix(matrix);
      rotateY(radians(30));
      line(0, 0, 0, 0, 0, 1000);
      rotateY(radians(-2 * 30));
      line(0, 0, 0, 0, 0, 1000);
      popMatrix();

      for (int i = 0; i < cameras.size(); i++) {
        if (i == selectedIdx) {
          continue;
        }

        if (!cameras.get(i).isInView(ch1Location) && !cameras.get(i).isInView(ch2Location)) {
          continue;
        }
        PVector currCamLocation = cameras.get(i).getTranslation();
        PVector vect1 = PVector.sub(currCamLocation, intersection);
        PVector vect2 = PVector.sub(selectedCameraLocation, intersection);
        float dotP = vect1.dot(vect2) / (vect1.mag() * vect2.mag());
        if (acos(dotP) <= PI / 6) {
          cameras.get(i).setColor(255, 0, 0);
        } else {
          cameras.get(i).setColor(0, 0, 255);
        }
      }
    }