예제 #1
0
 private boolean parseAndPublishItem(L2PcInstance owner) {
   int pos1 = -1;
   while ((pos1 = _text.indexOf(8, pos1)) > -1) {
     int pos = _text.indexOf("ID=", pos1);
     if (pos == -1) return false;
     StringBuilder result = new StringBuilder(9);
     pos += 3;
     while (Character.isDigit(_text.charAt(pos))) result.append(_text.charAt(pos++));
     int id = Integer.parseInt(result.toString());
     L2Object item = L2World.getInstance().findObject(id);
     if (item instanceof L2ItemInstance) {
       if (owner.getInventory().getItemByObjectId(id) == null) {
         _log.info(getClient() + " trying publish item which doesnt own! ID:" + id);
         return false;
       }
       ((L2ItemInstance) item).publish();
     } else {
       _log.info(getClient() + " trying publish object which is not item! Object:" + item);
       return false;
     }
     pos1 = _text.indexOf(8, pos) + 1;
     if (pos1 == 0) // missing ending tag
     {
       _log.info(getClient() + " sent invalid publish item msg! ID:" + id);
       return false;
     }
   }
   return true;
 }
예제 #2
0
  /** Get back items in container from database */
  public void restore() {
    Connection con = null;
    try {
      con = L2DatabaseFactory.getInstance().getConnection();
      PreparedStatement statement =
          con.prepareStatement(
              "SELECT object_id, item_id, count, enchant_level, loc, loc_data, custom_type1, custom_type2, mana_left, time FROM items WHERE owner_id=? AND (loc=?)");
      statement.setInt(1, getOwnerId());
      statement.setString(2, getBaseLocation().name());
      ResultSet inv = statement.executeQuery();

      L2ItemInstance item;
      while (inv.next()) {
        item = L2ItemInstance.restoreFromDb(getOwnerId(), inv);
        if (item == null) continue;

        L2World.getInstance().storeObject(item);

        L2PcInstance owner = getOwner() == null ? null : getOwner().getActingPlayer();

        // If stackable item is found in inventory just add to current quantity
        if (item.isStackable() && getItemByItemId(item.getItemId()) != null)
          addItem("Restore", item, owner, null);
        else addItem(item);
      }

      inv.close();
      statement.close();
      refreshWeight();
    } catch (Exception e) {
      _log.log(Level.WARNING, "could not restore container:", e);
    } finally {
      L2DatabaseFactory.close(con);
    }
  }
예제 #3
0
  public void setReenterTime(InstanceWorld world) {
    if (world instanceof DPFWorld) {
      // Reenter time should be cleared every Wed and Sat at 6:30 AM, so we set next suitable
      Calendar reenter;
      Calendar now = Calendar.getInstance();
      Calendar reenterPointWed = (Calendar) now.clone();
      reenterPointWed.set(Calendar.AM_PM, Calendar.AM);
      reenterPointWed.set(Calendar.MINUTE, RESET_MIN);
      reenterPointWed.set(Calendar.HOUR_OF_DAY, RESET_HOUR);
      reenterPointWed.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
      Calendar reenterPointSat = (Calendar) reenterPointWed.clone();
      reenterPointSat.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);

      if (now.after(reenterPointSat)) {
        reenterPointWed.add(Calendar.WEEK_OF_MONTH, 1);
        reenter = (Calendar) reenterPointWed.clone();
      } else {
        reenter = (Calendar) reenterPointSat.clone();
      }

      SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.INSTANT_ZONE_S1_RESTRICTED);
      sm.addInstanceName(world.getTemplateId());
      // set instance reenter time for all allowed players
      for (int objectId : world.getAllowed()) {
        L2PcInstance player = L2World.getInstance().getPlayer(objectId);
        if ((player != null) && player.isOnline()) {
          InstanceManager.getInstance()
              .setInstanceTime(objectId, world.getTemplateId(), reenter.getTimeInMillis());
          player.sendPacket(sm);
        }
      }
    }
  }
예제 #4
0
 @Override
 public void run() {
   GrandBossManager.getInstance().setBossStatus(_bossId, DORMANT);
   if (FWA_DOSERVEREARTHQUAKE) {
     for (L2PcInstance p : L2World.getInstance().getAllPlayersArray()) {
       p.broadcastPacket(new Earthquake(185708, 114298, -8221, 20, 10));
     }
   }
 }
예제 #5
0
  protected void handleRemoveBuffs(InstanceWorld world) {
    for (int objId : world.getAllowed()) {
      final L2PcInstance player = L2World.getInstance().getPlayer(objId);

      if (player != null) {
        handleRemoveBuffs(player, world);
      }
    }
  }
예제 #6
0
  /** Delete item object from world */
  public void deleteMe() {
    try {
      updateDatabase();
    } catch (Exception e) {
      _log.log(Level.SEVERE, "deletedMe()", e);
    }
    List<L2Object> items = new FastList<L2Object>(_items);
    _items.clear();

    L2World.getInstance().removeObjects(items);
  }
예제 #7
0
  @Override
  protected void runImpl() {
    final L2PcInstance player = getClient().getActiveChar();
    if (player == null) return;

    final TradeList trade = player.getActiveTradeList();
    if (trade == null) {
      _log.warning(
          "Character: "
              + player.getName()
              + " requested item:"
              + _objectId
              + " add without active tradelist:"
              + _tradeId);
      return;
    }

    final L2PcInstance partner = trade.getPartner();
    if (partner == null
        || L2World.getInstance().getPlayer(partner.getObjectId()) == null
        || partner.getActiveTradeList() == null) {
      // Trade partner not found, cancel trade
      if (partner != null)
        _log.warning(
            "Character:" + player.getName() + " requested invalid trade object: " + _objectId);
      SystemMessage msg = new SystemMessage(SystemMessageId.TARGET_IS_NOT_FOUND_IN_THE_GAME);
      player.sendPacket(msg);
      player.cancelActiveTrade();
      return;
    }

    if (trade.isConfirmed() || partner.getActiveTradeList().isConfirmed()) {
      player.sendPacket(
          new SystemMessage(SystemMessageId.CANNOT_ADJUST_ITEMS_AFTER_TRADE_CONFIRMED));
      return;
    }

    if (!player.getAccessLevel().allowTransaction()) {
      player.sendMessage("Transactions are disable for your Access Level");
      player.cancelActiveTrade();
      return;
    }

    if (!player.validateItemManipulation(_objectId, "trade")) {
      player.sendPacket(new SystemMessage(SystemMessageId.NOTHING_HAPPENED));
      return;
    }

    final TradeList.TradeItem item = trade.addItem(_objectId, _count);
    if (item != null) {
      player.sendPacket(new TradeOwnAdd(item));
      trade.getPartner().sendPacket(new TradeOtherAdd(item));
    }
  }
예제 #8
0
 public void deleteCouple(int coupleId) {
   int index = getCoupleIndex(coupleId);
   Couple couple = getCouples().get(index);
   if (couple != null) {
     L2PcInstance player1 = L2World.getInstance().getPlayer(couple.getPlayer1Id());
     L2PcInstance player2 = L2World.getInstance().getPlayer(couple.getPlayer2Id());
     if (player1 != null) {
       player1.setPartnerId(0);
       player1.setMarried(false);
       player1.setCoupleId(0);
     }
     if (player2 != null) {
       player2.setPartnerId(0);
       player2.setMarried(false);
       player2.setCoupleId(0);
     }
     couple.divorce();
     getCouples().remove(index);
   }
 }
  public ChangePasswordResponse(byte[] decrypt) {
    super(decrypt);
    // boolean isSuccessful = readC() > 0;
    String character = readS();
    String msgToSend = readS();

    L2PcInstance player = L2World.getInstance().getPlayer(character);

    if (player != null) {
      player.sendMessage(msgToSend);
    }
  }
