Ejemplo n.º 1
0
  /**
   * Decode file charset.
   *
   * @param f File to process.
   * @return File charset.
   * @throws IOException in case of error.
   */
  public static Charset decode(File f) throws IOException {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();

    String[] firstCharsets = {
      Charset.defaultCharset().name(), "US-ASCII", "UTF-8", "UTF-16BE", "UTF-16LE"
    };

    Collection<Charset> orderedCharsets = U.newLinkedHashSet(charsets.size());

    for (String c : firstCharsets)
      if (charsets.containsKey(c)) orderedCharsets.add(charsets.get(c));

    orderedCharsets.addAll(charsets.values());

    try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
      FileChannel ch = raf.getChannel();

      ByteBuffer buf = ByteBuffer.allocate(4096);

      ch.read(buf);

      buf.flip();

      for (Charset charset : orderedCharsets) {
        CharsetDecoder decoder = charset.newDecoder();

        decoder.reset();

        try {
          decoder.decode(buf);

          return charset;
        } catch (CharacterCodingException ignored) {
        }
      }
    }

    return Charset.defaultCharset();
  }
Ejemplo n.º 2
0
  /** {@inheritDoc} */
  @Override
  public ByteBuffer encode(GridNioSession ses, GridClientMessage msg)
      throws IOException, GridException {
    assert msg != null;

    if (msg instanceof GridTcpRestPacket) return encodeMemcache((GridTcpRestPacket) msg);
    else if (msg == PING_MESSAGE) return ByteBuffer.wrap(PING_PACKET);
    else {
      byte[] data = marshaller.marshal(msg);

      assert data.length > 0;

      ByteBuffer res = ByteBuffer.allocate(data.length + 5);

      res.put(GRIDGAIN_REQ_FLAG);
      res.put(U.intToBytes(data.length));
      res.put(data);

      res.flip();

      return res;
    }
  }