com.google.common.io.ByteArrayDataInput Java Examples

The following examples show how to use com.google.common.io.ByteArrayDataInput. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PluginMessageListener.java    From ChangeSkin with MIT License 6 votes vote down vote up
@EventHandler
public void onPluginMessage(PluginMessageEvent messageEvent) {
    String channel = messageEvent.getTag();
    if (messageEvent.isCancelled() || !channel.startsWith(plugin.getName().toLowerCase())) {
        return;
    }

    ByteArrayDataInput dataInput = ByteStreams.newDataInput(messageEvent.getData());

    ProxiedPlayer invoker = (ProxiedPlayer) messageEvent.getReceiver();
    if (channel.equals(permissionResultChannel)) {
        PermResultMessage message = new PermResultMessage();
        message.readFrom(dataInput);
        if (message.isAllowed()) {
            onPermissionSuccess(message, invoker);
        } else {
            plugin.sendMessage(invoker, "no-permission");
        }
    } else if (channel.equals(forwardCommandChannel)) {
        onCommandForward(invoker, dataInput);
    }
}
 
Example #2
Source File: BungeeReceiver.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPluginMessageReceived(final String channel, final Player player, final byte[] data) {
    if (!isEnabled) {
        return;
    }

    final ByteArrayDataInput in = ByteStreams.newDataInput(data);

    // Check subchannel
    final String subChannel = in.readUTF();
    if ("AuthMe.v2.Broadcast".equals(subChannel)) {
        handleBroadcast(in);
    } else if ("AuthMe.v2".equals(subChannel)) {
        handle(in);
    }
}
 
Example #3
Source File: BungeeCordVariables.java    From ScoreboardStats with MIT License 6 votes vote down vote up
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
    if (!channel.equals(BUNGEE_CHANNEL)) {
        return;
    }

    ByteArrayDataInput in = ByteStreams.newDataInput(message);
    String subChannel = in.readUTF();
    if ("PlayerCount".equals(subChannel)) {
        try {
            String server = in.readUTF();
            int count = in.readInt();

            if ("ALL".equals(server)) {
                onlinePlayers = count;
            }
        } catch (Exception eofException) {
            //happens if bungeecord doesn't know the server
            //ignore the admin should be notified by seeing the -1
        }
    }
}
 
Example #4
Source File: MerkleTreeTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@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);

    DataOutputBuffer out = new DataOutputBuffer();
    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));
}
 
Example #5
Source File: PluginMessageListener.java    From ResourcepacksPlugins with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void pluginMessageReceived(PluginMessageEvent event) {
    if(!plugin.isEnabled() || !event.getTag().equals("rp:plugin") || !(event.getSender() instanceof Server))
        return;

    ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());
    String subchannel = in.readUTF();
    if("authMeLogin".equals(subchannel)) {
        String playerName = in.readUTF();
        UUID playerId = UUID.fromString(in.readUTF());

        plugin.setAuthenticated(playerId, true);
        if(!plugin.hasBackend(playerId) && plugin.getConfig().getBoolean("useauth", false)) {
            ProxiedPlayer player = plugin.getProxy().getPlayer(playerId);
            if(player != null) {
                String serverName = "";
                if(player.getServer() != null) {
                    serverName = player.getServer().getInfo().getName();
                }
                plugin.getPackManager().applyPack(playerId, serverName);
            }
        }
    }
}
 
Example #6
Source File: SettingMapFactory.java    From helper with MIT License 6 votes vote down vote up
/**
 * Decodes the given byte array to a {@link SettingMap}.
 *
 * <p>Operates on the reverse of {@link SettingMap#encode()}.</p>
 *
 * @param buf the byte array
 * @return the decoded map
 */
public SettingMap<S, V> decode(byte[] buf) {
    if (buf.length == 0) {
        return newMap();
    }

    ByteArrayDataInput in = ByteStreams.newDataInput(buf);
    int n = Byte.toUnsignedInt(in.readByte());

    byte[] states = Arrays.copyOf(this.defaultStates, this.defaultStates.length);

    for (int i = 0; i < n; i++) {
        int settingOrdinal = Byte.toUnsignedInt(in.readByte());
        byte stateByte = in.readByte();

        states[settingOrdinal] = stateByte;
    }

    return new SettingMap<>(this, states);
}
 