예제 #10
0
  final void onAuctionFinished(final ItemAuction auction) {
    auction.broadcastToAllBiddersInternal(
        new SystemMessage(SystemMessageId.S1_AUCTION_ENDED).addNumber(auction.getAuctionId()));

    final ItemAuctionBid bid = auction.getHighestBid();
    if (bid != null) {
      final L2ItemInstance item = auction.createNewItemInstance();
      final L2PcInstance player = bid.getPlayer();
      if (player != null) {
        player.getWarehouse().addItem("ItemAuction", item, null, null);
        player.sendPacket(
            new SystemMessage(SystemMessageId.WON_BID_ITEM_CAN_BE_FOUND_IN_WAREHOUSE));

        _log.log(
            Level.INFO,
            "L2ItemAuctionInstance: Auction "
                + auction.getAuctionId()
                + " has finished. Highest bid by "
                + player.getName()
                + " for instance "
                + _instanceId);
      } else {
        item.setOwnerId(bid.getPlayerObjId());
        item.setLocation(ItemLocation.WAREHOUSE);
        item.updateDatabase();
        L2World.getInstance().removeObject(item);

        _log.log(
            Level.INFO,
            "L2ItemAuctionInstance: Auction "
                + auction.getAuctionId()
                + " has finished. Highest bid by "
                + CharNameTable.getInstance().getNameById(bid.getPlayerObjId())
                + " for instance "
                + _instanceId);
      }

      // Clean all canceled bids
      auction.clearCanceledBids();
    } else {
      _log.log(
          Level.INFO,
          "L2ItemAuctionInstance: Auction "
              + auction.getAuctionId()
              + " has finished. There have not been any bid for instance "
              + _instanceId);
    }
  }
예제 #11
0
  @Override
  public boolean useAdminCommand(String command, L2PcInstance activeChar) {
    String[] parts = command.split(" ");
    if (parts.length == 2) {
      try {
        int lvl = Integer.parseInt(parts[1]);
        if (activeChar.getTarget() instanceof L2PcInstance) {
          onlineChange(activeChar, (L2PcInstance) activeChar.getTarget(), lvl);
        } else {
          activeChar.sendPacket(SystemMessageId.INCORRECT_TARGET);
        }
      } catch (Exception e) {
        activeChar.sendMessage("Usage: //changelvl <target_new_level> | <player_name> <new_level>");
      }
    } else if (parts.length == 3) {
      String name = parts[1];
      int lvl = Integer.parseInt(parts[2]);
      L2PcInstance player = L2World.getInstance().getPlayer(name);
      if (player != null) {
        onlineChange(activeChar, player, lvl);
      } else {
        try (Connection con = ConnectionFactory.getInstance().getConnection();
            PreparedStatement ps =
                con.prepareStatement("UPDATE characters SET accesslevel=? WHERE char_name=?")) {
          ps.setInt(1, lvl);
          ps.setString(2, name);
          ps.execute();

          if (ps.getUpdateCount() == 0) {
            activeChar.sendMessage("角色不在线或者权限等级没有变化.");
          } else {
            activeChar.sendMessage("将角色的权限等级谁定为 " + lvl);
          }
        } catch (SQLException se) {
          activeChar.sendMessage("角色权限等级变化时SQL异常");
          if (Config.DEBUG) {
            se.printStackTrace();
          }
        }
      }
    }
    return true;
  }
 @Override
 protected void runImpl() {
   L2GameClient client = getClient();
   if (client != null) {
     L2Object object = L2World.getInstance().findObject(_objectId);
     if (object instanceof L2ItemInstance) {
       L2ItemInstance item = (L2ItemInstance) object;
       if (item.isPublished()) {
         client.sendPacket(new ExRpItemLink(item));
       } else {
         if (Config.DEBUG) {
           _log.info(
               getClient()
                   + " requested item link for item which wasnt published! ID:"
                   + _objectId);
         }
       }
     }
   }
 }
  @Override
  protected void runImpl() {
    final L2PcInstance activeChar = getClient().getActiveChar();

    if ((activeChar == null) || (activeChar.getClan() != null)) {
      return;
    }

    final L2Clan clan = ClanTable.getInstance().getClan(_clanId);

    if (clan == null) {
      return;
    }

    final PledgeApplicantInfo info =
        new PledgeApplicantInfo(
            activeChar.getObjectId(),
            activeChar.getName(),
            activeChar.getLevel(),
            _karma,
            _clanId,
            _message);

    if (ClanEntryManager.getInstance().addPlayerApplicationToClan(_clanId, info)) {
      activeChar.sendPacket(new ExPledgeRecruitApplyInfo(ClanEntryStatus.WAITING));

      final L2PcInstance clanLeader = L2World.getInstance().getPlayer(clan.getLeaderId());

      if (clanLeader != null) {
        clanLeader.sendPacket(ExPledgeWaitingListAlarm.STATIC_PACKET);
      }
    } else {
      final SystemMessage sm =
          SystemMessage.getSystemMessage(
              SystemMessageId
                  .YOU_MAY_APPLY_FOR_ENTRY_AFTER_S1_MINUTE_S_DUE_TO_CANCELLING_YOUR_APPLICATION);
      sm.addLong(ClanEntryManager.getInstance().getPlayerLockTime(activeChar.getObjectId()));
      activeChar.sendPacket(sm);
    }
  }
예제 #14
0
  /**
   * Sets reenter time for every player in the instance.
   *
   * @param world the instance
   * @param time the time in milliseconds
   */
  protected void setReenterTime(InstanceWorld world, long time) {
    for (int objectId : world.getAllowed()) {
      InstanceManager.getInstance().setInstanceTime(objectId, world.getTemplateId(), time);
      final L2PcInstance player = L2World.getInstance().getPlayer(objectId);
      if ((player != null) && player.isOnline()) {
        player.sendPacket(
            SystemMessage.getSystemMessage(
                    SystemMessageId
                        .INSTANT_ZONE_S1_S_ENTRY_HAS_BEEN_RESTRICTED_YOU_CAN_CHECK_THE_NEXT_POSSIBLE_ENTRY_TIME_BY_USING_THE_COMMAND_INSTANCEZONE)
                .addString(
                    InstanceManager.getInstance().getInstance(world.getInstanceId()).getName()));
      }
    }

    if (Config.DEBUG_INSTANCES) {
      _log.info(
          "Time restrictions has been set for player in instance ID: "
              + world.getInstanceId()
              + " ("
              + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
              + ")");
    }
  }
