Java 类com.google.common.io.ByteArrayDataOutput 实例源码

项目:CloudNet    文件:SignSelector.java   
@EventHandler
public void handleInteract(PlayerInteractEvent e)
{
    if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && (e.getClickedBlock().getType().equals(Material.SIGN_POST) || e.getClickedBlock().getType().equals(Material.WALL_SIGN)))
    {
        if (containsPosition(e.getClickedBlock().getLocation()))
        {
            Sign sign = getSignByPosition(e.getClickedBlock().getLocation());
            if (sign.getServerInfo() != null)
            {
                String s = sign.getServerInfo().getServiceId().getServerId();
                ByteArrayDataOutput output = ByteStreams.newDataOutput();
                output.writeUTF("Connect");
                output.writeUTF(s);
                e.getPlayer().sendPluginMessage(CloudServer.getInstance().getPlugin(), "BungeeCord", output.toByteArray());
            }
        }
    }
}
项目:CloudNet    文件:MobSelector.java   
@EventHandler
public void handleInventoryClick(InventoryClickEvent e)
{
    if (!(e.getWhoClicked() instanceof Player)) return;

    if (inventories().contains(e.getInventory()) && e.getCurrentItem() != null && e.getSlot() == e.getRawSlot())
    {
        e.setCancelled(true);
        if (mobConfig.getItemLayout().getItemId() == e.getCurrentItem().getTypeId())
        {
            MobImpl mob = find(e.getInventory());
            if (mob.getServerPosition().containsKey(e.getSlot()))
            {
                if (CloudAPI.getInstance().getServerId().equalsIgnoreCase(mob.getServerPosition().get(e.getSlot()))) return;
                ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
                byteArrayDataOutput.writeUTF("Connect");
                byteArrayDataOutput.writeUTF(mob.getServerPosition().get(e.getSlot()));
                ((Player) e.getWhoClicked()).sendPluginMessage(CloudServer.getInstance().getPlugin(), "BungeeCord", byteArrayDataOutput.toByteArray());
            }
        }
    }
}
项目:apkfile    文件:ResourceString.java   
/**
 * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
 * Strings are prefixed by 2 values. The first is the number of characters in the string.
 * The second is the encoding length (number of bytes in the string).
 *
 * <p>Here's an example UTF-8-encoded string of ab©:
 * <pre>03 04 61 62 C2 A9 00</pre>
 *
 * @param str  The string to be encoded.
 * @param type The encoding type that the {@link ResourceString} should be encoded in.
 * @return The encoded string.
 */
public static byte[] encodeString(String str, Type type) {
    byte[] bytes = str.getBytes(type.charset());
    // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
    ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
    encodeLength(output, str.length(), type);
    if (type == Type.UTF8) {  // Only UTF-8 strings have the encoding length.
        encodeLength(output, bytes.length, type);
    }
    output.write(bytes);
    // NULL-terminate the string
    if (type == Type.UTF8) {
        output.write(0);
    } else {
        output.writeShort(0);
    }
    return output.toByteArray();
}
项目:apkfile    文件:ResourceString.java   
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
    if (length < 0) {
        output.write(0);
        return;
    }
    if (type == Type.UTF8) {
        if (length > 0x7F) {
            output.write(((length & 0x7F00) >> 8) | 0x80);
        }
        output.write(length & 0xFF);
    } else {  // UTF-16
        // TODO(acornwall): Replace output with a little-endian output.
        if (length > 0x7FFF) {
            int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
            output.write(highBytes & 0xFF);
            output.write((highBytes & 0xFF00) >> 8);
        }
        int lowBytes = length & 0xFFFF;
        output.write(lowBytes & 0xFF);
        output.write((lowBytes & 0xFF00) >> 8);
    }
}
项目:android-chunk-utils    文件:ResourceString.java   
/**
 * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
 * Strings are prefixed by 2 values. The first is the number of characters in the string.
 * The second is the encoding length (number of bytes in the string).
 *
 * <p>Here's an example UTF-8-encoded string of ab©:
 * <pre>03 04 61 62 C2 A9 00</pre>
 *
 * @param str The string to be encoded.
 * @param type The encoding type that the {@link ResourceString} should be encoded in.
 * @return The encoded string.
 */