Example #7
Source File: StatementPatternStorage.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public Tuple getNext() throws IOException {
    try {
        if (reader.nextKeyValue()) {
            Key key = reader.getCurrentKey();
            org.apache.accumulo.core.data.Value value = reader.getCurrentValue();
            ByteArrayDataInput input = ByteStreams.newDataInput(key.getRow().getBytes());
            RyaStatement ryaStatement = ryaContext.deserializeTriple(layout, new TripleRow(key.getRow().getBytes(),
                    key.getColumnFamily().getBytes(), key.getColumnQualifier().getBytes()));

            Tuple tuple = TupleFactory.getInstance().newTuple(7);
            tuple.set(0, ryaStatement.getSubject().getData());
            tuple.set(1, ryaStatement.getPredicate().getData());
            tuple.set(2, ryaStatement.getObject().getData());
            tuple.set(3, (ryaStatement.getContext() != null) ? (ryaStatement.getContext().getData()) : (null));
            tuple.set(4, ryaStatement.getSubject().getDataType());
            tuple.set(5, ryaStatement.getPredicate().getDataType());
            tuple.set(6, ryaStatement.getObject().getDataType());
            return tuple;
        }
    } catch (Exception e) {
        throw new IOException(e);
    }
    return null;
}
 
Example #8
Source File: PluginMessageListener.java    From ChangeSkin with MIT License 6 votes vote down vote up
private void onCommandForward(CommandSender invoker, ByteArrayDataInput dataInput) {
    ForwardMessage message = new ForwardMessage();
    message.readFrom(dataInput);

    if (message.isOP() && message.isSource()) {
        //bukkit op and it won't run as bungee console
        invoker.addGroups(plugin.getName() + "-OP");
    }

    String line = message.getCommandName() + ' ' + message.getArgs();
    if (message.isSource()) {
        //the player is the actual invoker other it's the console
        ProxyServer.getInstance().getPluginManager().dispatchCommand(invoker, line);
    } else {
        CommandSender console = ProxyServer.getInstance().getConsole();
        ProxyServer.getInstance().getPluginManager().dispatchCommand(console, line);
    }
}
 
Example #9
Source File: MetaBlockPacket.java    From bartworks with MIT License 6 votes vote down vote up
@Override
public GT_Packet decode(ByteArrayDataInput byteArrayDataInput) {
    byte[] tmp = new byte[16];
    byteArrayDataInput.readFully(tmp);
    ByteBuffer buff = ByteBuffer.wrap(tmp);
    this.x = buff.getInt();
    this.z = buff.getInt();
    this.y = buff.getShort();
    this.meta = buff.getShort();
    MetaBlockPacket todecode = new MetaBlockPacket(this.x, this.y, this.z, this.meta);
    if (buff.getInt() != MurmurHash3.murmurhash3_x86_32(ByteBuffer.allocate(12).putInt(this.x).putInt(this.z).putShort(this.y).putShort(this.meta).array(), 0, 12, 31)) {
        MainMod.LOGGER.error("PACKET HASH DOES NOT MATCH!");
        return null;
    }
    return todecode;
}
 
Example #10
Source File: PluginMessageMessenger.java    From LuckPerms with MIT License 6 votes vote down vote up
@Subscribe
public void onPluginMessage(PluginMessageEvent e) {
    // compare the underlying text representation of the channel
    // the namespaced representation is used by legacy servers too, so we
    // are able to support both. :)
    if (!e.getIdentifier().getId().equals(CHANNEL.getId())) {
        return;
    }

    e.setResult(ForwardResult.handled());

    if (e.getSource() instanceof Player) {
        return;
    }

    ByteArrayDataInput in = e.dataAsDataStream();
    String msg = in.readUTF();

    if (this.consumer.consumeIncomingMessageAsString(msg)) {
        // Forward to other servers
        this.plugin.getBootstrap().getScheduler().executeAsync(() -> dispatchMessage(e.getData()));
    }
}
 
Example #11
Source File: RendererPacket.java    From bartworks with MIT License 6 votes vote down vote up
@Override
public GT_Packet decode(ByteArrayDataInput dataInput) {

    byte[] buffer = new byte[19];
    dataInput.readFully(buffer);

    this.coords = new Coords(ByteBuffer.wrap(buffer).getInt(0), ByteBuffer.wrap(buffer).getShort(4), ByteBuffer.wrap(buffer).getInt(6), ByteBuffer.wrap(buffer).getInt(10));
    int[] rgb = {ByteBuffer.wrap(buffer).get(14) - Byte.MIN_VALUE, ByteBuffer.wrap(buffer).get(15) - Byte.MIN_VALUE, ByteBuffer.wrap(buffer).get(16) - Byte.MIN_VALUE};
    this.integer = BW_ColorUtil.getColorFromRGBArray(rgb);
    this.removal = ByteBuffer.wrap(buffer).get(17);

    byte checksum = (byte) (this.coords.x % 25 + this.coords.y % 25 + this.coords.z % 25 + this.coords.wID % 25 + this.integer % 25 + this.removal);

    if (checksum != ByteBuffer.wrap(buffer).get(18)) {
        MainMod.LOGGER.error("BW Packet was corrupted or modified!");
        return null;
    }

    return new RendererPacket(this.coords, this.integer, this.removal == 1);
}
 