예제 #15
0
  @Override
  protected void runImpl() {
    L2PcInstance activeChar = getClient().getActiveChar();
    if (activeChar == null) {
      return;
    }

    L2PcInstance ob = L2World.getInstance().getPlayer(_id);

    if (ob == null) {
      activeChar.sendPacket(new SystemMessage(SystemMessageId.YOU_HAVE_INVITED_THE_WRONG_TARGET));
      return;
    }

    if (activeChar.getClan() == null) {
      activeChar.sendPacket(new SystemMessage(SystemMessageId.YOU_ARE_NOT_A_CLAN_MEMBER));
      return;
    }

    L2PcInstance target = ob;
    L2Clan clan = activeChar.getClan();
    if (!clan.checkAllyJoinCondition(activeChar, target)) {
      return;
    }
    if (!activeChar.getRequest().setRequest(target, this)) {
      return;
    }

    SystemMessage sm =
        new SystemMessage(SystemMessageId.S2_ALLIANCE_LEADER_OF_S1_REQUESTED_ALLIANCE);
    sm.addString(activeChar.getClan().getAllyName());
    sm.addString(activeChar.getName());
    target.sendPacket(sm);
    sm = null;
    AskJoinAlly aja = new AskJoinAlly(activeChar.getObjectId(), activeChar.getClan().getAllyName());
    target.sendPacket(aja);
  }
  public String getServerStatus() {
    int playerCount = 0, objectCount = 0;
    int max = LoginServerThread.getInstance().getMaxPlayer();

    playerCount = L2World.getInstance().getAllPlayersCount();
    objectCount = L2World.getInstance().getVisibleObjectsCount();

    int itemCount = 0;
    int itemVoidCount = 0;
    int monsterCount = 0;
    int minionCount = 0;
    int minionsGroupCount = 0;
    int npcCount = 0;
    int charCount = 0;
    int pcCount = 0;
    int detachedCount = 0;
    int doorCount = 0;
    int summonCount = 0;
    int AICount = 0;

    for (L2Object obj : L2World.getInstance().getVisibleObjects()) {
      if (obj == null) {
        continue;
      }
      if (obj instanceof L2Character) {
        if (((L2Character) obj).hasAI()) {
          AICount++;
        }
      }
      if (obj instanceof L2ItemInstance) {
        if (((L2ItemInstance) obj).getItemLocation() == ItemLocation.VOID) {
          itemVoidCount++;
        } else {
          itemCount++;
        }
      } else if (obj instanceof L2MonsterInstance) {
        monsterCount++;
        if (((L2MonsterInstance) obj).hasMinions()) {
          minionCount += ((L2MonsterInstance) obj).getMinionList().countSpawnedMinions();
          minionsGroupCount +=
              ((L2MonsterInstance) obj).getMinionList().lazyCountSpawnedMinionsGroups();
        }
      } else if (obj instanceof L2Npc) {
        npcCount++;
      } else if (obj instanceof L2PcInstance) {
        pcCount++;
        if ((((L2PcInstance) obj).getClient() != null)
            && ((L2PcInstance) obj).getClient().isDetached()) {
          detachedCount++;
        }
      } else if (obj instanceof L2Summon) {
        summonCount++;
      } else if (obj instanceof L2DoorInstance) {
        doorCount++;
      } else if (obj instanceof L2Character) {
        charCount++;
      }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("Server Status: ");
    sb.append("\r\n  --->  Player Count: " + playerCount + "/" + max);
    sb.append("\r\n  ---> Offline Count: " + detachedCount + "/" + playerCount);
    sb.append("\r\n  +-->  Object Count: " + objectCount);
    sb.append("\r\n  +-->      AI Count: " + AICount);
    sb.append("\r\n  +.... L2Item(Void): " + itemVoidCount);
    sb.append("\r\n  +.......... L2Item: " + itemCount);
    sb.append("\r\n  +....... L2Monster: " + monsterCount);
    sb.append("\r\n  +......... Minions: " + minionCount);
    sb.append("\r\n  +.. Minions Groups: " + minionsGroupCount);
    sb.append("\r\n  +........... L2Npc: " + npcCount);
    sb.append("\r\n  +............ L2Pc: " + pcCount);
    sb.append("\r\n  +........ L2Summon: " + summonCount);
    sb.append("\r\n  +.......... L2Door: " + doorCount);
    sb.append("\r\n  +.......... L2Char: " + charCount);
    sb.append("\r\n  --->   Ingame Time: " + gameTime());
    sb.append("\r\n  ---> Server Uptime: " + getUptime(uptime));
    sb.append("\r\n  --->      GM Count: " + getOnlineGMS());
    sb.append("\r\n  --->       Threads: " + Thread.activeCount());
    sb.append(
        "\r\n  RAM Used: "
            + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())
                / 1048576)); // 1024 * 1024 = 1048576
    sb.append("\r\n");

    return sb.toString();
  }
예제 #17
0
파일: Fort.java 프로젝트: 3mRe/L2Java
  private void updateOwnerInDB() {
    L2Clan clan = getOwnerClan();
    int clanId = 0;
    if (clan != null) {
      clanId = clan.getId();
      _lastOwnedTime.setTimeInMillis(System.currentTimeMillis());
    } else {
      _lastOwnedTime.setTimeInMillis(0);
    }

    try (Connection con = ConnectionFactory.getInstance().getConnection();
        PreparedStatement ps =
            con.prepareStatement(
                "UPDATE fort SET owner=?,lastOwnedTime=?,state=?,castleId=? WHERE id = ?")) {
      ps.setInt(1, clanId);
      ps.setLong(2, _lastOwnedTime.getTimeInMillis());
      ps.setInt(3, 0);
      ps.setInt(4, 0);
      ps.setInt(5, getResidenceId());
      ps.execute();

      // Announce to clan members
      if (clan != null) {
        clan.setFortId(getResidenceId()); // Set has fort flag for new owner
        SystemMessage sm;
        sm =
            SystemMessage.getSystemMessage(
                SystemMessageId.S1_IS_VICTORIOUS_IN_THE_FORTRESS_BATTLE_OF_S2);
        sm.addString(clan.getName());
        sm.addCastleId(getResidenceId());
        L2World.getInstance().getPlayers().forEach(p -> p.sendPacket(sm));
        clan.broadcastToOnlineMembers(new PledgeShowInfoUpdate(clan));
        clan.broadcastToOnlineMembers(new PlaySound(1, "Siege_Victory", 0, 0, 0, 0, 0));
        if (_FortUpdater[0] != null) {
          _FortUpdater[0].cancel(false);
        }
        if (_FortUpdater[1] != null) {
          _FortUpdater[1].cancel(false);
        }
        _FortUpdater[0] =
            ThreadPoolManager.getInstance()
                .scheduleGeneralAtFixedRate(
                    new FortUpdater(this, clan, 0, UpdaterType.PERIODIC_UPDATE),
                    Config.FS_UPDATE_FRQ * 60000L,
                    Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
        if (Config.FS_MAX_OWN_TIME > 0) {
          _FortUpdater[1] =
              ThreadPoolManager.getInstance()
                  .scheduleGeneralAtFixedRate(
                      new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME),
                      3600000,
                      3600000); // Schedule owner tasks to remove owener
        }
      } else {
        if (_FortUpdater[0] != null) {
          _FortUpdater[0].cancel(false);
        }
        _FortUpdater[0] = null;
        if (_FortUpdater[1] != null) {
          _FortUpdater[1].cancel(false);
        }
        _FortUpdater[1] = null;
      }
    } catch (Exception e) {
      _log.log(Level.WARNING, "Exception: updateOwnerInDB(L2Clan clan): " + e.getMessage(), e);
    }
  }
