@Override
  public void onPacketOut(Object packet, Player player) {
    GameProfile profile =
        (GameProfile)
            ReflectionUtils.getPrivateField(
                PACKET_CLASS,
                ReflectionUtils.byClass(PACKET_CLASS, GameProfile.class).getName(),
                packet);

    if (playerHandlers.containsKey(profile.getId())) playerHandlers.remove(profile.getId());

    PlayerHandler handler = new PlayerHandler(player);
    handler.setChannel(super.channel);

    playerHandlers.put(profile.getId(), handler);
  }
 private boolean canRidePlayer(EntityPlayer player) {
   final GameProfile owner = minime.getOwner();
   return owner != null
       && player != null
       && player.getGameProfile().getId().equals(owner.getId())
       && player.ridingEntity == null;
 }
  @Mod.EventHandler
  public void postInit(FMLPostInitializationEvent event) {
    BCLog.logger.info(
        "BuildCraft's fake player: UUID = "
            + gameProfile.getId().toString()
            + ", name = '"
            + gameProfile.getName()
            + "'!");

    for (Object o : Block.blockRegistry) {
      Block block = (Block) o;

      if (block instanceof BlockFluidBase
          || block instanceof BlockLiquid
          || block instanceof IPlantable) {
        BuildCraftAPI.softBlocks.add(block);
      }
    }

    BuildCraftAPI.softBlocks.add(Blocks.snow);
    BuildCraftAPI.softBlocks.add(Blocks.vine);
    BuildCraftAPI.softBlocks.add(Blocks.fire);
    BuildCraftAPI.softBlocks.add(Blocks.air);

    FMLCommonHandler.instance().bus().register(new TickHandlerCore());

    CropManager.setDefaultHandler(new CropHandlerPlantable());
    CropManager.registerHandler(new CropHandlerReeds());

    BuildCraftAPI.registerWorldProperty("soft", new WorldPropertyIsSoft());
    BuildCraftAPI.registerWorldProperty("wood", new WorldPropertyIsWood());
    BuildCraftAPI.registerWorldProperty("leaves", new WorldPropertyIsLeaf());
    for (int i = 0; i < 4; i++) {
      BuildCraftAPI.registerWorldProperty("ore@hardness=" + i, new WorldPropertyIsOre(i));
    }
    BuildCraftAPI.registerWorldProperty("harvestable", new WorldPropertyIsHarvestable());
    BuildCraftAPI.registerWorldProperty("farmland", new WorldPropertyIsFarmland());
    BuildCraftAPI.registerWorldProperty("shoveled", new WorldPropertyIsShoveled());
    BuildCraftAPI.registerWorldProperty("dirt", new WorldPropertyIsDirt());
    BuildCraftAPI.registerWorldProperty("fluidSource", new WorldPropertyIsFluidSource());

    ColorUtils.initialize();

    actionControl = new IActionExternal[IControllable.Mode.values().length];
    for (IControllable.Mode mode : IControllable.Mode.values()) {
      if (mode != IControllable.Mode.Unknown && mode != IControllable.Mode.Mode) {
        actionControl[mode.ordinal()] = new ActionMachineControl(mode);
      }
    }
  }
  public void initializeConnectionToPlayer(NetworkManager netManager, EntityPlayerMP playerIn) {
    GameProfile var3 = playerIn.getGameProfile();
    PlayerProfileCache var4 = this.mcServer.getPlayerProfileCache();
    GameProfile var5 = var4.func_152652_a(var3.getId());
    String var6 = var5 == null ? var3.getName() : var5.getName();
    var4.func_152649_a(var3);
    NBTTagCompound var7 = this.readPlayerDataFromFile(playerIn);
    playerIn.setWorld(this.mcServer.worldServerForDimension(playerIn.dimension));
    playerIn.theItemInWorldManager.setWorld((WorldServer) playerIn.worldObj);
    String var8 = "local";

    if (netManager.getRemoteAddress() != null) {
      var8 = netManager.getRemoteAddress().toString();
    }

    logger.info(
        playerIn.getName()
            + "["
            + var8
            + "] logged in with entity id "
            + playerIn.getEntityId()
            + " at ("
            + playerIn.posX
            + ", "
            + playerIn.posY
            + ", "
            + playerIn.posZ
            + ")");
    WorldServer var9 = this.mcServer.worldServerForDimension(playerIn.dimension);
    WorldInfo var10 = var9.getWorldInfo();
    BlockPos var11 = var9.getSpawnPoint();
    this.func_72381_a(playerIn, (EntityPlayerMP) null, var9);
    NetHandlerPlayServer var12 = new NetHandlerPlayServer(this.mcServer, netManager, playerIn);
    var12.sendPacket(
        new S01PacketJoinGame(
            playerIn.getEntityId(),
            playerIn.theItemInWorldManager.getGameType(),
            var10.isHardcoreModeEnabled(),
            var9.provider.getDimensionId(),
            var9.getDifficulty(),
            this.getMaxPlayers(),
            var10.getTerrainType(),
            var9.getGameRules().getGameRuleBooleanValue("reducedDebugInfo")));
    var12.sendPacket(
        new S3FPacketCustomPayload(
            "MC|Brand",
            (new PacketBuffer(Unpooled.buffer()))
                .writeString(this.getServerInstance().getServerModName())));
    var12.sendPacket(
        new S41PacketServerDifficulty(var10.getDifficulty(), var10.isDifficultyLocked()));
    var12.sendPacket(new S05PacketSpawnPosition(var11));
    var12.sendPacket(new S39PacketPlayerAbilities(playerIn.capabilities));
    var12.sendPacket(new S09PacketHeldItemChange(playerIn.inventory.currentItem));
    playerIn.getStatFile().func_150877_d();
    playerIn.getStatFile().func_150884_b(playerIn);
    this.func_96456_a((ServerScoreboard) var9.getScoreboard(), playerIn);
    this.mcServer.refreshStatusNextTick();
    ChatComponentTranslation var13;

    if (!playerIn.getName().equalsIgnoreCase(var6)) {
      var13 =
          new ChatComponentTranslation(
              "multiplayer.player.joined.renamed", new Object[] {playerIn.getDisplayName(), var6});
    } else {
      var13 =
          new ChatComponentTranslation(
              "multiplayer.player.joined", new Object[] {playerIn.getDisplayName()});
    }

    var13.getChatStyle().setColor(EnumChatFormatting.YELLOW);
    this.sendChatMsg(var13);
    this.playerLoggedIn(playerIn);
    var12.setPlayerLocation(
        playerIn.posX, playerIn.posY, playerIn.posZ, playerIn.rotationYaw, playerIn.rotationPitch);
    this.updateTimeAndWeatherForPlayer(playerIn, var9);

    if (this.mcServer.getResourcePackUrl().length() > 0) {
      playerIn.func_175397_a(
          this.mcServer.getResourcePackUrl(), this.mcServer.getResourcePackHash());
    }

    Iterator var14 = playerIn.getActivePotionEffects().iterator();

    while (var14.hasNext()) {
      PotionEffect var15 = (PotionEffect) var14.next();
      var12.sendPacket(new S1DPacketEntityEffect(playerIn.getEntityId(), var15));
    }

    playerIn.addSelfToInternalCraftingInventory();

    if (var7 != null && var7.hasKey("Riding", 10)) {
      Entity var16 = EntityList.createEntityFromNBT(var7.getCompoundTag("Riding"), var9);

      if (var16 != null) {
        var16.forceSpawn = true;
        var9.spawnEntityInWorld(var16);
        playerIn.mountEntity(var16);
        var16.forceSpawn = false;
      }
    }
  }
  protected static LoginResponse authenticateWithAuthlib(
      String user, String pass, String mojangData, String selectedProfileName) {
    String displayName;
    boolean hasMojangData = false;
    boolean hasPassword = false;
    GameProfile selectedProfile = null;
    YggdrasilUserAuthentication authentication =
        (YggdrasilUserAuthentication)
            new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1")
                .createUserAuthentication(Agent.MINECRAFT);
    if (user != null) {
      Logger.logDebug(
          user.contains("@")
              ? "Email address given"
              : "Username given" + " Not 100% sure, mojangdata might contain different username");
      Logger.logInfo("Beginning authlib authentication attempt");
      Logger.logInfo("successfully created YggdrasilAuthenticationService");
      authentication.setUsername(user);
      if (pass != null && !pass.isEmpty()) {
        authentication.setPassword(pass);
        hasPassword = true;
      }
      if (mojangData != null && !mojangData.isEmpty()) {
        Logger.logDebug("mojangData was passed to current method");
        Map<String, Object> m = decode(mojangData);
        if (m != null) {
          Logger.logDebug("Loading mojangData into authlib");
          authentication.loadFromStorage(m);
          hasMojangData = true;
        }
      } else {
        Logger.logDebug("mojangData is null or empty");
      }
      if (authentication.canLogIn()) {
        try {
          authentication.logIn();
        } catch (UserMigratedException e) {
          Logger.logError(e.toString());
          ErrorUtils.tossError(
              "Invalid credentials, please make sure to login with your Mojang account.");
          return null;
        } catch (InvalidCredentialsException e) {
          Logger.logError("Invalid credentials recieved for user: "******"Invalid username or password.");
            return null;
          }
        } catch (AuthenticationUnavailableException e) {
          Logger.logDebug("Error while authenticating, trying offline mode");
          if (hasMojangData) {
            // if the UUID is valid we can proceed to offline mode later
            uniqueID = authentication.getSelectedProfile().getId().toString();
            if (uniqueID != null && !uniqueID.isEmpty()) Logger.logDebug("Setting UUID");
            UserManager.setUUID(user, uniqueID);
          }
          if (uniqueID != null && !uniqueID.isEmpty()) {
            UserManager.setUUID(user, uniqueID);
            Logger.logDebug("Setting UUID and creating and returning new LoginResponse");
            return new LoginResponse(
                Integer.toString(authentication.getAgent().getVersion()),
                "token",
                user,
                null,
                uniqueID,
                authentication);
          }
          ErrorUtils.tossError(
              "Exception occurred, minecraft servers might be down. Check @ help.mojang.com");
          Logger.logDebug("failed", e);
          Logger.logDebug("AuthenticationUnavailableException caused by", e.getCause());
          return null;
        } catch (AuthenticationException e) {
          Logger.logError("Unknown error from authlib:", e);
        } catch (Exception e) {
          Logger.logError("Unknown authentication error occurred", e);
        }
      } else {
        Logger.logDebug("authentication.canLogIn() returned false");
      }

      if (isValid(authentication)) {
        Logger.logDebug("Authentication is valid ");
        displayName = authentication.getSelectedProfile().getName();
        if ((authentication.isLoggedIn()) && (authentication.canPlayOnline())) {
          Logger.logDebug("loggedIn() && CanPlayOnline()");
          if ((authentication instanceof YggdrasilUserAuthentication)) {
            UserManager.setStore(user, encode(authentication.saveForStorage()));
            UserManager.setUUID(
                user,
                authentication
                    .getSelectedProfile()
                    .getId()
                    .toString()); // enables use of offline mode later if needed on newer MC
            // Versions
            Logger.logDebug("Authentication done, returning LoginResponse");
            return new LoginResponse(
                Integer.toString(authentication.getAgent().getVersion()),
                "token",
                displayName,
                authentication.getAuthenticatedToken(),
                authentication.getSelectedProfile().getId().toString(),
                authentication);
          }
        }
        Logger.logDebug(
            "this should never happen: isLoggedIn: "
                + authentication.isLoggedIn()
                + " canPlayOnline(): "
                + authentication.canPlayOnline());
      } else if (authentication.getSelectedProfile() == null
          && (authentication.getAvailableProfiles() != null
              && authentication.getAvailableProfiles().length != 0)) {
        // user has more than one profile
        Logger.logDebug("User has more than one profile: " + toString(authentication));
        for (GameProfile profile : authentication.getAvailableProfiles()) {
          if (selectedProfileName.equals(profile.getName())) {
            Logger.logInfo("Selected profile: " + profile.getName());
            selectedProfile = profile;
          }
        }
        if (selectedProfile == null) {
          Logger.logInfo("Profile not found, defaulting to first");
          selectedProfile = authentication.getAvailableProfiles()[0];
        }
        Logger.logDebug("Authentication done, returning LoginResponse");
        return new LoginResponse(
            Integer.toString(authentication.getAgent().getVersion()),
            "token",
            selectedProfile.getName(),
            authentication.getAuthenticatedToken(),
            selectedProfile.getId().toString(),
            authentication);
      } else if (authentication.getSelectedProfile() == null
          && (authentication.getAvailableProfiles() != null
              && authentication.getAvailableProfiles().length == 0)) {
        Logger.logDebug("No profiles in mojang account: " + toString(authentication));
        ErrorUtils.showClickableMessage(
            "You need to own minecraft to play FTB Modpacks",
            "https://help.mojang.com/customer/portal/articles/1218766-can-only-play-minecraft-demo");
        return null;
      } else {
        Logger.logDebug("this should never happen: " + toString(authentication));
      }

    } else {
      Logger.logDebug("this should never happen");
    }

    if (hasMojangData) {
      Logger.logError(
          "Failed to authenticate with mojang data, attempting to use username & password");
      if (!hasPassword) {
        new PasswordDialog(LaunchFrame.getInstance(), true).setVisible(true);
        if (LaunchFrame.tempPass.isEmpty()) return null;
        pass = LaunchFrame.tempPass;
      }

      LoginResponse l = authenticateWithAuthlib(user, pass, null, selectedProfileName);
      if (l == null) {
        Logger.logError("Failed to login with username & password");
        return null;
      } else {
        Logger.logDebug("authentication ready, returning LoginResponse from authlib");
        return l;
      }
    }
    Logger.logError("Failed to authenticate");
    return null;
  }