public static byte[] encodeString(String str, Type type) {
  byte[] bytes = str.getBytes(type.charset());
  // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
  ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
  encodeLength(output, str.length(), type);
  if (type == Type.UTF8) {  // Only UTF-8 strings have the encoding length.
    encodeLength(output, bytes.length, type);
  }
  output.write(bytes);
  // NULL-terminate the string
  if (type == Type.UTF8) {
    output.write(0);
  } else {
    output.writeShort(0);
  }
  return output.toByteArray();
}
项目:android-chunk-utils    文件:ResourceString.java   
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
  if (length < 0) {
    output.write(0);
    return;
  }
  if (type == Type.UTF8) {
    if (length > 0x7F) {
      output.write(((length & 0x7F00) >> 8) | 0x80);
    }
    output.write(length & 0xFF);
  } else {  // UTF-16
    // TODO(acornwall): Replace output with a little-endian output.
    if (length > 0x7FFF) {
      int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
      output.write(highBytes & 0xFF);
      output.write((highBytes & 0xFF00) >> 8);
    }
    int lowBytes = length & 0xFFFF;
    output.write(lowBytes & 0xFF);
    output.write((lowBytes & 0xFF00) >> 8);
  }
}
项目:AndResM    文件:ResourceString.java   
/**
 * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
 * Strings are prefixed by 2 values. The first is the number of characters in the string.
 * The second is the encoding length (number of bytes in the string).
 *
 * <p>Here's an example UTF-8-encoded string of ab©:
 * <pre>03 04 61 62 C2 A9 00</pre>
 *
 * @param str The string to be encoded.
 * @param type The encoding type that the {@link ResourceString} should be encoded in.
 * @return The encoded string.
 */