Example #12
Source File: PluginMessenger.java    From TAB with Apache License 2.0 6 votes vote down vote up
public void onPluginMessageReceived(String channel, Player player, byte[] bytes){
	if (!channel.equalsIgnoreCase(Shared.CHANNEL_NAME)) return;
	ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
	String subChannel = in.readUTF();
	if (subChannel.equalsIgnoreCase("Placeholder")){
		String placeholder = in.readUTF();
		long start = System.nanoTime();
		String output = PluginHooks.PlaceholderAPI_setPlaceholders(player, placeholder);
		long time = System.nanoTime() - start;

		ByteArrayDataOutput out = ByteStreams.newDataOutput();
		out.writeUTF("Placeholder");
		out.writeUTF(placeholder);
		out.writeUTF(output);
		out.writeLong(time);
		player.sendPluginMessage(plugin, Shared.CHANNEL_NAME, out.toByteArray());
	}
}
 
Example #13
Source File: PartiesPacket.java    From Parties with GNU Affero General Public License v3.0 6 votes vote down vote up
public static PartiesPacket read(ADPPlugin plugin, byte[] bytes) {
	PartiesPacket ret = null;
	try {
		ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
		String foundVersion = input.readUTF();
		
		if (foundVersion.equals(plugin.getVersion())) {
			PartiesPacket packet = new PartiesPacket(foundVersion);
			packet.type = PacketType.valueOf(input.readUTF());
			packet.partyName = input.readUTF();
			packet.playerUuid = UUID.fromString(input.readUTF());
			packet.payload = input.readUTF();
			ret = packet;
		} else {
			plugin.getLoggerManager().printError(Constants.DEBUG_LOG_MESSAGING_FAILED_VERSION
					.replace("{current}", plugin.getVersion())
					.replace("{version}", foundVersion));
		}
	} catch (Exception ex) {
		plugin.getLoggerManager().printError(Constants.DEBUG_LOG_MESSAGING_FAILED_READ
				.replace("{message}", ex.getMessage()));
	}
	return ret;
}
 
Example #14
Source File: SkyWarsReloaded.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
public void onPluginMessageReceived(String channel, Player player, byte[] message) {
	if (!channel.equals("BungeeCord")) {
		return;
    }
    ByteArrayDataInput in = ByteStreams.newDataInput(message);
    String subchannel = in.readUTF();
   
    if (subchannel.equals("GetServer")) {
    	servername = in.readUTF();
    }
    
    if (subchannel.equals("SWRMessaging")) {
    	short len = in.readShort();
    	byte[] msgbytes = new byte[len];
    	in.readFully(msgbytes);

    	DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes));
    	try {
			String header = msgin.readUTF();
			if (header.equalsIgnoreCase("RequestUpdate")) {
				String sendToServer = msgin.readUTF();
				String playerCount = "" + GameMap.getMaps().get(0).getAlivePlayers().size();
				String maxPlayers = "" + GameMap.getMaps().get(0).getMaxPlayers();
				String gameStarted = "" + GameMap.getMaps().get(0).getMatchState().toString();
				ArrayList<String> messages = new ArrayList<>();
				messages.add("ServerUpdate");
				messages.add(servername);
				messages.add(playerCount);
				messages.add(maxPlayers);
				messages.add(gameStarted);
				sendSWRMessage(player, sendToServer, messages);					
			}
		} catch (IOException e) {
			e.printStackTrace();
		} 
    }
}
 
Example #15
Source File: PacketBusFluidExport.java    From ExtraCells1 with MIT License 5 votes vote down vote up
@Override
public void read(ByteArrayDataInput in) throws ProtocolException
{
	world = DimensionManager.getWorld(in.readInt());
	x = in.readInt();
	y = in.readInt();
	z = in.readInt();
	playername = in.readUTF();
	action = in.readInt();
}
 
Example #16
Source File: CheckPermMessage.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void readFrom(ByteArrayDataInput in) {
    int rowId = in.readInt();
    String encodedData = in.readUTF();
    String encodedSignature = in.readUTF();

    targetSkin = SkinModel.createSkinFromEncoded(encodedData, encodedSignature);
    targetSkin.setRowId(rowId);

    //continue on success only
    receiverUUD = UUID.fromString(in.readUTF());
    skinPerm = in.readBoolean();
    isOp = in.readBoolean();
}
 