예제 #18
0
  @Override
  protected void runImpl() {
    L2PcInstance activeChar = getClient().getActiveChar();
    L2PcInstance targetChar = L2World.getInstance().getPlayer(_player);
    if (activeChar == null) {
      return;
    }
    if (targetChar == null) {
      activeChar.sendPacket(
          SystemMessageId.THERE_IS_NO_OPPONENT_TO_RECEIVE_YOUR_CHALLENGE_FOR_A_DUEL);
      return;
    }
    if (activeChar == targetChar) {
      activeChar.sendPacket(
          SystemMessageId.THERE_IS_NO_OPPONENT_TO_RECEIVE_YOUR_CHALLENGE_FOR_A_DUEL);
      return;
    }

    // Check if duel is possible
    if (!activeChar.canDuel()) {
      activeChar.sendPacket(SystemMessageId.YOU_ARE_UNABLE_TO_REQUEST_A_DUEL_AT_THIS_TIME);
      return;
    } else if (!targetChar.canDuel()) {
      activeChar.sendPacket(targetChar.getNoDuelReason());
      return;
    }
    // Players may not be too far apart
    else if (!activeChar.isInsideRadius(targetChar, 250, false, false)) {
      SystemMessage msg =
          SystemMessage.getSystemMessage(
              SystemMessageId.C1_IS_TOO_FAR_AWAY_TO_RECEIVE_A_DUEL_CHALLENGE);
      msg.addString(targetChar.getName());
      activeChar.sendPacket(msg);
      return;
    } else if (Config.FACTION_SYSTEM_ENABLED
        && ((activeChar.isEvil() && targetChar.isGood())
            || (activeChar.isGood() && targetChar.isEvil()))) {
      activeChar.sendPacket(SystemMessageId.YOU_ARE_UNABLE_TO_REQUEST_A_DUEL_AT_THIS_TIME);
      return;
    }

    // Duel is a party duel
    if (_partyDuel == 1) {
      // Player must be in a party & the party leader
      if (!activeChar.isInParty() || !activeChar.getParty().isLeader(activeChar)) {
        activeChar.sendMessage(
            "You have to be the leader of a party in order to request a party duel.");
        return;
      }
      // Target must be in a party
      else if (!targetChar.isInParty()) {
        activeChar.sendPacket(
            SystemMessageId
                .SINCE_THE_PERSON_YOU_CHALLENGED_IS_NOT_CURRENTLY_IN_A_PARTY_THEY_CANNOT_DUEL_AGAINST_YOUR_PARTY);
        return;
      }
      // Target may not be of the same party
      else if (activeChar.getParty().containsPlayer(targetChar)) {
        activeChar.sendMessage("This player is a member of your own party.");
        return;
      }

      // Check if every player is ready for a duel
      for (L2PcInstance temp : activeChar.getParty().getMembers()) {
        if (!temp.canDuel()) {
          activeChar.sendMessage("Not all the members of your party are ready for a duel.");
          return;
        }
      }
      L2PcInstance partyLeader = null; // snatch party leader of targetChar's party
      for (L2PcInstance temp : targetChar.getParty().getMembers()) {
        if (partyLeader == null) {
          partyLeader = temp;
        }
        if (!temp.canDuel()) {
          activeChar.sendPacket(
              SystemMessageId
                  .THE_OPPOSING_PARTY_IS_CURRENTLY_UNABLE_TO_ACCEPT_A_CHALLENGE_TO_A_DUEL);
          return;
        }
      }

      // Send request to targetChar's party leader
      if (partyLeader != null) {
        if (!partyLeader.isProcessingRequest()) {
          activeChar.onTransactionRequest(partyLeader);
          partyLeader.sendPacket(new ExDuelAskStart(activeChar.getName(), _partyDuel));

          if (Config.DEBUG) {
            _log.fine(activeChar.getName() + " requested a duel with " + partyLeader.getName());
          }

          SystemMessage msg =
              SystemMessage.getSystemMessage(
                  SystemMessageId.C1_S_PARTY_HAS_BEEN_CHALLENGED_TO_A_DUEL);
          msg.addString(partyLeader.getName());
          activeChar.sendPacket(msg);

          msg =
              SystemMessage.getSystemMessage(
                  SystemMessageId.C1_S_PARTY_HAS_CHALLENGED_YOUR_PARTY_TO_A_DUEL);
          msg.addString(activeChar.getName());
          targetChar.sendPacket(msg);
        } else {
          SystemMessage msg =
              SystemMessage.getSystemMessage(
                  SystemMessageId.C1_IS_ON_ANOTHER_TASK_PLEASE_TRY_AGAIN_LATER);
          msg.addString(partyLeader.getName());
          activeChar.sendPacket(msg);
        }
      }
    } else
    // 1vs1 duel
    {
      if (!targetChar.isProcessingRequest()) {
        activeChar.onTransactionRequest(targetChar);
        targetChar.sendPacket(new ExDuelAskStart(activeChar.getName(), _partyDuel));

        if (Config.DEBUG) {
          _log.fine(activeChar.getName() + " requested a duel with " + targetChar.getName());
        }

        SystemMessage msg =
            SystemMessage.getSystemMessage(SystemMessageId.C1_HAS_BEEN_CHALLENGED_TO_A_DUEL);
        msg.addString(targetChar.getName());
        activeChar.sendPacket(msg);

        msg = SystemMessage.getSystemMessage(SystemMessageId.C1_HAS_CHALLENGED_YOU_TO_A_DUEL);
        msg.addString(activeChar.getName());
        targetChar.sendPacket(msg);
      } else {
        SystemMessage msg =
            SystemMessage.getSystemMessage(
                SystemMessageId.C1_IS_ON_ANOTHER_TASK_PLEASE_TRY_AGAIN_LATER);
        msg.addString(targetChar.getName());
        activeChar.sendPacket(msg);
      }
    }
  }
예제 #19
0
 final L2PcInstance getPlayer() {
   return L2World.getInstance().getPlayer(_playerObjId);
 }
  @Override
  public final void run() {
    final int playerObjId = super.readD();
    final int type = super.readD();

    L2PcInstance player = L2World.getInstance().getPlayer(playerObjId);
    if (player == null) return;

    switch (type) {
      case -1: // mail arrived
        player.sendPacket(ExMailArrived.STATIC_PACKET);
        break;
      case 0: // text message
        player.sendMessage(super.readS());
        break;
      case 236:
        player.sendPacket(
            SystemMessage.getSystemMessage(SystemMessageId.ONLY_THE_CLAN_LEADER_IS_ENABLED));
        break;
      case 1050:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NO_CB_IN_MY_CLAN));
        break;
      case 1070:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NO_READ_PERMISSION));
        break;
      case 1071:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NO_WRITE_PERMISSION));
        break;
      case 1205:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.MAILBOX_FULL));
        break;
      case 1206:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.MEMOBOX_FULL));
        break;
      case 1227:
        try {
          SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_UNREAD_MESSAGES);
          final int number = super.readD();
          sm.addNumber(number);
          player.sendPacket(sm);
        } catch (Exception e) {
          _log.info("Incorrect packet from CBserver!");
        }
        break;
      case 1228:
        try {
          SystemMessage sm =
              SystemMessage.getSystemMessage(SystemMessageId.C1_BLOCKED_YOU_CANNOT_MAIL);
          final String name = super.readS();
          sm.addString(name);
          player.sendPacket(sm);
        } catch (Exception e) {
          _log.info("Incorrect packet from CBserver!");
        }
        break;
      case 1229:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NO_MORE_MESSAGES_TODAY));
        break;
      case 1230:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.ONLY_FIVE_RECIPIENTS));
        break;
      case 1231:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.SENT_MAIL));
        break;
      case 1232:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.MESSAGE_NOT_SENT));
        break;
      case 1233:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.NEW_MAIL));
        break;
      case 1234:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.MAIL_STORED_IN_MAILBOX));
        break;
      case 1238:
        player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.TEMP_MAILBOX_FULL));
        break;
      case 1370:
        try {
          SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CANNOT_MAIL_GM_C1);
          final String name = super.readS();
          sm.addString(name);
          player.sendPacket(sm);
        } catch (Exception e) {
          _log.info("Incorrect packet from CBserver!");
        }
        break;
      default:
        _log.info("error: Unknown message request from CB server: " + type);
    }
  }
  @Override
  protected void runImpl() {
    L2PcInstance player = getActiveChar();
    if (player == null) {
      return;
    }

    if (!player.getAccessLevel().allowTransaction()) {
      player.sendMessage("Transactions are disabled for your current Access Level.");
      sendPacket(ActionFailed.STATIC_PACKET);
      return;
    }

    BuffInfo info = player.getEffectList().getBuffInfoByAbnormalType(AbnormalType.BOT_PENALTY);
    if (info != null) {
      for (AbstractEffect effect : info.getEffects()) {
        if (!effect.checkCondition(BotReportTable.TRADE_ACTION_BLOCK_ID)) {
          player.sendPacket(SystemMessageId.YOU_HAVE_BEEN_REPORTED_SO_ACTIONS_NOT_ALLOWED);
          player.sendPacket(ActionFailed.STATIC_PACKET);
          return;
        }
      }
    }

    final L2Object target = L2World.getInstance().findObject(_objectId);
    // If there is no target, target is far away or
    // they are in different instances (except multiverse)
    // trade request is ignored and there is no system message.
    if ((target == null)
        || !player.getKnownList().knowsObject(target)
        || ((target.getInstanceId() != player.getInstanceId()) && (player.getInstanceId() != -1))) {
      return;
    }

    // If target and acting player are the same, trade request is ignored
    // and the following system message is sent to acting player.
    if (target.getObjectId() == player.getObjectId()) {
      player.sendPacket(SystemMessageId.TARGET_IS_INCORRECT);
      return;
    }

    if (!target.isPlayer()) {
      player.sendPacket(SystemMessageId.INCORRECT_TARGET);
      return;
    }

    final L2PcInstance partner = target.getActingPlayer();
    if (partner.isInOlympiadMode() || player.isInOlympiadMode()) {
      player.sendMessage(
          "A user currently participating in the Olympiad cannot accept or request a trade.");
      return;
    }

    info = partner.getEffectList().getBuffInfoByAbnormalType(AbnormalType.BOT_PENALTY);
    if (info != null) {
      for (AbstractEffect effect : info.getEffects()) {
        if (!effect.checkCondition(BotReportTable.TRADE_ACTION_BLOCK_ID)) {
          final SystemMessage sm =
              SystemMessage.getSystemMessage(SystemMessageId.C1_REPORTED_AND_IS_BEING_INVESTIGATED);
          sm.addCharName(partner);
          player.sendPacket(sm);
          player.sendPacket(ActionFailed.STATIC_PACKET);
          return;
        }
      }
    }

    // L2J Customs: Karma punishment
    if (!Config.ALT_GAME_KARMA_PLAYER_CAN_TRADE && (player.getKarma() > 0)) {
      player.sendMessage("You cannot trade while you are in a chaotic state.");
      return;
    }

    if (!Config.ALT_GAME_KARMA_PLAYER_CAN_TRADE && (partner.getKarma() > 0)) {
      player.sendMessage("You cannot request a trade while your target is in a chaotic state.");
      return;
    }

    if (Config.JAIL_DISABLE_TRANSACTION && (player.isJailed() || partner.isJailed())) {
      player.sendMessage("You cannot trade while you are in in Jail.");
      return;
    }

    if ((player.getPrivateStoreType() != PrivateStoreType.NONE)
        || (partner.getPrivateStoreType() != PrivateStoreType.NONE)) {
      player.sendPacket(SystemMessageId.CANNOT_TRADE_DISCARD_DROP_ITEM_WHILE_IN_SHOPMODE);
      return;
    }

    if (player.isProcessingTransaction()) {
      if (Config.DEBUG) {
        _log.fine("Already trading with someone else.");
      }
      player.sendPacket(SystemMessageId.ALREADY_TRADING);
      return;
    }

    SystemMessage sm;
    if (partner.isProcessingRequest() || partner.isProcessingTransaction()) {
      if (Config.DEBUG) {
        _log.info("Transaction already in progress.");
      }
      sm = SystemMessage.getSystemMessage(SystemMessageId.C1_IS_BUSY_TRY_LATER);
      sm.addString(partner.getName());
      player.sendPacket(sm);
      return;
    }

    if (partner.getTradeRefusal()) {
      player.sendMessage("That person is in trade refusal mode.");
      return;
    }

    if (BlockList.isBlocked(partner, player)) {
      sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_ADDED_YOU_TO_IGNORE_LIST);
      sm.addCharName(partner);
      player.sendPacket(sm);
      return;
    }

    if (player.calculateDistance(partner, true, false) > 150) {
      player.sendPacket(SystemMessageId.TARGET_TOO_FAR);
      return;
    }

    player.onTransactionRequest(partner);
    partner.sendPacket(new SendTradeRequest(player.getObjectId()));
    sm = SystemMessage.getSystemMessage(SystemMessageId.REQUEST_C1_FOR_TRADE);
    sm.addString(partner.getName());
    player.sendPacket(sm);
  }