public static byte[] encodeString(String str, Type type) {
  byte[] bytes = str.getBytes(type.charset());
  // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
  ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
  encodeLength(output, str.length(), type);
  if (type == Type.UTF8) {  // Only UTF-8 strings have the encoding length.
    encodeLength(output, bytes.length, type);
  }
  output.write(bytes);
  // NULL-terminate the string
  if (type == Type.UTF8) {
    output.write(0);
  } else {
    output.writeShort(0);
  }
  return output.toByteArray();
}
项目:AndResM    文件:ResourceString.java   
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
  if (length < 0) {
    output.write(0);
    return;
  }
  if (type == Type.UTF8) {
    if (length > 0x7F) {
      output.write(((length & 0x7F00) >> 8) | 0x80);
    }
    output.write(length & 0xFF);
  } else {  // UTF-16
    // TODO(acornwall): Replace output with a little-endian output.
    if (length > 0x7FFF) {
      int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
      output.write(highBytes & 0xFF);
      output.write((highBytes & 0xFF00) >> 8);
    }
    int lowBytes = length & 0xFFFF;
    output.write(lowBytes & 0xFF);
    output.write((lowBytes & 0xFF00) >> 8);
  }
}
项目:SkyWarsReloaded    文件:BungeeUtil.java   
public static void sendSignUpdateRequest(Game game) {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    String name = SkyWarsReloaded.getCfg().getBungeeServer();
    try {
        out.writeUTF("Forward");
        out.writeUTF("ALL");
        out.writeUTF("SkyWarsReloaded");

        ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
        DataOutputStream msgout = new DataOutputStream(msgbytes);
        msgout.writeUTF(name + ":" + game.getState().toString() + ":" + Integer.toString(game.getPlayers().size()) + ":" + Integer.toString(game.getNumberOfSpawns()) + ":" + game.getMapName());

        out.writeShort(msgbytes.toByteArray().length);
        out.write(msgbytes.toByteArray());

        Bukkit.getServer().sendPluginMessage(SkyWarsReloaded.get(), "BungeeCord", out.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:uavstack    文件:TailFile.java   
private String readLine() throws IOException {

        ByteArrayDataOutput out = ByteStreams.newDataOutput(300);
        int i = 0;
        int c;
        while ((c = raf.read()) != -1) {
            i++;
            out.write((byte) c);
            if (c == LINE_SEP.charAt(0)) {
                break;
            }
        }
        if (i == 0) {
            return null;
        }
        return new String(out.toByteArray(), Charsets.UTF_8);
    }
项目:uavstack    文件:TailFile.java   
private String readLine() throws IOException {

        ByteArrayDataOutput out = ByteStreams.newDataOutput(300);
        int i = 0;
        int c;
        while ((c = raf.read()) != -1) {
            i++;
            out.write((byte) c);
            if (c == LINE_SEP.charAt(0)) {
                break;
            }
        }
        if (i == 0) {
            return null;
        }
        return new String(out.toByteArray(), Charsets.UTF_8);
    }
项目:SamaGamesCore    文件:ImpPlayerSettings.java   
@Override
public void update() {
    Player player = Bukkit.getPlayer(playerData.getPlayerID());

    try {
        //Update SQL
        gameServiceManager.setPlayerSettings(playerData.getPlayerBean(), this);

        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        //Comamnd type
        out.writeUTF("settingsChanges");
        //The player to refresh settings on bungee
        out.writeUTF(player.getUniqueId().toString());
        //Send data on network channel
        player.sendPluginMessage(APIPlugin.getInstance(), "Network", out.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:ServerSync    文件:VaultIO.java   
public void sendVaultBalance(String playerName, double playerBalance)
{
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(ServerSync.vault.vaultSubchannel); //Vault Subchannel
    out.writeUTF(ServerSync.vault.economySubchannel); //Vault Economy Subchannel
    out.writeUTF("Balance"); //Operation
    out.writeUTF(ServerSync.bungeeServerName); //Server Name
    out.writeUTF(ServerSync.pluginVersion); //Client Version
    out.writeUTF(playerName); //Player name

    if (ServerSync.encryption.isEnabled())
    {
        out.writeUTF(ServerSync.encryption.encrypt(String.valueOf(playerBalance)));
    }
    else
    {
        out.writeUTF(Double.toString(playerBalance)+""); //Player balance
    }

    ServerSync.bungeeOutgoing.sendMessage(out, ServerSync.bungeePluginChannel);

    if (ServerSync.verbose)
    {
        Log.info(ServerSync.consolePrefix + "Vault - Balance update sent for " + ChatColor.YELLOW + playerName + " for $" + playerBalance);
    }
}
项目:ServerSync    文件:VaultIO.java   
protected void sendPlayerGroups(OfflinePlayer player, String world, String groups)
{
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeUTF(ServerSync.vault.vaultSubchannel);
    out.writeUTF(ServerSync.vault.permissionSubchannel); //Vault Permission sub channel
    out.writeUTF("PlayerGroups"); //Operation
    out.writeUTF(ServerSync.bungeeServerName); //Server Name
    out.writeUTF(ServerSync.pluginVersion); //Client Version
    out.writeUTF(player.getUniqueId().toString()); //Player UUID
    out.writeUTF(world); //World
    out.writeUTF(groups); //Groups

    ServerSync.bungeeOutgoing.sendMessage(out, ServerSync.bungeePluginChannel);

    if (ServerSync.verbose)
    {
        Log.info(ServerSync.consolePrefix + "Vault - Permission group update sent for " + ChatColor.YELLOW + player.getName());
    }
}
项目:PocketServer    文件:PocketChunk.java   
public byte[] getData() {
    if (this.cache == null || this.dirty) {
        ByteArrayDataOutput output = ByteStreams.newDataOutput();
        output.write(toByteArray(blocks, pocketBlock -> (byte) pocketBlock.getId()));
        output.write(data.getRaw());
        output.write(lighting.getRaw());
        output.write(skylight.getRaw());
        output.write(height.getRaw());

        for (int i = 0; i < this.biomes.length; ++i) {
            byte r = this.biomeColors[i * 3];
            byte g = this.biomeColors[i * 3 + 1];
            byte b = this.biomeColors[i * 3 + 2];
            int color = r << 16 | g << 8 | b;
            output.writeInt(24 << this.biomes[i] | color & 0xffffff);
        }
        output.writeInt(0);

        this.dirty = false;
        this.cache = output.toByteArray();
    }
    return this.cache;
}
项目:LuckPerms    文件:BungeeMessagingService.java   
@Override
protected void sendMessage(String message) {
    new BukkitRunnable() {
        @Override
        public void run() {
            Collection<? extends Player> players = BungeeMessagingService.this.plugin.getServer().getOnlinePlayers();
            Player p = Iterables.getFirst(players, null);
            if (p == null) {
                return;
            }

            ByteArrayDataOutput out = ByteStreams.newDataOutput();
            out.writeUTF(message);

            byte[] data = out.toByteArray();

            p.sendPluginMessage(BungeeMessagingService.this.plugin, CHANNEL, data);
            cancel();
        }
    }.runTaskTimer(this.plugin, 1L, 100L);
}
项目:android-arscblamer    文件:ResourceString.java   
/**
 * Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
 * Strings are prefixed by 2 values. The first is the number of characters in the string.
 * The second is the encoding length (number of bytes in the string).
 *
 * <p>Here's an example UTF-8-encoded string of ab©:
 * <pre>03 04 61 62 C2 A9 00</pre>
 *
 * @param str The string to be encoded.
 * @param type The encoding type that the {@link ResourceString} should be encoded in.
 * @return The encoded string.
 */
public static byte[] encodeString(String str, Type type) {
  byte[] bytes = str.getBytes(type.charset());
  // The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
  ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
  encodeLength(output, str.length(), type);
  if (type == Type.UTF8) {  // Only UTF-8 strings have the encoding length.
    encodeLength(output, bytes.length, type);
  }
  output.write(bytes);
  // NULL-terminate the string
  if (type == Type.UTF8) {
    output.write(0);
  } else {
    output.writeShort(0);
  }
  return output.toByteArray();
}
项目:android-arscblamer    文件:ResourceString.java   
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
  if (length < 0) {
    output.write(0);
    return;
  }
  if (type == Type.UTF8) {
    if (length > 0x7F) {
      output.write(((length & 0x7F00) >> 8) | 0x80);
    }
    output.write(length & 0xFF);
  } else {  // UTF-16
    // TODO(acornwall): Replace output with a little-endian output.
    if (length > 0x7FFF) {
      int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
      output.write(highBytes & 0xFF);
      output.write((highBytes & 0xFF00) >> 8);
    }
    int lowBytes = length & 0xFFFF;
    output.write(lowBytes & 0xFF);
    output.write((lowBytes & 0xFF00) >> 8);
  }
}
项目:turbine    文件:ClassWriter.java   
/** Writes a {@link ClassFile} to bytecode. */
public static byte[] writeClass(ClassFile classfile) {
  ConstantPool pool = new ConstantPool();
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.writeShort(classfile.access());
  output.writeShort(pool.classInfo(classfile.name()));
  output.writeShort(classfile.superName() != null ? pool.classInfo(classfile.superName()) : 0);
  output.writeShort(classfile.interfaces().size());
  for (String i : classfile.interfaces()) {
    output.writeShort(pool.classInfo(i));
  }
  output.writeShort(classfile.fields().size());
  for (ClassFile.FieldInfo f : classfile.fields()) {
    writeField(pool, output, f);
  }
  output.writeShort(classfile.methods().size());
  for (ClassFile.MethodInfo m : classfile.methods()) {
    writeMethod(pool, output, m);
  }
  writeAttributes(pool, output, LowerAttributes.classAttributes(classfile));
  return finishClass(pool, output);
}
项目:turbine    文件:ClassWriterTest.java   
@Test
public void manyManyConstants() {
  ConstantPool pool = new ConstantPool();
  Map<Integer, String> entries = new LinkedHashMap<>();
  int i = 0;
  while (pool.nextEntry < 0xffff) {
    String value = "c" + i++;
    entries.put(pool.classInfo(value), value);
  }
  ByteArrayDataOutput bytes = ByteStreams.newDataOutput();
  ClassWriter.writeConstantPool(pool, bytes);
  ConstantPoolReader reader =
      ConstantPoolReader.readConstantPool(new ByteReader(bytes.toByteArray(), 0));
  for (Map.Entry<Integer, String> entry : entries.entrySet()) {
    assertThat(reader.classInfo(entry.getKey())).isEqualTo(entry.getValue());
  }
}
项目:opencensus-java    文件:SerializationUtils.java   
static byte[] serializeBinary(TagContext tags) throws TagContextSerializationException {
  // Use a ByteArrayDataOutput to avoid needing to handle IOExceptions.
  final ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
  byteArrayDataOutput.write(VERSION_ID);
  int totalChars = 0; // Here chars are equivalent to bytes, since we're using ascii chars.
  for (Iterator<Tag> i = InternalUtils.getTags(tags); i.hasNext(); ) {
    Tag tag = i.next();
    totalChars += tag.getKey().getName().length();
    totalChars += tag.getValue().asString().length();
    encodeTag(tag, byteArrayDataOutput);
  }
  if (totalChars > TAGCONTEXT_SERIALIZED_SIZE_LIMIT) {
    throw new TagContextSerializationException(
        "Size of TagContext exceeds the maximum serialized size "
            + TAGCONTEXT_SERIALIZED_SIZE_LIMIT);
  }
  return byteArrayDataOutput.toByteArray();
}
项目:opencensus-java    文件:TagContextDeserializationTest.java   
@Test
public void testDeserializeNonConsecutiveDuplicateKeys()
    throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(SerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  encodeTagToOutput("Key3", "Value3", output);
  encodeTagToOutput("Key1", "Value4", output);
  encodeTagToOutput("Key2", "Value5", output);
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value4"))
          .put(TagKey.create("Key2"), TagValue.create("Value5"))
          .put(TagKey.create("Key3"), TagValue.create("Value3"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
项目:opencensus-java    文件:TagContextDeserializationTest.java   
@Test
public void testDeserializeNonConsecutiveDuplicateTags()
    throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(SerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  encodeTagToOutput("Key3", "Value3", output);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value1"))
          .put(TagKey.create("Key2"), TagValue.create("Value2"))
          .put(TagKey.create("Key3"), TagValue.create("Value3"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
项目:opencensus-java    文件:TagContextDeserializationTest.java   
@Test
public void stopParsingAtUnknownField() throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(SerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);

  // Write unknown field ID 1.
  output.write(1);
  output.write(new byte[] {1, 2, 3, 4});

  encodeTagToOutput("Key3", "Value3", output);

  // key 3 should not be included
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value1"))
          .put(TagKey.create("Key2"), TagValue.create("Value2"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
项目:leveldb-sstable    文件:DBFormat.java   
@Override
public Slice findShortestSeparator(Slice start, Slice limit) {
    Slice userStart = extractUserKey(start);
    Slice userLimit = extractUserKey(limit);
    Slice tmp = userComparator.findShortestSeparator(userStart, userLimit);
    if (tmp.size() < userStart.size() && userComparator.compare(userStart, tmp) < 0) {
        ByteArrayDataOutput buffer = ByteStreams.newDataOutput();
        buffer.write(tmp.data(), 0, tmp.size());
        try {
            Coding.putFixed64(buffer, packSequenceAndType(MAX_SEQUENCE_NUMBER, VALUE_TYPE_FOR_SEEK));
        } catch (IOException e) {
            // should never exception
            return start;
        }
        tmp = new Slice(buffer.toByteArray());
        Preconditions.checkState(compare(start, tmp) < 0);
        Preconditions.checkState(compare(tmp, limit) < 0);
        return tmp;
    }
    return start;
}
项目:leveldb-sstable    文件:DBFormat.java   
@Override
public Slice findShortSuccessor(Slice key) {
    Slice userKey = extractUserKey(key);
    Slice tmp = userComparator.findShortSuccessor(userKey);
    if (tmp.size() < userKey.size() && userComparator.compare(userKey, tmp) < 0) {
        ByteArrayDataOutput buffer = ByteStreams.newDataOutput();
        buffer.write(tmp.data(), 0, tmp.size());
        try {
            Coding.putFixed64(buffer, packSequenceAndType(MAX_SEQUENCE_NUMBER, VALUE_TYPE_FOR_SEEK));
        } catch (IOException e) {
            // should never exception
            return key;
        }
        tmp = new Slice(buffer.toByteArray());
        Preconditions.checkState(compare(key, tmp) < 0);
        return tmp;
    }
    return key;
}
项目:leveldb-sstable    文件:TestCoding.java   
@Test
public void testVarint32() throws IOException {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    Coding.putVarint32(out, 0x4d);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x4d});
    out = ByteStreams.newDataOutput();
    Coding.putVarint32(out, 0x987);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0x13});
    out = ByteStreams.newDataOutput();
    Coding.putVarint32(out, 0xa987);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0x02});
    out = ByteStreams.newDataOutput();
    Coding.putVarint32(out, 0xf0a987);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0xc2, (byte) 0x07});
    out = ByteStreams.newDataOutput();
    Coding.putVarint32(out, 0xfedca987);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0xf2, (byte) 0xf6, (byte) 0x0f});
}
项目:leveldb-sstable    文件:TestCoding.java   
@Test
public void testVarint64() throws IOException {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0x4dL);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x4d});
    out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0x987L);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0x13});
    out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0xa987L);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0x02});
    out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0xf0a987L);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0xc2, (byte) 0x07});
    out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0xfedca987L);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0x87, (byte) 0xd3, (byte) 0xf2, (byte) 0xf6, (byte) 0x0f});
    out = ByteStreams.newDataOutput();
    Coding.putVarint64(out, 0xffffffffffffffffL);
    assertArrayEquals(out.toByteArray(), new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x01});
}
项目:leveldb-sstable    文件:TestBloomFilter.java   
@Test
public void TestSimpleBuilder() throws IOException {
    FilterPolicy bloom = new BloomFilterPolicy(10);
    ImmutableList.Builder<Slice> keys = new ImmutableList.Builder<Slice>();
    keys.add(new Slice("foo"));
    keys.add(new Slice("bar"));
    keys.add(new Slice("leveldb"));
    keys.add(new Slice("mapreduce"));
    keys.add(new Slice(""));
    keys.add(new Slice("1234"));
    keys.add(new Slice("\0\1\2\3\4"));
    keys.add(new Slice(new byte[]{(byte) 255, (byte) 254, (byte) 253, (byte) 252, (byte) 251}));
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    bloom.createFilter(keys.build(), out);
    assertEquals(Utils.escapeString(new Slice(out.toByteArray())), "4\\xfd_1C\\x96<\\x18\\x12K\\x06");
}
项目:ACaZoo    文件:MerkleTreeTest.java   
@Test
public void testSerialization() throws Exception
{
    Range<Token> full = new Range<>(tok(-1), tok(-1));

    // populate and validate the tree
    mt.maxsize(256);
    mt.init();
    for (TreeRange range : mt.invalids())
        range.addAll(new HIterator(range.right));

    byte[] initialhash = mt.hash(full);

    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    MerkleTree.serializer.serialize(mt, out, MessagingService.current_version);
    byte[] serialized = out.toByteArray();

    ByteArrayDataInput in = ByteStreams.newDataInput(serialized);
    MerkleTree restored = MerkleTree.serializer.deserialize(in, MessagingService.current_version);

    assertHashEquals(initialhash, restored.hash(full));
}
项目:WorldDownloader-Serverside-Companion    文件:WDLPackets.java   
/**
 * Creates the WDL packet #4.
 * 
 * This packet specifies the initial overrides for what chunks can and
 * cannot be saved.
 *
 * This packet starts with an int stating the number of keys, and then a
 * series of values for 1 range group. The range group starts with its name
 * (the key in ranges), then an int (the number of ranges) and then each of
 * the ranges as generated by
 * {@link #writeProtectionRange(ProtectionRange, ByteArrayDataOutput)}.
 */
