de.mineformers.powergrid.network.packet.BasePacket.java Source code

Java tutorial

Introduction

Here is the source code for de.mineformers.powergrid.network.packet.BasePacket.java

Source

package de.mineformers.powergrid.network.packet;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.packet.Packet;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;

import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
import de.mineformers.powergrid.PowerGrid;

/**
 * 
 * PowerGrid
 * 
 * BasePacket
 * 
 * @author PaleoCrafter
 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
 * 
 */
public abstract class BasePacket {
    private static final BiMap<Integer, Class<? extends BasePacket>> idMap;
    private static int lastId = 0;

    static {
        idMap = HashBiMap.create();
    }

    public static BasePacket constructPacket(int packetId)
            throws ProtocolException, InstantiationException, IllegalAccessException {
        Class<? extends BasePacket> clazz = idMap.get(Integer.valueOf(packetId));
        if (clazz == null) {
            throw new ProtocolException("Unknown Packet Id!");
        } else {
            return clazz.newInstance();
        }
    }

    @SuppressWarnings("serial")
    public static class ProtocolException extends Exception {

        public ProtocolException() {
        }

        public ProtocolException(String message, Throwable cause) {
            super(message, cause);
        }

        public ProtocolException(String message) {
            super(message);
        }

        public ProtocolException(Throwable cause) {
            super(cause);
        }
    }

    public final int getPacketId() {
        if (idMap.inverse().containsKey(getClass())) {
            return idMap.inverse().get(getClass()).intValue();
        } else {
            throw new RuntimeException("Packet " + getClass().getSimpleName() + " is missing a mapping!");
        }
    }

    public final Packet makePacket() {
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeByte(getPacketId());
        write(out);
        return PacketDispatcher.getPacket(PowerGrid.CHANNEL_NAME, out.toByteArray());
    }

    public static final void registerPacket(Class<? extends BasePacket> packet) {
        idMap.put(lastId, packet);
        lastId += 1;
    }

    public abstract void write(ByteArrayDataOutput out);

    public abstract void read(ByteArrayDataInput in);

    public abstract void execute(EntityPlayer player, Side side);
}