예제 #22
0
  @Override
  protected void runImpl() {
    L2PcInstance activeChar = getClient().getActiveChar();

    if (activeChar == null) {
      _log.fine("RequestCrystalizeItem: activeChar was null");
      return;
    }

    if (!getClient().getFloodProtectors().getTransaction().tryPerformAction("crystallize")) {
      activeChar.sendMessage("You are crystallizing too fast.");
      return;
    }

    if (_count <= 0) {
      Util.handleIllegalPlayerAction(
          activeChar,
          "[RequestCrystallizeItem] count <= 0! ban! oid: "
              + _objectId
              + " owner: "
              + activeChar.getName(),
          Config.DEFAULT_PUNISH);
      return;
    }

    if ((activeChar.getPrivateStoreType() != PrivateStoreType.NONE)
        || !activeChar.isInCrystallize()) {
      activeChar.sendPacket(
          SystemMessageId
              .WHILE_OPERATING_A_PRIVATE_STORE_OR_WORKSHOP_YOU_CANNOT_DISCARD_DESTROY_OR_TRADE_AN_ITEM);
      return;
    }

    int skillLevel = activeChar.getSkillLevel(CommonSkill.CRYSTALLIZE.getId());
    if (skillLevel <= 0) {
      activeChar.sendPacket(
          SystemMessageId
              .YOU_MAY_NOT_CRYSTALLIZE_THIS_ITEM_YOUR_CRYSTALLIZATION_SKILL_LEVEL_IS_TOO_LOW);
      activeChar.sendPacket(ActionFailed.STATIC_PACKET);
      if ((activeChar.getRace() != Race.DWARF)
          && (activeChar.getClassId().ordinal() != 117)
          && (activeChar.getClassId().ordinal() != 55)) {
        _log.info(
            "Player "
                + activeChar.getClient()
                + " used crystalize with classid: "
                + activeChar.getClassId().ordinal());
      }
      return;
    }

    PcInventory inventory = activeChar.getInventory();
    if (inventory != null) {
      L2ItemInstance item = inventory.getItemByObjectId(_objectId);
      if (item == null) {
        activeChar.sendPacket(ActionFailed.STATIC_PACKET);
        return;
      }

      if (item.isHeroItem()) {
        return;
      }

      if (_count > item.getCount()) {
        _count = activeChar.getInventory().getItemByObjectId(_objectId).getCount();
      }
    }

    final L2ItemInstance itemToRemove = activeChar.getInventory().getItemByObjectId(_objectId);
    if ((itemToRemove == null) || itemToRemove.isShadowItem() || itemToRemove.isTimeLimitedItem()) {
      return;
    }

    if (!itemToRemove.getItem().isCrystallizable()
        || (itemToRemove.getItem().getCrystalCount() <= 0)
        || (itemToRemove.getItem().getCrystalType() == CrystalType.NONE)) {
      _log.warning(
          activeChar.getName()
              + " ("
              + activeChar.getObjectId()
              + ") tried to crystallize "
              + itemToRemove.getItem().getId());
      return;
    }

    if (!activeChar.getInventory().canManipulateWithItemId(itemToRemove.getId())) {
      activeChar.sendMessage("You cannot use this item.");
      return;
    }

    // Check if the char can crystallize items and return if false;
    boolean canCrystallize = true;

    switch (itemToRemove.getItem().getCrystalTypePlus()) {
      case D:
        {
          if (skillLevel < 1) {
            canCrystallize = false;
          }
          break;
        }
      case C:
        {
          if (skillLevel < 2) {
            canCrystallize = false;
          }
          break;
        }
      case B:
        {
          if (skillLevel < 3) {
            canCrystallize = false;
          }
          break;
        }
      case A:
        {
          if (skillLevel < 4) {
            canCrystallize = false;
          }
          break;
        }
      case S:
        {
          if (skillLevel < 5) {
            canCrystallize = false;
          }
          break;
        }
      case R:
        {
          if (skillLevel < 6) {
            canCrystallize = false;
          }
          break;
        }
    }

    if (!canCrystallize) {
      activeChar.sendPacket(
          SystemMessageId
              .YOU_MAY_NOT_CRYSTALLIZE_THIS_ITEM_YOUR_CRYSTALLIZATION_SKILL_LEVEL_IS_TOO_LOW);
      activeChar.sendPacket(ActionFailed.STATIC_PACKET);
      return;
    }

    // activeChar.setInCrystallize(true);

    // unequip if needed
    SystemMessage sm;
    if (itemToRemove.isEquipped()) {
      L2ItemInstance[] unequiped =
          activeChar.getInventory().unEquipItemInSlotAndRecord(itemToRemove.getLocationSlot());
      InventoryUpdate iu = new InventoryUpdate();
      for (L2ItemInstance item : unequiped) {
        iu.addModifiedItem(item);
      }
      activeChar.sendPacket(iu);

      if (itemToRemove.getEnchantLevel() > 0) {
        sm = SystemMessage.getSystemMessage(SystemMessageId.THE_EQUIPMENT_S1_S2_HAS_BEEN_REMOVED);
        sm.addInt(itemToRemove.getEnchantLevel());
        sm.addItemName(itemToRemove);
      } else {
        sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_BEEN_UNEQUIPPED);
        sm.addItemName(itemToRemove);
      }
      activeChar.sendPacket(sm);
    }

    // remove from inventory
    final L2ItemInstance removedItem =
        activeChar.getInventory().destroyItem("Crystalize", _objectId, _count, activeChar, null);

    final InventoryUpdate iu = new InventoryUpdate();
    iu.addRemovedItem(removedItem);
    activeChar.sendPacket(iu);

    final int crystalId = itemToRemove.getItem().getCrystalItemId();
    final int crystalAmount = itemToRemove.getCrystalCount();

    final List<ItemChanceHolder> items = new ArrayList<>();
    items.add(new ItemChanceHolder(crystalId, 100, crystalAmount));

    final CrystalizationData data =
        ItemCrystalizationData.getInstance().getCrystalization(itemToRemove.getId());
    if (data != null) {
      data.getItems().stream().filter(holder -> (holder.getId() != crystalId)).forEach(items::add);
    }

    for (ItemChanceHolder holder : items) {
      final double rand = Rnd.nextDouble() * 100;
      if (rand < holder.getChance()) {
        // add crystals
        final L2ItemInstance createdItem =
            activeChar
                .getInventory()
                .addItem("Crystalize", holder.getId(), holder.getCount(), activeChar, activeChar);

        sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_HAVE_EARNED_S2_S1_S);
        sm.addItemName(createdItem);
        sm.addLong(holder.getCount());
        activeChar.sendPacket(sm);
      }
    }

    sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HAS_BEEN_CRYSTALLIZED);
    sm.addItemName(removedItem);
    activeChar.sendPacket(sm);

    activeChar.broadcastUserInfo();

    L2World.getInstance().removeObject(removedItem);

    activeChar.setInCrystallize(false);
  }
  protected static final Participant[][] createListOfParticipants(List<List<Integer>> list) {
    if ((list == null) || list.isEmpty() || (list.size() < 2)) {
      return null;
    }

    List<Integer> teamOne = null;
    List<Integer> teamTwo = null;
    L2PcInstance player;
    List<L2PcInstance> teamOnePlayers = new ArrayList<>(MAX_TEAM_SIZE);
    List<L2PcInstance> teamTwoPlayers = new ArrayList<>(MAX_TEAM_SIZE);

    while (list.size() > 1) {
      teamOne = list.remove(Rnd.nextInt(list.size()));

      if (((teamOne == null) || teamOne.isEmpty())) {
        continue;
      }

      for (int objectId : teamOne) {
        player = L2World.getInstance().getPlayer(objectId);
        if ((player == null) || !player.isOnline()) {
          teamOnePlayers.clear();
          break;
        }
        teamOnePlayers.add(player);
      }
      if (teamOnePlayers.isEmpty()) {
        continue;
      }

      teamTwo = list.remove(Rnd.nextInt(list.size()));
      if ((teamTwo == null) || teamTwo.isEmpty()) {
        list.add(teamOne);
        teamOnePlayers.clear();
        continue;
      }

      for (int objectId : teamTwo) {
        player = L2World.getInstance().getPlayer(objectId);
        if ((player == null) || !player.isOnline()) {
          teamTwoPlayers.clear();
          break;
        }
        teamTwoPlayers.add(player);
      }
      if (teamTwoPlayers.isEmpty()) {
        list.add(teamOne);
        teamOnePlayers.clear();
        continue;
      }

      Participant[] t1 = new Participant[teamOnePlayers.size()];
      Participant[] t2 = new Participant[teamTwoPlayers.size()];
      Participant[][] result = new Participant[2][];

      for (int i = 0; i < t1.length; i++) {
        t1[i] = new Participant(teamOnePlayers.get(i), 1);
      }

      for (int i = 0; i < t2.length; i++) {
        t2[i] = new Participant(teamTwoPlayers.get(i), 2);
      }

      result[0] = t1;
      result[1] = t2;
      return result;
    }

    return null;
  }
 @Override
 public boolean useAdminCommand(String command, L2PcInstance activeChar) {
   if (command.equals("admin_show_spawns")) {
     AdminHtml.showAdminHtml(activeChar, "spawns.htm");
   } else if (command.equalsIgnoreCase("admin_spawn_debug_menu")) {
     AdminHtml.showAdminHtml(activeChar, "spawns_debug.htm");
   } else if (command.startsWith("admin_spawn_debug_print")) {
     StringTokenizer st = new StringTokenizer(command, " ");
     L2Object target = activeChar.getTarget();
     if (target instanceof L2Npc) {
       try {
         st.nextToken();
         int type = Integer.parseInt(st.nextToken());
         printSpawn((L2Npc) target, type);
         if (command.contains("_menu")) {
           AdminHtml.showAdminHtml(activeChar, "spawns_debug.htm");
         }
       } catch (Exception e) {
       }
     } else {
       activeChar.sendPacket(SystemMessageId.INCORRECT_TARGET);
     }
   } else if (command.startsWith("admin_spawn_index")) {
     StringTokenizer st = new StringTokenizer(command, " ");
     try {
       st.nextToken();
       int level = Integer.parseInt(st.nextToken());
       int from = 0;
       try {
         from = Integer.parseInt(st.nextToken());
       } catch (NoSuchElementException nsee) {
       }
       showMonsters(activeChar, level, from);
     } catch (Exception e) {
       AdminHtml.showAdminHtml(activeChar, "spawns.htm");
     }
   } else if (command.equals("admin_show_npcs")) {
     AdminHtml.showAdminHtml(activeChar, "npcs.htm");
   } else if (command.startsWith("admin_npc_index")) {
     StringTokenizer st = new StringTokenizer(command, " ");
     try {
       st.nextToken();
       String letter = st.nextToken();
       int from = 0;
       try {
         from = Integer.parseInt(st.nextToken());
       } catch (NoSuchElementException nsee) {
       }
       showNpcs(activeChar, letter, from);
     } catch (Exception e) {
       AdminHtml.showAdminHtml(activeChar, "npcs.htm");
     }
   } else if (command.startsWith("admin_instance_spawns")) {
     StringTokenizer st = new StringTokenizer(command, " ");
     try {
       st.nextToken();
       int instance = Integer.parseInt(st.nextToken());
       if (instance >= 300000) {
         final StringBuilder html =
             StringUtil.startAppend(
                 500 + 1000,
                 "<html><table width=\"100%\"><tr><td width=45><button value=\"Main\" action=\"bypass -h admin_admin\" width=45 height=21 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td><td width=180><center>",
                 "<font color=\"LEVEL\">Spawns for " + String.valueOf(instance) + "</font>",
                 "</td><td width=45><button value=\"Back\" action=\"bypass -h admin_current_player\" width=45 height=21 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\"></td></tr></table><br>",
                 "<table width=\"100%\"><tr><td width=200>NpcName</td><td width=70>Action</td></tr>");
         int counter = 0;
         int skiped = 0;
         Instance inst = InstanceManager.getInstance().getInstance(instance);
         if (inst != null) {
           for (L2Npc npc : inst.getNpcs()) {
             if (!npc.isDead()) {
               // Only 50 because of client html limitation
               if (counter < 50) {
                 StringUtil.append(
                     html,
                     "<tr><td>" + npc.getName() + "</td><td>",
                     "<a action=\"bypass -h admin_move_to "
                         + npc.getX()
                         + " "
                         + npc.getY()
                         + " "
                         + npc.getZ()
                         + "\">Go</a>",
                     "</td></tr>");
                 counter++;
               } else {
                 skiped++;
               }
             }
           }
           StringUtil.append(
               html,
               "<tr><td>Skipped:</td><td>"
                   + String.valueOf(skiped)
                   + "</td></tr></table></body></html>");
           final NpcHtmlMessage ms = new NpcHtmlMessage();
           ms.setHtml(html.toString());
           activeChar.sendPacket(ms);
         } else {
           activeChar.sendMessage("Cannot find instance " + instance);
         }
       } else {
         activeChar.sendMessage("Invalid instance number.");
       }
     } catch (Exception e) {
       activeChar.sendMessage("Usage //instance_spawns <instance_number>");
     }
   } else if (command.startsWith("admin_unspawnall")) {
     Broadcast.toAllOnlinePlayers(
         SystemMessage.getSystemMessage(SystemMessageId.NPC_SERVER_NOT_OPERATING));
     RaidBossSpawnManager.getInstance().cleanUp();
     DayNightSpawnManager.getInstance().cleanUp();
     L2World.getInstance().deleteVisibleNpcSpawns();
     AdminTable.getInstance().broadcastMessageToGMs("NPC Unspawn completed!");
   } else if (command.startsWith("admin_spawnday")) {
     DayNightSpawnManager.getInstance().spawnDayCreatures();
   } else if (command.startsWith("admin_spawnnight")) {
     DayNightSpawnManager.getInstance().spawnNightCreatures();
   } else if (command.startsWith("admin_respawnall") || command.startsWith("admin_spawn_reload")) {
     // make sure all spawns are deleted
     RaidBossSpawnManager.getInstance().cleanUp();
     DayNightSpawnManager.getInstance().cleanUp();
     L2World.getInstance().deleteVisibleNpcSpawns();
     // now respawn all
     NpcData.getInstance().load();
     SpawnTable.getInstance().load();
     RaidBossSpawnManager.getInstance().load();
     AutoSpawnHandler.getInstance().reload();
     SevenSigns.getInstance().spawnSevenSignsNPC();
     QuestManager.getInstance().reloadAllScripts();
     AdminTable.getInstance().broadcastMessageToGMs("NPC Respawn completed!");
   } else if (command.startsWith("admin_spawn_monster") || command.startsWith("admin_spawn")) {
     StringTokenizer st = new StringTokenizer(command, " ");
     try {
       String cmd = st.nextToken();
       String id = st.nextToken();
       int respawnTime = 0;
       int mobCount = 1;
       if (st.hasMoreTokens()) {
         mobCount = Integer.parseInt(st.nextToken());
       }
       if (st.hasMoreTokens()) {
         respawnTime = Integer.parseInt(st.nextToken());
       }
       if (cmd.equalsIgnoreCase("admin_spawn_once")) {
         spawnMonster(activeChar, id, respawnTime, mobCount, false);
       } else {
         spawnMonster(activeChar, id, respawnTime, mobCount, true);
       }
     } catch (Exception e) { // Case of wrong or missing monster data
       AdminHtml.showAdminHtml(activeChar, "spawns.htm");
     }
   } else if (command.startsWith("admin_list_spawns")
       || command.startsWith("admin_list_positions")) {
     int npcId = 0;
     int teleportIndex = -1;
     try { // admin_list_spawns x[xxxx] x[xx]
       String[] params = command.split(" ");
       Pattern pattern = Pattern.compile("[0-9]*");
       Matcher regexp = pattern.matcher(params[1]);
       if (regexp.matches()) {
         npcId = Integer.parseInt(params[1]);
       } else {
         params[1] = params[1].replace('_', ' ');
         npcId = NpcData.getInstance().getTemplateByName(params[1]).getId();
       }
       if (params.length > 2) {
         teleportIndex = Integer.parseInt(params[2]);
       }
     } catch (Exception e) {
       activeChar.sendMessage("Command format is //list_spawns <npcId|npc_name> [tele_index]");
     }
     if (command.startsWith("admin_list_positions")) {
       findNPCInstances(activeChar, npcId, teleportIndex, true);
     } else {
       findNPCInstances(activeChar, npcId, teleportIndex, false);
     }
   }
   return true;
 }