Example #17
Source File: PlayerSqlProtocol.java    From PlayerSQL with GNU General Public License v2.0 5 votes vote down vote up
public PlayerSqlProtocol decode(ByteArrayDataInput input) {
    DataSupply pk = new DataSupply();
    pk.setId(new UUID(input.readLong(), input.readLong()));
    pk.setGroup(input.readUTF());
    byte[] buf = new byte[input.readInt()];
    input.readFully(buf);
    pk.setBuf(buf);
    return pk;
}
 
Example #18
Source File: ForwardMessage.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void readFrom(ByteArrayDataInput in) {
    commandName = in.readUTF();
    args = in.readUTF();

    isSource = in.readBoolean();
    isOP = in.readBoolean();
}
 
Example #19
Source File: UpdateSkinListener.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void handlePayload(ChannelBuf data, RemoteConnection connection, Type side) {
    ByteArrayDataInput dataInput = ByteStreams.newDataInput(data.array());
    SkinUpdateMessage updateMessage = new SkinUpdateMessage();
    updateMessage.readFrom(dataInput);

    String playerName = updateMessage.getPlayerName();
    Optional<Player> receiver = Sponge.getServer().getPlayer(playerName);
    if (receiver.isPresent()) {
        Runnable skinUpdater = new SkinApplier(plugin, (CommandSource) connection, receiver.get(), null, false);
        Task.builder().execute(skinUpdater).submit(plugin);
    }
}
 
Example #20
Source File: CheckPermissionListener.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] data) {
    ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
    CheckPermMessage message = new CheckPermMessage();
    message.readFrom(dataInput);

    UUID receiverUUID = message.getReceiverUUD();
    boolean op = message.isOp();
    SkinModel targetSkin = message.getTargetSkin();
    UUID skinProfile = targetSkin.getProfileId();

    boolean success = op || checkBungeePerms(player, receiverUUID, message.isSkinPerm(), skinProfile);
    plugin.sendPluginMessage(player, new PermResultMessage(success, targetSkin, receiverUUID));
}
 
Example #21
Source File: SkinUpdateListener.java    From ChangeSkin with MIT License 5 votes vote down vote up
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] data) {
    ByteArrayDataInput dataInput = ByteStreams.newDataInput(data);
    SkinUpdateMessage updateMessage = new SkinUpdateMessage();
    updateMessage.readFrom(dataInput);

    String playerName = updateMessage.getPlayerName();
    Player receiver = Bukkit.getPlayerExact(playerName);
    if (receiver != null) {
        Bukkit.getScheduler().runTask(plugin, new SkinApplier(plugin, player, receiver, null, false));
    }
}
 
Example #22
Source File: TypedByteArrayComparator.java    From eagle with Apache License 2.0 5 votes vote down vote up
/**
 * For hbase 0.98
 *
 * @param bytes raw byte array
 * @return Comparator instance
 * @throws DeserializationException
 */
public static TypedByteArrayComparator parseFrom(final byte[] bytes) throws DeserializationException {
    TypedByteArrayComparator comparator = new TypedByteArrayComparator();
    ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(bytes);
    try {
        comparator.readFields(byteArrayDataInput);
    } catch (IOException e) {
        LOG.error("Got error to deserialize TypedByteArrayComparator from PB bytes", e);
        throw new DeserializationException(e);
    }
    return comparator;
}
 
Example #23
Source File: RowValueFilter.java    From Eagle with Apache License 2.0 5 votes vote down vote up
/**
 * TODO: Currently still use older serialization method from hbase-0.94, need to migrate into ProtoBuff based
 */
// Override static method
public static Filter parseFrom(final byte [] pbBytes) throws DeserializationException {
    ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(pbBytes);
    RowValueFilter filter = new RowValueFilter();
    try {
        filter.readFields(byteArrayDataInput);
    } catch (IOException e) {
        LOG.error("Got error to deserialize RowValueFilter from PB bytes",e);
        throw new DeserializationException(e);
    }
    return filter;
}
 
Example #24
Source File: MoCEntityGolem.java    From mocreaturesdev with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void readSpawnData(ByteArrayDataInput data)
{
    for (int i = 0; i < 23; i++)
    {
        golemCubes[i] = data.readByte();
    }
}
 