public static byte[] createWDLPacket4(
        Map<String, List<ProtectionRange>> ranges) {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();

    output.writeInt(4);

    output.writeInt(ranges.size());

    for (String key : ranges.keySet()) {
        output.writeUTF(key);
        List<ProtectionRange> rangeGroup = ranges.get(key);
        output.writeInt(rangeGroup.size());
        for (ProtectionRange range : rangeGroup) {
            writeProtectionRange(range, output);
        }
    }

    return output.toByteArray();
}
项目:WorldDownloader-Serverside-Companion    文件:WDLPackets.java   
/**
 * Creates the WDL packet #5.
 * 
 * This packet specifies adds additional overrides to or sets all of the
 * overrides in a single group.
 *
 * This packet starts with a String stating the group, then a boolean that
 * specifies whether it is setting (true) or adding (false) the ranges, and
 * then an int (the number of ranges that will be added). Then, each range,
 * formated by
 * {@link #writeProtectionRange(ProtectionRange, ByteArrayDataOutput)}.
 */
public static byte[] createWDLPacket5(String group,
        boolean replace, List<ProtectionRange> ranges) {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();

    output.writeInt(5);

    output.writeUTF(group);
    output.writeBoolean(replace);
    output.writeInt(ranges.size());

    for (ProtectionRange range : ranges) {
        writeProtectionRange(range, output);
    }

    return output.toByteArray();
}
项目:WorldDownloader-Serverside-Companion    文件:WDLPackets.java   
/**
 * Creates the WDL packet #7.
 * 
 * This packet replaces all of the ranges with the given tag with a new set
 * of ranges.
 *
 * This packet starts with a String stating the group, then a second string
 * that specifies the tag to replace. After that, there is an int stating
 * the number of ranges, and then each range as formated by
 * {@link #writeProtectionRange(ProtectionRange, ByteArrayDataOutput)}.
 */