예제 #25
0
  public synchronized void computeNewHeroes(List<StatsSet> newHeroes) {
    updateHeroes(true);

    for (Integer objectId : _heroes.keySet()) {
      final L2PcInstance player = L2World.getInstance().getPlayer(objectId);
      if (player == null) {
        continue;
      }

      player.setHero(false);

      for (int i = 0; i < Inventory.PAPERDOLL_TOTALSLOTS; i++) {
        L2ItemInstance equippedItem = player.getInventory().getPaperdollItem(i);
        if ((equippedItem != null) && equippedItem.isHeroItem()) {
          player.getInventory().unEquipItemInSlot(i);
        }
      }

      final InventoryUpdate iu = new InventoryUpdate();
      for (L2ItemInstance item : player.getInventory().getAvailableItems(false, false, false)) {
        if ((item != null) && item.isHeroItem()) {
          player.destroyItem("Hero", item, null, true);
          iu.addRemovedItem(item);
        }
      }

      if (!iu.getItems().isEmpty()) {
        player.sendPacket(iu);
      }

      player.broadcastUserInfo();
    }

    if (newHeroes.isEmpty()) {
      _heroes.clear();
      return;
    }

    Map<Integer, StatsSet> heroes = new FastMap<>();

    for (StatsSet hero : newHeroes) {
      int charId = hero.getInt(Olympiad.CHAR_ID);

      if ((_completeHeroes != null) && _completeHeroes.containsKey(charId)) {
        StatsSet oldHero = _completeHeroes.get(charId);
        int count = oldHero.getInt(COUNT);
        oldHero.set(COUNT, count + 1);
        oldHero.set(PLAYED, 1);
        oldHero.set(CLAIMED, false);
        heroes.put(charId, oldHero);
      } else {
        StatsSet newHero = new StatsSet();
        newHero.set(Olympiad.CHAR_NAME, hero.getString(Olympiad.CHAR_NAME));
        newHero.set(Olympiad.CLASS_ID, hero.getInt(Olympiad.CLASS_ID));
        newHero.set(COUNT, 1);
        newHero.set(PLAYED, 1);
        newHero.set(CLAIMED, false);
        heroes.put(charId, newHero);
      }
    }

    deleteItemsInDb();

    _heroes.clear();
    _heroes.putAll(heroes);

    heroes.clear();

    updateHeroes(false);
  }
  @Override
  public boolean useCommand(String command, PrintWriter _print, Socket _cSocket, int _uptime) {
    if (command.startsWith("debug") && (command.length() > 6)) {
      StringTokenizer st = new StringTokenizer(command.substring(6));
      // TODO: Rewrite to use ARM.
      FileOutputStream fos = null;
      OutputStreamWriter out = null;
      try {
        String dbg = st.nextToken();

        if (dbg.equals("decay")) {
          _print.print(DecayTaskManager.getInstance().toString());
        } else if (dbg.equals("packetsend")) {
          if (st.countTokens() < 2) {
            _print.println("Usage: debug packetsend <charName> <packetData>");
            return false;
          }
          String charName = st.nextToken();
          L2PcInstance targetPlayer = L2World.getInstance().getPlayer(charName);

          if (targetPlayer == null) {
            _print.println("Player " + charName + " cannot be found online");
            return false;
          }

          AdminForgePacket sp = new AdminForgePacket();
          while (st.hasMoreTokens()) {
            String b = st.nextToken();
            if (!b.isEmpty()) {
              sp.addPart("C".getBytes()[0], "0x" + b);
            }
          }

          targetPlayer.sendPacket(sp);
          _print.println("Packet sent to player " + charName);
        } else if (dbg.equals("PacketTP")) {
          String str = ThreadPoolManager.getInstance().getPacketStats();
          _print.println(str);
          int i = 0;
          File f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
          while (f.exists()) {
            i++;
            f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
          }
          f.getParentFile().mkdirs();
          fos = new FileOutputStream(f);
          out = new OutputStreamWriter(fos, "UTF-8");
          out.write(str);
        } else if (dbg.equals("IOPacketTP")) {
          String str = ThreadPoolManager.getInstance().getIOPacketStats();
          _print.println(str);
          int i = 0;
          File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
          while (f.exists()) {
            i++;
            f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
          }
          f.getParentFile().mkdirs();
          fos = new FileOutputStream(f);
          out = new OutputStreamWriter(fos, "UTF-8");
          out.write(str);
        } else if (dbg.equals("GeneralTP")) {
          String str = ThreadPoolManager.getInstance().getGeneralStats();
          _print.println(str);
          int i = 0;
          File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
          while (f.exists()) {
            i++;
            f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
          }
          f.getParentFile().mkdirs();
          fos = new FileOutputStream(f);
          out = new OutputStreamWriter(fos, "UTF-8");
          out.write(str);
        } else if (dbg.equals("full")) {
          Calendar cal = Calendar.getInstance();
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

          StringBuilder sb = new StringBuilder();
          sb.append(sdf.format(cal.getTime()));
          sb.append("\n\n");
          uptime = _uptime;
          sb.append(getServerStatus());
          sb.append("\n\n");
          sb.append("\n## Java Platform Information ##");
          sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
          sb.append("\nJava Version: " + System.getProperty("java.version"));
          sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
          sb.append('\n');
          sb.append("\n## Virtual Machine Information ##");
          sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
          sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
          sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
          sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
          sb.append('\n');
          sb.append("\n## OS Information ##");
          sb.append("\nName: " + System.getProperty("os.name"));
          sb.append("\nArchiteture: " + System.getProperty("os.arch"));
          sb.append("\nVersion: " + System.getProperty("os.version"));
          sb.append('\n');
          sb.append("\n## Runtime Information ##");
          sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
          sb.append(
              "\nCurrent Free Heap Size: "
                  + (Runtime.getRuntime().freeMemory() / 1024 / 1024)
                  + " mb");
          sb.append(
              "\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
          sb.append(
              "\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");

          sb.append('\n');
          sb.append("\n## Class Path Information ##\n");
          String cp = System.getProperty("java.class.path");
          String[] libs = cp.split(File.pathSeparator);
          for (String lib : libs) {
            sb.append(lib);
            sb.append('\n');
          }

          sb.append('\n');
          sb.append("## Threads Information ##\n");
          Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();

          FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<>();
          entries.setValueComparator(
              new FastComparator<Entry<Thread, StackTraceElement[]>>() {

                /** */
                private static final long serialVersionUID = 1L;

                @Override
                public boolean areEqual(
                    Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) {
                  return e1.getKey().getName().equals(e2.getKey().getName());
                }

                @Override
                public int compare(
                    Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) {
                  return e1.getKey().getName().compareTo(e2.getKey().getName());
                }

                @Override
                public int hashCodeOf(Entry<Thread, StackTraceElement[]> e) {
                  return e.hashCode();
                }
              });
          entries.addAll(allThread.entrySet());
          entries.sort();
          for (Entry<Thread, StackTraceElement[]> entry : entries) {
            StackTraceElement[] stes = entry.getValue();
            Thread t = entry.getKey();
            sb.append("--------------\n");
            sb.append(t.toString() + " (" + t.getId() + ")\n");
            sb.append("State: " + t.getState() + '\n');
            sb.append(
                "isAlive: "
                    + t.isAlive()
                    + " | isDaemon: "
                    + t.isDaemon()
                    + " | isInterrupted: "
                    + t.isInterrupted()
                    + '\n');
            sb.append('\n');
            for (StackTraceElement ste : stes) {
              sb.append(ste.toString());
              sb.append('\n');
            }
            sb.append('\n');
          }

          sb.append('\n');
          ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
          long[] ids = findDeadlockedThreads(mbean);
          if ((ids != null) && (ids.length > 0)) {
            Thread[] threads = new Thread[ids.length];
            for (int i = 0; i < threads.length; i++) {
              threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
            }
            sb.append("Deadlocked Threads:\n");
            sb.append("-------------------\n");
            for (Thread thread : threads) {
              System.err.println(thread);
              for (StackTraceElement ste : thread.getStackTrace()) {
                sb.append("\t" + ste);
                sb.append('\n');
              }
            }
          }

          sb.append("\n\n## Thread Pool Manager Statistics ##\n");
          for (String line : ThreadPoolManager.getInstance().getStats()) {
            sb.append(line);
            sb.append('\n');
          }

          int i = 0;
          File f = new File("./log/Debug-" + i + ".txt");
          while (f.exists()) {
            i++;
            f = new File("./log/Debug-" + i + ".txt");
          }
          f.getParentFile().mkdirs();
          fos = new FileOutputStream(f);
          out = new OutputStreamWriter(fos, "UTF-8");
          out.write(sb.toString());
          out.flush();
          out.close();
          fos.close();

          _print.println("Debug output saved to log/" + f.getName());
          _print.flush();
        }
      } catch (Exception e) {
      } finally {
        try {
          if (out != null) {
            out.close();
          }
        } catch (Exception e) {
        }

        try {
          if (fos != null) {
            fos.close();
          }
        } catch (Exception e) {
        }
      }
    }
    return false;
  }
  private void initNewChar(L2GameClient client, L2PcInstance newChar) {
    if (Config.DEBUG) _log.fine("Character init start");

    L2World.getInstance().storeObject(newChar);

    L2PcTemplate template = newChar.getTemplate();

    newChar.addAdena("Init", Config.STARTING_ADENA, null, false);

    newChar.setXYZInvisible(template.spawnX, template.spawnY, template.spawnZ);
    newChar.setTitle("");

    if (Config.ENABLE_VITALITY)
      newChar.setVitalityPoints(
          Math.min(Config.STARTING_VITALITY_POINTS, PcStat.MAX_VITALITY_POINTS), true);

    if (Config.STARTING_LEVEL > 1) {
      newChar.getStat().addLevel((byte) (Config.STARTING_LEVEL - 1));
    }
    if (Config.STARTING_SP > 0) {
      newChar.getStat().addSp(Config.STARTING_SP);
    }

    L2ShortCut shortcut;
    // add attack shortcut
    shortcut = new L2ShortCut(0, 0, 3, 2, 0, 1);
    newChar.registerShortCut(shortcut);
    // add take shortcut
    shortcut = new L2ShortCut(3, 0, 3, 5, 0, 1);
    newChar.registerShortCut(shortcut);
    // add sit shortcut
    shortcut = new L2ShortCut(10, 0, 3, 0, 0, 1);
    newChar.registerShortCut(shortcut);

    for (PcTemplateItem ia : template.getItems()) {
      L2ItemInstance item =
          newChar.getInventory().addItem("Init", ia.getItemId(), ia.getAmount(), newChar, null);

      if (item == null) {
        _log.warning(
            "Could not create item during char creation: itemId "
                + ia.getItemId()
                + ", amount "
                + ia.getAmount()
                + ".");
        continue;
      }

      // add tutbook shortcut
      if (item.getItemId() == 5588) {
        shortcut = new L2ShortCut(11, 0, 1, item.getObjectId(), 0, 1);
        newChar.registerShortCut(shortcut);
      }

      if (item.isEquipable() && ia.isEquipped()) {
        newChar.getInventory().equipItem(item);
      }
    }

    for (L2SkillLearn skill :
        SkillTreesData.getInstance()
            .getAvailableSkills(newChar, newChar.getClassId(), false, true)) {
      newChar.addSkill(
          SkillTable.getInstance().getInfo(skill.getSkillId(), skill.getSkillLevel()), true);
      if (skill.getSkillId() == 1001 || skill.getSkillId() == 1177) {
        shortcut = new L2ShortCut(1, 0, 2, skill.getSkillId(), skill.getSkillLevel(), 1);
        newChar.registerShortCut(shortcut);
      }
      if (skill.getSkillId() == 1216) {
        shortcut = new L2ShortCut(10, 0, 2, skill.getSkillId(), skill.getSkillLevel(), 1);
        newChar.registerShortCut(shortcut);
      }
      if (Config.DEBUG)
        _log.fine("Adding starter skill:" + skill.getSkillId() + " / " + skill.getSkillLevel());
    }

    if (!Config.DISABLE_TUTORIAL) startTutorialQuest(newChar);

    newChar.setOnlineStatus(true, false);
    newChar.deleteMe();

    CharSelectionInfo cl =
        new CharSelectionInfo(client.getAccountName(), client.getSessionId().playOkID1);
    client.getConnection().sendPacket(cl);
    client.setCharSelection(cl.getCharInfo());

    if (Config.DEBUG) _log.fine("Character init end");
  }