Example #25
Source File: PacketBusFluidStorage.java    From ExtraCells1 with MIT License 5 votes vote down vote up
@Override
public void read(ByteArrayDataInput in) throws ProtocolException
{
	world = DimensionManager.getWorld(in.readInt());
	x = in.readInt();
	y = in.readInt();
	z = in.readInt();
	priority = in.readInt();
}
 
Example #26
Source File: RowValueFilter.java    From eagle with Apache License 2.0 5 votes vote down vote up
/**
 * TODO: Currently still use older serialization method from hbase-0.94, need to migrate into ProtoBuff
 * based
 */
// Override static method
public static Filter parseFrom(final byte[] pbBytes) throws DeserializationException {
    ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(pbBytes);
    RowValueFilter filter = new RowValueFilter();
    try {
        filter.readFields(byteArrayDataInput);
    } catch (IOException e) {
        LOG.error("Got error to deserialize RowValueFilter from PB bytes", e);
        throw new DeserializationException(e);
    }
    return filter;
}
 
Example #27
Source File: ConstantPoolReader.java    From turbine with Apache License 2.0 5 votes vote down vote up
/** Reads the CONSTANT_Module_info at the given index. */
public String moduleInfo(int index) {
  ByteArrayDataInput reader = byteReader.seek(constantPool[index - 1]);
  byte tag = reader.readByte();
  if (tag != CONSTANT_MODULE) {
    throw new AssertionError(String.format("bad tag: %x", tag));
  }
  int nameIndex = reader.readUnsignedShort();
  return utf8(nameIndex);
}
 
Example #28
Source File: BungeeReceiver.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Processes the given data input and attempts to translate it to a message for the "AuthMe.v2.Broadcast" channel.
 *
 * @param in the input to handle
 */
private void handleBroadcast(final ByteArrayDataInput in) {
    // Read data byte array
    final short dataLength = in.readShort();
    final byte[] dataBytes = new byte[dataLength];
    in.readFully(dataBytes);
    final ByteArrayDataInput dataIn = ByteStreams.newDataInput(dataBytes);

    // Parse type
    final String typeId = dataIn.readUTF();
    final Optional<MessageType> type = MessageType.fromId(typeId);
    if (!type.isPresent()) {
        logger.debug("Received unsupported forwarded bungeecord message type! ({0})", typeId);
        return;
    }

    // Parse argument
    final String argument;
    try {
        argument = dataIn.readUTF();
    } catch (IllegalStateException e) {
        logger.warning("Received invalid forwarded plugin message of type " + type.get().name()
            + ": argument is missing!");
        return;
    }

    // Handle type
    switch (type.get()) {
        case UNREGISTER:
            dataSource.invalidateCache(argument);
            break;
        case REFRESH_PASSWORD:
        case REFRESH_QUITLOC:
        case REFRESH_EMAIL:
        case REFRESH:
            dataSource.refreshCache(argument);
            break;
        default:
    }
}
 
Example #29
Source File: ConstantPoolReader.java    From turbine with Apache License 2.0 5 votes vote down vote up
/** Reads the CONSTANT_Class_info at the given index. */
public String classInfo(int index) {
  ByteArrayDataInput reader = byteReader.seek(constantPool[index - 1]);
  byte tag = reader.readByte();
  if (tag != CONSTANT_CLASS) {
    throw new AssertionError(String.format("bad tag: %x", tag));
  }
  int nameIndex = reader.readUnsignedShort();
  return utf8(nameIndex);
}
 
Example #30
Source File: NickNamerPlugin.java    From NickNamer with MIT License 5 votes vote down vote up
@Override
public void onPluginMessageReceived(String s, Player player, byte[] bytes) {
	if (!bungeecord) { return; }
	if (channelIdentifier.equals(s)) {
		ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
		String sub = in.readUTF();
		UUID who = UUID.fromString(in.readUTF());
		if ("name".equals(sub)) {
			String name = in.readUTF();

			if (name == null || "reset".equals(name)) {
				getAPI().removeNick(who);
			} else {
				getAPI().setNick(who, name);
			}
		} else if ("skin".equals(sub)) {
			String skin = in.readUTF();

			if (skin == null || "reset".equals(skin)) {
				getAPI().removeSkin(who);
			} else {
				getAPI().setSkin(who, skin);
			}
		} else if ("data".equals(sub)) {
			try {
				String owner = in.readUTF();
				JsonObject data = new JsonParser().parse(in.readUTF()).getAsJsonObject();
				SkinLoaderBridge.getSkinProvider().put(owner, new GameProfileWrapper(data).toJson());
			} catch (JsonParseException e) {
				e.printStackTrace();
			}
		} else {
			getLogger().warning("Unknown incoming plugin message: " + sub);
		}
	}
}