public static byte[] createWDLPacket7(String group,
        String tag, List<ProtectionRange> newRanges) {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();

    output.writeInt(7);

    output.writeUTF(group);
    output.writeUTF(tag);

    output.writeInt(newRanges.size());

    for (ProtectionRange range : newRanges) {
        writeProtectionRange(range, output);
    }

    return output.toByteArray();
}
项目:WorldDownloader-Serverside-Companion    文件:WDLPackets.java   
/**
 * Writes a protection range to the given output stream.
 * 
 * This is a string with the range's tag, then 4 integers for the
 * coordinates (x1, z1, x2, z2). This method also swaps x1 and x2 if x1 is
 * greater than x2.
 */
private static void writeProtectionRange(ProtectionRange range, 
        ByteArrayDataOutput output) {
    output.writeUTF(range.tag);

    int x1 = range.x1, z1 = range.z1;
    int x2 = range.x2, z2 = range.z2;

    if (x1 > x2) {
        x2 = range.x1;
        x1 = range.x2;
    }
    if (z1 > z2) {
        z2 = range.z1;
        z1 = range.z2;
    }

    output.writeInt(x1);
    output.writeInt(z1);
    output.writeInt(x2);
    output.writeInt(z2);
}
项目:bedwars-reloaded-bungee    文件:JoinSign.java   
public void sendUpdateRequest() {
    Player player = Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
    if(player == null) return;

    try {
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeUTF("Forward");
        out.writeUTF(Subchannel.UPDATE_REQUEST.toString());
        out.writeUTF(this.gameName);
        out.writeUTF(this.serverName);

        Main.getInstance().getServer().getMessenger()
            .dispatchIncomingMessage(player, Main.BUNGEE_CHANNEL_NAME, out.toByteArray());
    } catch(Exception ex) {
        if(Main.DEBUGGING) {
            Main.getInstance().getLogger().info("Error on sending update request for sign: " + ex.getMessage());
        }
    }
}
项目:java-u2flib-server    文件:Client.java   
public SignResponse sign(DeviceRegistration registeredDevice, SignRequest startedSignature) throws Exception {
    Map<String, String> clientData = new HashMap<String, String>();
    clientData.put("typ", "navigator.id.getAssertion");
    clientData.put("challenge", startedSignature.getChallenge());
    clientData.put("origin", "http://example.com");
    String clientDataJson = objectMapper.writeValueAsString(clientData);


    byte[] clientParam = crypto.hash(clientDataJson);
    byte[] appParam = crypto.hash(startedSignature.getAppId());
    com.yubico.u2f.softkey.messages.SignRequest signRequest = new com.yubico.u2f.softkey.messages.SignRequest((byte) 0x01, clientParam, appParam, U2fB64Encoding.decode(registeredDevice.getKeyHandle()));

    RawSignResponse rawSignResponse = key.sign(signRequest);

    String clientDataBase64 = U2fB64Encoding.encode(clientDataJson.getBytes());
    ByteArrayDataOutput authData = ByteStreams.newDataOutput();
    authData.write(rawSignResponse.getUserPresence());
    authData.writeInt((int) rawSignResponse.getCounter());
    authData.write(rawSignResponse.getSignature());

    return new SignResponse(
            clientDataBase64,
            U2fB64Encoding.encode(authData.toByteArray()),
            startedSignature.getKeyHandle()
    );
}
项目:java-u2flib-server    文件:CodecTestUtils.java   
public static byte[] encodeRegisterResponse(RawRegisterResponse rawRegisterResponse) throws U2fBadInputException {
    byte[] keyHandle = rawRegisterResponse.keyHandle;
    if (keyHandle.length > 255) {
        throw new U2fBadInputException("keyHandle length cannot be longer than 255 bytes!");
    }

    try {
        ByteArrayDataOutput encoded = ByteStreams.newDataOutput();
        encoded.write(RawRegisterResponse.REGISTRATION_RESERVED_BYTE_VALUE);
        encoded.write(rawRegisterResponse.userPublicKey);
        encoded.write((byte) keyHandle.length);
        encoded.write(keyHandle);
        encoded.write(rawRegisterResponse.attestationCertificate.getEncoded());
        encoded.write(rawRegisterResponse.signature);
        return encoded.toByteArray();
    } catch (CertificateEncodingException e) {
        throw new U2fBadInputException("Error when encoding attestation certificate.", e);
    }
}
项目:MC-MineAPI.Java    文件:ParticlePacket.java   
@Override
public void write(ByteArrayDataOutput out)
{
    // ------
    // SERVER
    // ------

    out.writeUTF( particleName );

    out.writeDouble( particlePosX );
    out.writeDouble( particlePosY );
    out.writeDouble( particlePosZ );

    out.writeDouble( velX );
    out.writeDouble( velY );
    out.writeDouble( velZ );
}
项目:MineFantasy    文件:BattlegearUtils.java   
public static void writeItemStack(ByteArrayDataOutput par1DataOutputStream, ItemStack par0ItemStack) throws IOException {

        if (par0ItemStack == null) {
            par1DataOutputStream.writeShort(-1);
        } else {
            par1DataOutputStream.writeShort(par0ItemStack.itemID);
            par1DataOutputStream.writeByte(par0ItemStack.stackSize);
            par1DataOutputStream.writeShort(par0ItemStack.getItemDamage());
            NBTTagCompound nbttagcompound = null;

            if (par0ItemStack.getItem().isDamageable() || par0ItemStack.getItem().getShareTag()) {
                nbttagcompound = par0ItemStack.stackTagCompound;
            }

            writeNBTTagCompound(nbttagcompound, par1DataOutputStream);
        }

    }
项目:PeripheralsPlusPlus    文件:PeripheralBarrel.java   
private void updateAmount() {
    int amount = item == null ? 0 : item.stackSize;
    if (prevAmount != amount || prevMaxSize != maxSize) {
        World world = turtle.getWorld();
        Vec3 pos = turtle.getPosition();
        int x = (int)Math.floor(pos.xCoord);
        int y = (int)Math.floor(pos.yCoord);
        int z = (int)Math.floor(pos.zCoord);

        ByteArrayDataOutput os = ByteStreams.newDataOutput();
        os.writeInt(x);
        os.writeInt(y);
        os.writeInt(z);
        os.writeInt(amount);
        os.writeInt(maxSize);
        PacketDispatcher.sendPacketToAllAround(pos.xCoord + 0.5D, pos.yCoord + 0.5D, pos.zCoord + 0.5D, 64.0D, world.provider.dimensionId, PacketDispatcher.getTinyPacket(MiscPeripherals.instance, (short)5, os.toByteArray()));
    }
}