    public static Inward create(Inward inward) {
        String sql = "INSERT INTO inwards (item_id, quantity, date, source_id) VALUES (?, ?, ?, ?)";

        try (Connection con = Connect.getConnection()) {
            PreparedStatement p = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            p.setInt(1, inward.getItem().getId());
            p.setBigDecimal(2, inward.getQuantity());
            p.setObject(3, java.sql.Date.valueOf(inward.getDate()));
            p.setInt(4, inward.getSource().getId());
            p.executeUpdate();

            try (ResultSet generatedKeys = p.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    inward.setId(generatedKeys.getInt(1));
                } else {
                    throw new SQLException("Obtaining inward ID failed.");
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(CRUDInwards.class.getName()).log(Level.SEVERE, null, ex);
        }
        return inward;
    }

    public static Inward create(Inward inward) {
        String sql = "INSERT INTO inwards (item_id, quantity, date, source_id) VALUES (?, ?, ?, ?)";
        con = Connect.getConnection();
        try {
            PreparedStatement p = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            p.setInt(1, inward.getItem().getId());
            p.setBigDecimal(2, inward.getQuantity());
            p.setObject(3, inward.getDate());
            p.setInt(4, inward.getSource().getId());
            p.executeUpdate();

            try (ResultSet generatedKeys = p.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    inward.setId(generatedKeys.getInt(1));
                } else {
                    throw new SQLException("Obtaining inward ID failed.");
                }
            }
            con.commit();
        } catch (SQLException ex) {
            Logger.getLogger(CRUDInwards.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            Connect.cleanUp();
        }
        return inward;
    }

Try With Resources try(Connection con=Connect.getConnection()) in method public create(inward Inward) : Inward from class warehouse.db.CRUDInwards


    public static List<ItemMeta> search(SearchFilters searchFilters, int LIMIT, int OFFSET) {
        List<ItemMeta> itemsMeta = new ArrayList<>();
        String sql = "SELECT it.id , it.name, it.specification,"
                + " ("
                + " COALESCE((SELECT SUM(i.quantity)"
                + " FROM inwards AS i"
                + " WHERE i.item_id = it.id),0)"
                + " -"
                + " COALESCE((SELECT SUM(o.quantity)"
                + " FROM outwards AS o"
                + " WHERE o.item_id = it.id),0)"
                + " ) AS balance, u.id AS unit_id, u.name AS unit"
                + " "
                + " FROM items AS it JOIN quantity_unit AS u"
                + " ON it.unit_id = u.id"
                + formulateSearchFilters(searchFilters)
                + " ORDER BY it.id ASC"
                + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";

        try (Connection con = Connect.getConnection()) {
            PreparedStatement p;
            p = con.prepareStatement(sql);
            PreparedStatementWrapper preparedStatementWrapper
                    = formulateSearchPreparedStatement(searchFilters, new PreparedStatementWrapper(p));
            int parameterIndex = preparedStatementWrapper.getParameterIndex();
            p.setInt(++parameterIndex, OFFSET);
            p.setInt(++parameterIndex, LIMIT);
            try (ResultSet result = p.executeQuery()) {
                while (result.next()) {
                    ItemMeta itemMeta = new ItemMeta();
                    itemMeta.setId(result.getInt("id"));
                    itemMeta.setName(result.getString("name"));
                    itemMeta.setSpecification(result.getString("specification"));
                    itemMeta.setBalance(result.getBigDecimal("balance"));
                    QuantityUnit quantityUnit = new QuantityUnit();
                    quantityUnit.setId(result.getInt("unit_id"));
                    quantityUnit.setName(result.getString("unit"));
                    itemMeta.setQuantityUnit(quantityUnit);
                    itemsMeta.add(itemMeta);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(CRUDItems.class.getName()).log(Level.SEVERE, null, ex);
        }
        return itemsMeta;
    }

    public static List<ItemMeta> search(SearchFilters searchFilters, int LIMIT, int OFFSET) {
        List<ItemMeta> itemsMeta = new ArrayList<>();
        try {
            String sql = " SELECT it.id , it.name, it.specification,"
                    + " ("
                    + " COALESCE((SELECT SUM(i.quantity)"
                    + " FROM inwards AS i"
                    + " WHERE i.item_id = it.id),0)"
                    + " -"
                    + " COALESCE((SELECT SUM(o.quantity)"
                    + " FROM outwards AS o"
                    + " WHERE o.item_id = it.id),0)"
                    + " ) AS balance, u.id AS unit_id, u.name AS unit"
                    + " "
                    + " FROM items AS it JOIN quantity_unit AS u"
                    + " ON it.unit_id = u.id"
                    + formulateSearchFilters(searchFilters)
                    + " ORDER BY id ASC"
                    + " LIMIT ? OFFSET ?";

            con = Connect.getConnection();
            PreparedStatement p;
            p = con.prepareStatement(sql);
            PreparedStatementWrapper preparedStatementWrapper
                    = formulateSearchPreparedStatement(searchFilters, new PreparedStatementWrapper(p));
            int parameterIndex = preparedStatementWrapper.getParameterIndex();
            p.setInt(++parameterIndex, LIMIT);
            p.setInt(++parameterIndex, OFFSET);
            ResultSet result = p.executeQuery();
            while (result.next()) {
                ItemMeta itemMeta = new ItemMeta();
                itemMeta.setId(result.getInt("id"));
                itemMeta.setName(result.getString("name"));
                itemMeta.setSpecification(result.getString("specification"));
                itemMeta.setBalance(result.getBigDecimal("balance"));
                QuantityUnit quantityUnit = new QuantityUnit();
                quantityUnit.setId(result.getInt("unit_id"));
                quantityUnit.setName(result.getString("unit"));
                itemMeta.setQuantityUnit(quantityUnit);
                itemsMeta.add(itemMeta);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CRUDItems.class.getName()).log(Level.SEVERE, null, ex);
        }
        return itemsMeta;
    }

Try With Resources try(ResultSet result=p.executeQuery()) in method public search(searchFilters SearchFilters, LIMIT int, OFFSET int) : List<ItemMeta> from class warehouse.db.CRUDItems


    public static List<Listable> search(Listable listableImplementation, String query, int LIMIT, int OFFSET) {
        List<Listable> listables = new ArrayList<>();
        String sql = "SELECT *"
                + " FROM " + "" + listableImplementation.getDBEntityName() + ""
                + formulateSearchFilters(listableImplementation, query)
                + " ORDER BY " + "" + listableImplementation.getDBAttributeName() + "" + " ASC"
                + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
        try (Connection con = Connect.getConnection()) {
            PreparedStatement p = con.prepareStatement(sql);
            PreparedStatementWrapper preparedStatementWrapper
                    = formulateSearchPreparedStatement(query, new PreparedStatementWrapper(p));
            int parameterIndex = preparedStatementWrapper.getParameterIndex();
            p.setInt(++parameterIndex, OFFSET);
            p.setInt(++parameterIndex, LIMIT);
            try (ResultSet result = p.executeQuery()) {
                while (result.next()) {
                    Listable listableInstance = listableImplementation.getNewInstance();
                    listableInstance.setId(result.getInt("id"));
                    listableInstance.setName(result.getString(listableImplementation.getDBAttributeName()));
                    listables.add(listableInstance);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(CRUDListable.class.getName()).log(Level.SEVERE, null, ex);
        }
        return listables;
    }

    public static List<Listable> search(Listable listableImplementation, String query, int LIMIT, int OFFSET) {
        List<Listable> listables = new ArrayList<>();
        try {
            String sql = "SELECT *"
                    + " FROM " + "" + listableImplementation.getDBEntityName() + ""
                    + formulateSearchFilters(listableImplementation, query)
                    + " ORDER BY " + "" + listableImplementation.getDBAttributeName() + "" + " ASC"
                    + " LIMIT ? OFFSET ?";

            con = Connect.getConnection();
            PreparedStatement p;
            p = con.prepareStatement(sql);
            PreparedStatementWrapper preparedStatementWrapper
                    = formulateSearchPreparedStatement(query, new PreparedStatementWrapper(p));
            int parameterIndex = preparedStatementWrapper.getParameterIndex();
            p.setInt(++parameterIndex, LIMIT);
            p.setInt(++parameterIndex, OFFSET);
            ResultSet result = p.executeQuery();
            while (result.next()) {
                Listable listableInstance = listableImplementation.getNewInstance();
                listableInstance.setId(result.getInt("id"));
                listableInstance.setName(result.getString(listableImplementation.getDBAttributeName()));
                listables.add(listableInstance);
            }
        } catch (SQLException ex) {
            Logger.getLogger(CRUDListable.class.getName()).log(Level.SEVERE, null, ex);
        }
        return listables;
    }

Try With Resources try(ResultSet result=p.executeQuery()) in method public search(listableImplementation Listable, query String, LIMIT int, OFFSET int) : List<Listable> from class warehouse.db.CRUDListable


    private void clearAllLegalMoveImages() {
        for (ImageView imageView : legalMoveImages) {
            ScaleTransition st = imageHandlerUtil.addScaleTransition(imageView, 75, false);

            st.setOnFinished(actionEvent -> chessboardContainer.getChildren().remove(imageView));
        }
        legalMoveImages.clear();
    }

    private void clearAllLegalMoveImages() {
        for (ImageView imageView : legalMoveImages) {
            ScaleTransition st = imageHandlerUtil.addScaleTransition(imageView, 75, false);

            st.setOnFinished(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent actionEvent) {
                    chessboardContainer.getChildren().remove(imageView);
                }
            });
        }
        legalMoveImages.clear();
    }

Replace Anonymous With Lambda mindchess.controller.MindchessController.clearAllLegalMoveImages.setOnFinished.new EventHandler<ActionEvent> with actionEvent -> chessboardContainer.getChildren().remove(imageView) in method private clearAllLegalMoveImages() : void from class mindchess.controller.MindchessController


    @Override
    public Map<Square, IPiece> getBoardSnapShot() {
        return new HashMap<>(boardMap);
    }

    @Override
    public Map<Square, IPiece> getBoardSnapShot() {
        return new HashMap<Square, IPiece>(boardMap);
    }

Replace Generic With Diamond HashMap<Square,IPiece> with HashMap<> in method public getBoardSnapShot() : Map<Square,IPiece> from class mindchess.model.Board


    private List<Square> calculateMove() {
        var allBoardSquares = new ArrayList<>(board.getBoardMap().keySet());
        Random rand;

        var returnList = new ArrayList<Square>();

        while (true) {
            rand = new Random();
            Square randSquare = allBoardSquares.get(rand.nextInt(allBoardSquares.size()));
            IPiece randPiece = board.getBoardMap().get(randSquare);

            if (randPiece.getColor() == context.getCurrentPlayerColor()) {
                legalSquares = randPiece.getMoveDelegate().fetchMoves(board, randSquare, randPiece.getHasMoved(), true);
                if (legalSquares.size() > 0) {
                    returnList.add(randSquare);
                    break;
                }
            }
        }
        returnList.add(legalSquares.get(rand.nextInt(legalSquares.size())));
        return returnList;
    }

    private List<Square> calculateMove() {
        var allBoardSquares = new ArrayList<Square>(board.getBoardMap().keySet());
        Random rand;

        var returnList = new ArrayList<Square>();

        while (true) {
            rand = new Random();
            Square randSquare = allBoardSquares.get(rand.nextInt(allBoardSquares.size()));
            IPiece randPiece = board.getBoardMap().get(randSquare);

            if (randPiece.getColor() == context.getCurrentPlayerColor()) {
                legalSquares = randPiece.getMoveDelegate().fetchMoves(board, randSquare, randPiece.getHasMoved(), true);
                if (legalSquares.size() > 0) {
                    returnList.add(randSquare);
                    break;
                }
            }
        }
        returnList.add(legalSquares.get(rand.nextInt(legalSquares.size())));
        return returnList;
    }

Replace Generic With Diamond ArrayList<Square> with ArrayList<> in method private calculateMove() : List<Square> from class mindchess.model.GameStateAIPlayerTurn


/**
     * Returns a stream consisting of all elements from this stream until the
     * first element which does not match the given predicate is found
     * (including the first mismatching element).
     *
     *

     * This is a quasi-intermediate
     * operation.
     *
     *

     * While this operation is quite cheap for sequential stream, it can be
     * quite expensive on parallel pipelines. Using unordered source or making it
     * explicitly unordered with {@link #unordered()} call may improve the parallel
     * processing performance if semantics permit.
     *
     * @param predicate a non-interfering, stateless predicate to apply to
     *        elements.
     * @return the new stream.
     * @since 0.5.5
     * @see #takeWhile(Predicate)
     */
    public S takeWhileInclusive(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        Spliterator<T> spltr = spliterator();
        return supply(
            spltr.hasCharacteristics(Spliterator.ORDERED) ? new TakeDrop.TDOfRef<>(spltr, false, true, predicate)
                    : new TakeDrop.UnorderedTDOfRef<>(spltr, false, true, predicate));
    }

/**
     * Returns a stream consisting of all elements from this stream until the
     * first element which does not match the given predicate is found
     * (including the first mismatching element).
     *
     *

     * This is a quasi-intermediate
     * operation.
     *
     *

     * While this operation is quite cheap for sequential stream, it can be
     * quite expensive on parallel pipelines. Using unordered source or making it
     * explicitly unordered with {@link #unordered()} call may improve the parallel
     * processing performance if semantics permit.
     *
     * @param predicate a non-interfering, stateless predicate to apply to
     *        elements.
     * @return the new stream.
     * @since 0.5.5
     * @see #takeWhile(Predicate)
     */
    public S takeWhileInclusive(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        Spliterator<T> spltr = spliterator();
        return supply(
            spltr.hasCharacteristics(Spliterator.ORDERED) ? new TakeDrop.TDOfRef<>(spltr, false, true, predicate)
                    : new TakeDrop.UnorderedTDOfRef<T>(spltr, false, true, predicate));
    }

Replace Generic With Diamond TakeDrop.UnorderedTDOfRef<T> with TakeDrop.UnorderedTDOfRef<> in method public takeWhileInclusive(predicate Predicate<? super T>) : S from class one.util.streamex.AbstractStreamEx


/**
     * Returns a stream containing cumulative results of applying the
     * accumulation function going left to right.
     *
     *

     * This is a stateful quasi-intermediate operation.
     *
     *

     * This operation resembles {@link #scanLeft(BinaryOperator)}, but unlike
     * {@code scanLeft} this operation is intermediate and accumulation function
     * must be associative.
     *
     *

     * This method cannot take all the advantages of parallel streams as it must
     * process elements strictly left to right. Using an unordered source or
     * removing the ordering constraint with {@link #unordered()} may improve
     * the parallel processing speed.
     *
     * @param op an associative, non-interfering ,
     *        stateless
     *        function for computing the next element based on the previous one
     * @return the new stream.
     * @see #scanLeft(BinaryOperator)
     * @since 0.6.1
     */
    public S prefix(BinaryOperator<T> op) {
        Spliterator<T> spltr = spliterator();
        return supply(spltr.hasCharacteristics(Spliterator.ORDERED) ? new PrefixOps.OfRef<>(spltr, op)
                : new PrefixOps.OfUnordRef<>(spltr, op));
    }

/**
     * Returns a stream containing cumulative results of applying the
     * accumulation function going left to right.
     *
     *

     * This is a stateful quasi-intermediate operation.
     *
     *

     * This operation resembles {@link #scanLeft(BinaryOperator)}, but unlike
     * {@code scanLeft} this operation is intermediate and accumulation function
     * must be associative.
     *
     *

     * This method cannot take all the advantages of parallel streams as it must
     * process elements strictly left to right. Using an unordered source or
     * removing the ordering constraint with {@link #unordered()} may improve
     * the parallel processing speed.
     *
     * @param op an associative, non-interfering ,
     *        stateless
     *        function for computing the next element based on the previous one
     * @return the new stream.
     * @see #scanLeft(BinaryOperator)
     * @since 0.6.1
     */
    public S prefix(BinaryOperator<T> op) {
        Spliterator<T> spltr = spliterator();
        return supply(spltr.hasCharacteristics(Spliterator.ORDERED) ? new PrefixOps.OfRef<>(spltr, op)
                : new PrefixOps.OfUnordRef<T>(spltr, op));
    }

Replace Generic With Diamond PrefixOps.OfUnordRef<T> with PrefixOps.OfUnordRef<> in method public prefix(op BinaryOperator<T>) : S from class one.util.streamex.AbstractStreamEx


/**
     * Merge series of adjacent stream entries with equal keys grouping the
     * corresponding values into {@code List}.
     *
     *

     * This is a quasi-intermediate
     * partial reduction operation.
     *
     *

     * There are no guarantees on the type, mutability, serializability, or
     * thread-safety of the {@code List} objects of the resulting stream.
     *
     *

     * The key of the resulting entry is the key of the first merged entry.
     *
     * @return a new {@code EntryStream} which keys are the keys of the original
     *         stream and the values of adjacent entries with the same keys are
     *         grouped into {@code List}
     * @see StreamEx#groupRuns(BiPredicate)
     * @since 0.5.5
     */
    public EntryStream<K, List<V>> collapseKeys() {
        return new StreamEx<>(new CollapseSpliterator<>(equalKeys(),
                e -> new PairBox<>(e.getKey(), Collections.singletonList(e.getValue())), (pb, e) -> {
            if (!(pb.b instanceof ArrayList)) {
                V old = pb.b.get(0);
                pb.b = new ArrayList<>();
                pb.b.add(old);
            }
            pb.b.add(e.getValue());
            return pb;
        }, (pb1, pb2) -> {
            if (!(pb1.b instanceof ArrayList)) {
                V old = pb1.b.get(0);
                pb1.b = new ArrayList<>();
                pb1.b.add(old);
            }
            pb1.b.addAll(pb2.b);
            return pb1;
        }, spliterator()), context).mapToEntry(pb -> pb.a, pb -> pb.b);
    }

/**
     * Merge series of adjacent stream entries with equal keys grouping the
     * corresponding values into {@code List}.
     *
     *

     * This is a quasi-intermediate
     * partial reduction operation.
     *
     *

     * There are no guarantees on the type, mutability, serializability, or
     * thread-safety of the {@code List} objects of the resulting stream.
     *
     *

     * The key of the resulting entry is the key of the first merged entry.
     *
     * @return a new {@code EntryStream} which keys are the keys of the original
     *         stream and the values of adjacent entries with the same keys are
     *         grouped into {@code List}
     * @see StreamEx#groupRuns(BiPredicate)
     * @since 0.5.5
     */
    public EntryStream<K, List<V>> collapseKeys() {
        return new StreamEx<>(new CollapseSpliterator<Entry<K, V>, PairBox<K, List<V>>>(equalKeys(),
                e -> new PairBox<>(e.getKey(), Collections.singletonList(e.getValue())), (pb, e) -> {
                    if (!(pb.b instanceof ArrayList)) {
                        V old = pb.b.get(0);
                        pb.b = new ArrayList<>();
                        pb.b.add(old);
                    }
                    pb.b.add(e.getValue());
                    return pb;
                }, (pb1, pb2) -> {
                    if (!(pb1.b instanceof ArrayList)) {
                        V old = pb1.b.get(0);
                        pb1.b = new ArrayList<>();
                        pb1.b.add(old);
                    }
                    pb1.b.addAll(pb2.b);
                    return pb1;
                }, spliterator()), context).mapToEntry(pb -> pb.a, pb -> pb.b);
    }

Replace Generic With Diamond StreamEx<> with StreamEx<> in method public collapseKeys() : EntryStream<K,List<V>> from class one.util.streamex.EntryStream


/**
     * Merge series of adjacent stream entries with equal keys combining the
     * corresponding values using the provided {@code Collector}.
     *
     *

     * This is a quasi-intermediate
     * partial reduction operation.
     *
     *

     * The key of the resulting entry is the key of the first merged entry.
     *
     * @param <R> the type of the values in the resulting stream
     * @param  the intermediate accumulation type of the {@code Collector}
     * @param collector a {@code Collector} which is used to combine the values
     *        of the adjacent entries with the equal keys.
     * @return a new {@code EntryStream} which keys are the keys of the original
     *         stream and the values are values of the adjacent entries with the
     *         same keys, combined using the provided collector.
     * @see StreamEx#collapse(BiPredicate, Collector)
     * @since 0.5.5
     */
    public  EntryStream<K, R> collapseKeys(Collector<? super V, A, R> collector) {
        Supplier supplier = collector.supplier();
        BiConsumer accumulator = collector.accumulator();
        BinaryOperator combiner = collector.combiner();
        Function finisher = collector.finisher();
        return new StreamEx<>(new CollapseSpliterator<>(equalKeys(), e -> {
            A a = supplier.get();
            accumulator.accept(a, e.getValue());
            return new PairBox<>(e.getKey(), a);
        }, (pb, e) -> {
            accumulator.accept(pb.b, e.getValue());
            return pb;
        }, (pb1, pb2) -> {
            pb1.b = combiner.apply(pb1.b, pb2.b);
            return pb1;
        }, spliterator()), context).mapToEntry(pb -> pb.a, pb -> finisher.apply(pb.b));
    }

/**
     * Merge series of adjacent stream entries with equal keys combining the
     * corresponding values using the provided {@code Collector}.
     *
     *

     * This is a quasi-intermediate
     * partial reduction operation.
     *
     *

     * The key of the resulting entry is the key of the first merged entry.
     *
     * @param <R> the type of the values in the resulting stream
     * @param  the intermediate accumulation type of the {@code Collector}
     * @param collector a {@code Collector} which is used to combine the values
     *        of the adjacent entries with the equal keys.
     * @return a new {@code EntryStream} which keys are the keys of the original
     *         stream and the values are values of the adjacent entries with the
     *         same keys, combined using the provided collector.
     * @see StreamEx#collapse(BiPredicate, Collector)
     * @since 0.5.5
     */
    public  EntryStream<K, R> collapseKeys(Collector<? super V, A, R> collector) {
        Supplier supplier = collector.supplier();
        BiConsumer accumulator = collector.accumulator();
        BinaryOperator combiner = collector.combiner();
        Function finisher = collector.finisher();
        return new StreamEx<>(new CollapseSpliterator<Entry<K, V>, PairBox<K, A>>(equalKeys(), e -> {
            A a = supplier.get();
            accumulator.accept(a, e.getValue());
            return new PairBox<>(e.getKey(), a);
        }, (pb, e) -> {
            accumulator.accept(pb.b, e.getValue());
            return pb;
        }, (pb1, pb2) -> {
            pb1.b = combiner.apply(pb1.b, pb2.b);
            return pb1;
        }, spliterator()), context).mapToEntry(pb -> pb.a, pb -> finisher.apply(pb.b));
    }

Replace Generic With Diamond StreamEx<> with StreamEx<> in method public collapseKeys(collector Collector<? super V,A,R>) : EntryStream<K,R> from class one.util.streamex.EntryStream


    @Test
    public void testPlainSpliterator() {
        List<String> expected = Arrays.asList("", "a", "aa", "aaa", "aaaa", "aaab", "aab", "aaba", "aabb", "ab", "aba",
            "abaa", "abab", "abb", "abba", "abbb", "b", "ba", "baa", "baaa", "baab", "bab", "baba", "babb", "bb", "bba",
            "bbaa", "bbab", "bbb", "bbba", "bbbb");
        checkSpliterator("tree", expected, () -> new TreeSpliterator.Plain<>("", s -> s.length() == 4 ? null
                : Stream.of("a", "b").map(s::concat)));
    }

    @Test
    public void testPlainSpliterator() {
        List<String> expected = Arrays.asList("", "a", "aa", "aaa", "aaaa", "aaab", "aab", "aaba", "aabb", "ab", "aba",
            "abaa", "abab", "abb", "abba", "abbb", "b", "ba", "baa", "baaa", "baab", "bab", "baba", "babb", "bb", "bba",
            "bbaa", "bbab", "bbb", "bbba", "bbbb");
        checkSpliterator("tree", expected, () -> new TreeSpliterator.Plain<String>("", s -> s.length() == 4 ? null
                : Stream.of("a", "b").map(s::concat)));
    }

Replace Generic With Diamond TreeSpliterator.Plain<String> with TreeSpliterator.Plain<> in method public testPlainSpliterator() : void from class one.util.streamex.TreeSpliteratorTest


    @Test
    public void testDepthSpliterator() {
        List<Entry<Integer, String>> expected = StreamEx.of("", "a", "aa", "ab", "ac", "b", "ba", "bb", "bc", "c", "ca",
            "cb", "cc").mapToEntry(String::length).invert().toList();
        checkSpliterator("tree", expected, () -> new TreeSpliterator.Depth<>("", (depth, s) -> depth == 2 ? null
                : Stream.of("a", "b", "c").map(s::concat), 0));
    }

    @Test
    public void testDepthSpliterator() {
        List<Entry<Integer, String>> expected = StreamEx.of("", "a", "aa", "ab", "ac", "b", "ba", "bb", "bc", "c", "ca",
            "cb", "cc").mapToEntry(String::length).invert().toList();
        checkSpliterator("tree", expected, () -> new TreeSpliterator.Depth<String>("", (depth, s) -> depth == 2 ? null
                : Stream.of("a", "b", "c").map(s::concat)));
    }

Replace Generic With Diamond TreeSpliterator.Depth<String> with TreeSpliterator.Depth<> in method public testDepthSpliterator() : void from class one.util.streamex.TreeSpliteratorTest


/**
     * Returns an {@link OptionalLong} describing the zero-based index of the
     * first element of this stream, which matches given predicate, or an empty
     * {@code OptionalLong} if there's no matching element.
     *
     *

     * This is a short-circuiting terminal operation.
     *
     * @param predicate a non-interfering ,
     *        stateless
     *        predicate which returned value should match
     * @return an {@code OptionalLong} describing the index of the first
     *         matching element of this stream, or an empty {@code OptionalLong}
     *         if there's no matching element.
     * @see #findFirst(Predicate)
     * @see #indexOf(Object)
     * @since 0.4.0
     */
    public OptionalLong indexOf(Predicate<? super T> predicate) {
        return collect(new CancellableCollectorImpl<>(() -> new long[]{-1}, (acc, t) -> {
            if (acc[0] < 0) {
                if (predicate.test(t)) {
                    acc[0] = -acc[0] - 1;
                } else {
                    acc[0]--;
                }
            }
        }, (acc1, acc2) -> {
            if (acc1[0] < 0) {
                if (acc2[0] < 0) {
                    acc1[0] = acc1[0] + acc2[0] + 1;
                } else {
                    acc1[0] = acc2[0] - acc1[0] - 1;
                }
            }
            return acc1;
        }, acc -> acc[0] < 0 ? OptionalLong.empty() : OptionalLong.of(acc[0]), acc -> acc[0] >= 0, NO_CHARACTERISTICS));
    }

/**
     * Returns an {@link OptionalLong} describing the zero-based index of the
     * first element of this stream, which matches given predicate, or an empty
     * {@code OptionalLong} if there's no matching element.
     *
     *

     * This is a short-circuiting terminal operation.
     *
     * @param predicate a non-interfering ,
     *        stateless
     *        predicate which returned value should match
     * @return an {@code OptionalLong} describing the index of the first
     *         matching element of this stream, or an empty {@code OptionalLong}
     *         if there's no matching element.
     * @see #findFirst(Predicate)
     * @see #indexOf(Object)
     * @since 0.4.0
     */
    public OptionalLong indexOf(Predicate<? super T> predicate) {
        return collect(new CancellableCollectorImpl<T, long[], OptionalLong>(() -> new long[] { -1 }, (acc, t) -> {
            if (acc[0] < 0) {
                if (predicate.test(t)) {
                    acc[0] = -acc[0] - 1;
                } else {
                    acc[0]--;
                }
            }
        }, (acc1, acc2) -> {
            if (acc1[0] < 0) {
                if (acc2[0] < 0) {
                    acc1[0] = acc1[0] + acc2[0] + 1;
                } else {
                    acc1[0] = acc2[0] - acc1[0] - 1;
                }
            }
            return acc1;
        }, acc -> acc[0] < 0 ? OptionalLong.empty() : OptionalLong.of(acc[0]), acc -> acc[0] >= 0, NO_CHARACTERISTICS));
    }

Replace Generic With Diamond CancellableCollectorImpl<T,long[],OptionalLong> with CancellableCollectorImpl<> in method public indexOf(predicate Predicate<? super T>) : OptionalLong from class one.util.streamex.AbstractStreamEx


    static <K, V> Stream<Entry<K, V>> withValue(Stream<? extends K> s, V value) {
        return s == null ? null : s.map(key -> new SimpleImmutableEntry<>(key, value));
    }

    static <K, V> Stream<Entry<K, V>> withValue(Stream<? extends K> s, V value) {
        return s == null ? null : s.map(key -> new SimpleImmutableEntry<K, V>(key, value));
    }

Replace Generic With Diamond SimpleImmutableEntry<K,V> with SimpleImmutableEntry<> in method package withValue(s Stream<? extends K>, value V) : Stream<Entry<K,V>> from class one.util.streamex.EntryStream


    public static <T> StreamEx<T> generate(Supplier<T> supplier) {
        return StreamEx.produce(action -> {
            action.accept(supplier.get());
            return true;
        });
    }

    public static <T> Emitter<T> generate(Supplier<T> supplier) {
        return new Emitter<T>() {
            @Override
            public Emitter<T> next(Consumer<? super T> action) {
                action.accept(supplier.get());
                return this;
            }
        };
    }

Replace Anonymous With Lambda one.util.streamex.EmitterTest.generate.new Emitter<T> with action -> {action.accept(supplier.get()); in method public generate(supplier Supplier<T>) : StreamEx<T> from class one.util.streamex.StreamExTest


        /**
         * Returns the spliterator which covers all the elements emitted by this
         * emitter.
         *
         * @return the new spliterator
         */
        default Spliterator<T> spliterator() {
            return new EmitterSpliterator<>(this);
        }

        /**
         * Returns the spliterator which covers all the elements emitted by this
         * emitter.
         *
         * @return the new spliterator
         */
        default Spliterator<T> spliterator() {
            return new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE) {
                Emitter<T> e = Emitter.this;
                Spliterator<T> buf;

                @Override
                public boolean tryAdvance(Consumer<? super T> action) {
                    if (!fillBuf())
                        return false;
                    while (!buf.tryAdvance(action)) {
                        buf = null;
                        if (!fillBuf())
                            return false;
                    }
                    return true;
                }

                @Override
                public void forEachRemaining(Consumer<? super T> action) {
                    if (buf != null) {
                        buf.forEachRemaining(action);
                        buf = null;
                    }
                    Emitter<T> e = this.e;
                    this.e = null;
                    while (e != null)
                        e = e.next(action);
                }

                private boolean fillBuf() {
                    while (buf == null) {
                        if (e == null)
                            return false;
                        Builder<T> b = Stream.builder();
                        Emitter<T> next = e.next(b);
                        buf = b.build().spliterator();
                        e = next;
                    }
                    return true;
                }
            };
        }

Replace Generic With Diamond Spliterators.AbstractSpliterator<T> with EmitterSpliterator<> in method public spliterator() : Spliterator<T> from class one.util.streamex.StreamEx.Emitter


    @Test
    public void testCharacteristics() {
        PairPermutationSpliterator<Integer, Integer> spltr = new PairPermutationSpliterator<>(Arrays.asList(1, 2, 3),
                Integer::sum);
        assertTrue(spltr.hasCharacteristics(Spliterator.ORDERED));
        assertTrue(spltr.hasCharacteristics(Spliterator.SIZED));
        assertTrue(spltr.hasCharacteristics(Spliterator.SUBSIZED));
        assertEquals(3, spltr.getExactSizeIfKnown());
    }

    @Test
    public void testCharacteristics() {
        PairPermutationSpliterator<Integer, Integer> spltr = new PairPermutationSpliterator<Integer, Integer>(
                Arrays.asList(1, 2, 3), Integer::sum);
        assertTrue(spltr.hasCharacteristics(Spliterator.ORDERED));
        assertTrue(spltr.hasCharacteristics(Spliterator.SIZED));
        assertTrue(spltr.hasCharacteristics(Spliterator.SUBSIZED));
        assertEquals(3, spltr.getExactSizeIfKnown());
    }

Replace Generic With Diamond PairPermutationSpliterator<Integer,Integer> with PairPermutationSpliterator<> in method public testCharacteristics() : void from class one.util.streamex.PairPermutationSpliteratorTest


    /**
     * Returns a {@link List} containing the elements of this stream. The
     * returned {@code List} is guaranteed to be mutable, but there are no
     * guarantees on the type, serializability, or thread-safety; if more
     * control over the returned {@code List} is required, use
     * {@link #toCollection(Supplier)}.
     *
     * <p>
     * This is a terminal operation.
     *
     * @return a {@code List} containing the elements of this stream
     * @see Collectors#toList()
     */
    @SuppressWarnings("unchecked")
    public List<T> toList() {
        return new ArrayList<>((Collection<T>) new ArrayCollection(toArray(Object[]::new)));
    }

    /**
     * Returns a {@link List} containing the elements of this stream. The
     * returned {@code List} is guaranteed to be mutable, but there are no
     * guarantees on the type, serializability, or thread-safety; if more
     * control over the returned {@code List} is required, use
     * {@link #toCollection(Supplier)}.
     *
     * <p>
     * This is a terminal operation.
     *
     * @return a {@code List} containing the elements of this stream
     * @see Collectors#toList()
     */
    @SuppressWarnings("unchecked")
    public List<T> toList() {
        return new ArrayList<T>((Collection<T>) new ArrayCollection(toArray()));
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method public toList() : List<T> from class one.util.streamex.AbstractStreamEx


/**
     * Returns a {@code Collector} which collects the stream element if stream
     * contains exactly one element.
     *
     *

     * This method returns a short-circuiting
     * collector.
     *
     * @param <T>
     *            the type of the input elements
     * @return a collector which returns an {@link Optional} which describes the
     *         only element of the stream. For empty stream or stream containing
     *         more than one element an empty {@code Optional} is returned.
     * @since 0.4.0
     */
    public static <T> Collector<T, ?, Optional<T>> onlyOne() {
        return new CancellableCollectorImpl<>(() -> new Box<Optional<T>>(null),
                (box, t) -> box.a = box.a == null ? Optional.of(t) : Optional.empty(),
                (box1, box2) -> box1.a == null ? box2 : box2.a == null ? box1 : new Box<>(Optional.empty()),
                box -> box.a == null ? Optional.empty() : box.a, box -> box.a != null && !box.a.isPresent(),
                UNORDERED_CHARACTERISTICS);
    }

/**
     * Returns a {@code Collector} which collects the stream element if stream
     * contains exactly one element.
     *
     *

     * This method returns a short-circuiting
     * collector.
     *
     * @param <T>
     *            the type of the input elements
     * @return a collector which returns an {@link Optional} which describes the
     *         only element of the stream. For empty stream or stream containing
     *         more than one element an empty {@code Optional} is returned.
     */
    public static <T> Collector<T, ?, Optional<T>> onlyOne() {
        return new CancellableCollectorImpl<T, Box<Optional<T>>, Optional<T>>(() -> new Box<>(null),
                (box, t) -> box.a = box.a == null ? Optional.of(t) : Optional.empty(),
                (box1, box2) -> box1.a == null ? box2 : box2.a == null ? box1 : new Box<>(Optional.empty()),
                box -> box.a == null ? Optional.empty() : box.a, box -> box.a != null && !box.a.isPresent(),
                UNORDERED_CHARACTERISTICS);
    }

Replace Generic With Diamond CancellableCollectorImpl<T,Box<Optional<T>>,Optional<T>> with CancellableCollectorImpl<> in method public onlyOne() : Collector<T,?,Optional<T>> from class javax.util.streamex.MoreCollectors


/**
     * Returns a {@code Collector} which collects only the first stream element
     * if any.
     *
     *

     * This method returns a short-circuiting
     * collector.
     *
     *

     * The operation performed by the returned collector is equivalent to
     * {@code stream.findFirst()}. This collector is mostly useful as a
     * downstream collector.
     *
     * @param <T>
     *            the type of the input elements
     * @return a collector which returns an {@link Optional} which describes the
     *         first element of the stream. For empty stream an empty
     *         {@code Optional} is returned.
     */
    public static <T> Collector<T, ?, Optional<T>> first() {
        return new CancellableCollectorImpl<>(() -> new Box<T>(none()), (box, t) -> {
            if (box.a == NONE)
                box.a = t;
        }, (box1, box2) -> box1.a == NONE ? box2 : box1, box -> box.a == NONE ? Optional.empty() : Optional.of(box.a),
                box -> box.a != NONE, NO_CHARACTERISTICS);
    }

/**
     * Returns a {@code Collector} which collects only the first stream element
     * if any.
     *
     *

     * This method returns a short-circuiting
     * collector.
     *
     *

     * The operation performed by the returned collector is equivalent to
     * {@code stream.findFirst()}. This collector is mostly useful as a
     * downstream collector.
     *
     * @param <T>
     *            the type of the input elements
     * @return a collector which returns an {@link Optional} which describes the
     *         first element of the stream. For empty stream an empty
     *         {@code Optional} is returned.
     */
    public static <T> Collector<T, ?, Optional<T>> first() {
        return new CancellableCollectorImpl<T, Box<T>, Optional<T>>(() -> new Box<>(none()), (box, t) -> {
            if (box.a == NONE)
                box.a = t;
        }, (box1, box2) -> box1.a == NONE ? box2 : box1, box -> box.a == NONE ? Optional.empty() : Optional.of(box.a),
                box -> box.a != NONE, NO_CHARACTERISTICS);
    }

Replace Generic With Diamond CancellableCollectorImpl<T,Box<T>,Optional<T>> with CancellableCollectorImpl<> in method public first() : Collector<T,?,Optional<T>> from class javax.util.streamex.MoreCollectors


    static <R> DoubleCollector<R, R> of(Supplier<R> supplier, ObjDoubleConsumer<R> doubleAccumulator,
            BiConsumer<R, R> merger) {
        return new DoubleCollectorImpl<>(supplier, doubleAccumulator, merger, Function.identity(), ID_CHARACTERISTICS);
    }

    static <R> DoubleCollector<R, R> of(Supplier<R> supplier, ObjDoubleConsumer<R> doubleAccumulator,
            BiConsumer<R, R> merger) {
        return new DoubleCollector<R, R>() {

            @Override
            public Supplier<R> supplier() {
                return supplier;
            }

            @Override
            public Function<R, R> finisher() {
                return Function.identity();
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.of(Collector.Characteristics.IDENTITY_FINISH);
            }

            @Override
            public ObjDoubleConsumer<R> doubleAccumulator() {
                return doubleAccumulator;
            }

            @Override
            public BiConsumer<R, R> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond DoubleCollector<R,R> with DoubleCollectorImpl<> in method public of(supplier Supplier<R>, doubleAccumulator ObjDoubleConsumer<R>, merger BiConsumer<R,R>) : DoubleCollector<R,R> from class javax.util.streamex.DoubleCollector


    static <A, R> DoubleCollector<A, R> of(Supplier<A> supplier, ObjDoubleConsumer<A> doubleAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new DoubleCollectorImpl<>(supplier, doubleAccumulator, merger, finisher, NO_CHARACTERISTICS);
    }

    static <A, R> DoubleCollector<A, R> of(Supplier<A> supplier, ObjDoubleConsumer<A> doubleAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new DoubleCollector<A, R>() {

            @Override
            public Supplier<A> supplier() {
                return supplier;
            }

            @Override
            public Function<A, R> finisher() {
                return finisher;
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.noneOf(Collector.Characteristics.class);
            }

            @Override
            public ObjDoubleConsumer<A> doubleAccumulator() {
                return doubleAccumulator;
            }

            @Override
            public BiConsumer<A, A> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond DoubleCollector<A,R> with DoubleCollectorImpl<> in method public of(supplier Supplier<A>, doubleAccumulator ObjDoubleConsumer<A>, merger BiConsumer<A,A>, finisher Function<A,R>) : DoubleCollector<A,R> from class javax.util.streamex.DoubleCollector


    static <R> IntCollector<R, R> of(Supplier<R> supplier, ObjIntConsumer<R> intAccumulator, BiConsumer<R, R> merger) {
        return new IntCollectorImpl<>(supplier, intAccumulator, merger, Function.identity(), ID_CHARACTERISTICS);
    }

    static <R> IntCollector<R, R> of(Supplier<R> supplier, ObjIntConsumer<R> intAccumulator, BiConsumer<R, R> merger) {
        return new IntCollector<R, R>() {

            @Override
            public Supplier<R> supplier() {
                return supplier;
            }

            @Override
            public Function<R, R> finisher() {
                return Function.identity();
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.of(Collector.Characteristics.IDENTITY_FINISH);
            }

            @Override
            public ObjIntConsumer<R> intAccumulator() {
                return intAccumulator;
            }

            @Override
            public BiConsumer<R, R> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond IntCollector<R,R> with IntCollectorImpl<> in method public of(supplier Supplier<R>, intAccumulator ObjIntConsumer<R>, merger BiConsumer<R,R>) : IntCollector<R,R> from class javax.util.streamex.IntCollector


    static <A, R> IntCollector<A, R> of(Supplier<A> supplier, ObjIntConsumer<A> intAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new IntCollectorImpl<>(supplier, intAccumulator, merger, finisher, NO_CHARACTERISTICS);
    }

    static <A, R> IntCollector<A, R> of(Supplier<A> supplier, ObjIntConsumer<A> intAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new IntCollector<A, R>() {

            @Override
            public Supplier<A> supplier() {
                return supplier;
            }

            @Override
            public Function<A, R> finisher() {
                return finisher;
            }

            @Override
            public ObjIntConsumer<A> intAccumulator() {
                return intAccumulator;
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.noneOf(Collector.Characteristics.class);
            }

            @Override
            public BiConsumer<A, A> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond IntCollector<A,R> with IntCollectorImpl<> in method public of(supplier Supplier<A>, intAccumulator ObjIntConsumer<A>, merger BiConsumer<A,A>, finisher Function<A,R>) : IntCollector<A,R> from class javax.util.streamex.IntCollector


    static <R> LongCollector<R, R> of(Supplier<R> supplier, ObjLongConsumer<R> longAccumulator, BiConsumer<R, R> merger) {
        return new LongCollectorImpl<>(supplier, longAccumulator, merger, Function.identity(), ID_CHARACTERISTICS);
    }

    static <R> LongCollector<R, R> of(Supplier<R> supplier, ObjLongConsumer<R> longAccumulator, BiConsumer<R, R> merger) {
        return new LongCollector<R, R>() {

            @Override
            public Supplier<R> supplier() {
                return supplier;
            }

            @Override
            public Function<R, R> finisher() {
                return Function.identity();
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.of(Collector.Characteristics.IDENTITY_FINISH);
            }

            @Override
            public ObjLongConsumer<R> longAccumulator() {
                return longAccumulator;
            }

            @Override
            public BiConsumer<R, R> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond LongCollector<R,R> with LongCollectorImpl<> in method public of(supplier Supplier<R>, longAccumulator ObjLongConsumer<R>, merger BiConsumer<R,R>) : LongCollector<R,R> from class javax.util.streamex.LongCollector


    static <A, R> LongCollector<A, R> of(Supplier<A> supplier, ObjLongConsumer<A> longAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new LongCollectorImpl<>(supplier, longAccumulator, merger, finisher, NO_CHARACTERISTICS);
    }

    static <A, R> LongCollector<A, R> of(Supplier<A> supplier, ObjLongConsumer<A> longAccumulator,
            BiConsumer<A, A> merger, Function<A, R> finisher) {
        return new LongCollector<A, R>() {

            @Override
            public Supplier<A> supplier() {
                return supplier;
            }

            @Override
            public Function<A, R> finisher() {
                return finisher;
            }

            @Override
            public ObjLongConsumer<A> longAccumulator() {
                return longAccumulator;
            }

            @Override
            public Set<Collector.Characteristics> characteristics() {
                return EnumSet.noneOf(Collector.Characteristics.class);
            }

            @Override
            public BiConsumer<A, A> merger() {
                return merger;
            }
        };
    }

Replace Generic With Diamond LongCollector<A,R> with LongCollectorImpl<> in method public of(supplier Supplier<A>, longAccumulator ObjLongConsumer<A>, merger BiConsumer<A,A>, finisher Function<A,R>) : LongCollector<A,R> from class javax.util.streamex.LongCollector


        @Override
        public <T> StreamEx<T> newStreamEx(Stream<T> src) {
            return new CustomStreamEx<>(src, this);
        }

        @Override
        public <T> StreamEx<T> newStreamEx(Stream<T> src) {
            return new StreamEx<T>(src) {
                @Override
                StreamManagingStrategy strategy() {
                    return CustomPoolStreamManagingStrategy.this;
                }
            };
        }

Replace Generic With Diamond StreamEx<T> with CustomStreamEx<> in method public newStreamEx(src Stream<T>) : StreamEx<T> from class javax.util.streamex.StreamManagingStrategy.CustomPoolStreamManagingStrategy


        @Override
        public <K, V> EntryStream<K, V> newEntryStream(Stream<Entry<K, V>> src) {
            return new CustomEntryStream<>(src, this);
        }

        @Override
        public <K, V> EntryStream<K, V> newEntryStream(Stream<Entry<K, V>> src) {
            return new EntryStream<K, V>(src) {
                @Override
                StreamManagingStrategy strategy() {
                    return CustomPoolStreamManagingStrategy.this;
                }
            };
        }

Replace Generic With Diamond EntryStream<K,V> with CustomEntryStream<> in method public newEntryStream(src Stream<Entry<K,V>>) : EntryStream<K,V> from class javax.util.streamex.StreamManagingStrategy.CustomPoolStreamManagingStrategy


    public <K, V> EntryStream<K, V> flatMapToEntry(Function<? super T, Map<K, V>> mapper) {
        return new EntryStream<>(stream.flatMap(e -> mapper.apply(e).entrySet().stream()));
    }

    public <K, V> EntryStream<K, V> flatMapToEntry(Function<? super T, Map<K, V>> mapper) {
        return new EntryStream<K, V>(stream.flatMap(e -> mapper.apply(e).entrySet().stream()));
    }

Replace Generic With Diamond EntryStream<K,V> with EntryStream<> in method public flatMapToEntry(mapper Function<? super T,Map<K,V>>) : EntryStream<K,V> from class javax.util.streamex.StreamEx


@Override
	public boolean useAdminCommand(String command, L2PcInstance activeChar)
	{
		StringTokenizer st = new StringTokenizer(command);
		String actualCommand = st.nextToken();
		try
		{
			if (actualCommand.equals("admin_event"))
			{
				if (L2Event.eventState != EventState.OFF)
				{
					showEventControl(activeChar);
				}
				else
				{
					showMainPage(activeChar);
				}
			}

			else if (actualCommand.equals("admin_event_new"))
			{
				showNewEventPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_add"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event info.
				tempBuffer += command.substring(10);
				showNewEventPage(activeChar);

			}
			else if (actualCommand.startsWith("admin_event_see"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				String eventName = command.substring(16);
				try
				{
					final NpcHtmlMessage adminReply = new NpcHtmlMessage();

					try (FileInputStream fis = new FileInputStream(Config.DATAPACK_ROOT + "/data/events/" + eventName);
						InputStreamReader isr = new InputStreamReader(fis);
						BufferedReader br = new BufferedReader(isr))
					{
						adminReply.setFile("en", "data/html/mods/EventEngine/Participation.htm");
						adminReply.replace("%eventName%", eventName);
						adminReply.replace("%eventCreator%", br.readLine());
						adminReply.replace("%eventInfo%", br.readLine());
						adminReply.replace("npc_%objectId%_event_participate", "admin_event"); // Weird, but nice hack, isnt it? :)
						adminReply.replace("button value=\"Participate\"", "button value=\"Back\"");
						activeChar.sendPacket(adminReply);
					}
				}
				catch (Exception e)
				{

					e.printStackTrace();

				}

			}
			else if (actualCommand.startsWith("admin_event_del"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				String eventName = command.substring(16);
				File file = new File(Config.DATAPACK_ROOT + "/data/events/" + eventName);
				file.delete();
				showMainPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_name"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				tempName += command.substring(17);
				showNewEventPage(activeChar);
			}
			else if (actualCommand.equalsIgnoreCase("admin_delete_buffer"))
			{
				tempBuffer = "";
				showNewEventPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_store"))
			{
				try
				{
					try (FileOutputStream file = new FileOutputStream(new File(Config.DATAPACK_ROOT, "data/events/" + tempName));
						PrintStream p = new PrintStream(file))
					{
						p.println(activeChar.getName());
						p.println(tempBuffer);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				tempBuffer = "";
				tempName = "";
				showMainPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_set"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				L2Event._eventName = command.substring(16);
				showEventParameters(activeChar, 2);
			}
			else if (actualCommand.startsWith("admin_event_change_teams_number"))
			{
				showEventParameters(activeChar, Integer.parseInt(st.nextToken()));
			}
			else if (actualCommand.startsWith("admin_event_panel"))
			{
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_announce"))
			{
				L2Event._npcId = Integer.parseInt(st.nextToken());
				L2Event._teamsNumber = Integer.parseInt(st.nextToken());
				String temp = " ";
				String temp2 = "";
				while (st.hasMoreElements())
				{
					temp += st.nextToken() + " ";
				}

				st = new StringTokenizer(temp, "-");

				Integer i = 1;

				while (st.hasMoreElements())
				{
					temp2 = st.nextToken();
					if (!temp2.equals(" "))
					{
						L2Event._teamNames.put(i++, temp2.substring(1, temp2.length() - 1));
					}
				}

				activeChar.sendMessage(L2Event.startEventParticipation());
				Broadcast.toAllOnlinePlayers(activeChar.getName() + " has started an event. You will find a participation NPC somewhere around you.");

				PlaySound _snd = new PlaySound(1, "B03_F", 0, 0, 0, 0, 0);
				activeChar.sendPacket(_snd);
				activeChar.broadcastPacket(_snd);

				final NpcHtmlMessage adminReply = new NpcHtmlMessage();

				final String replyMSG = StringUtil.concat("<title>[ L2J EVENT ENGINE ]</title>
", "The event ", L2Event._eventName, " has been announced, now you can type //event_panel to see the event panel control
", "");
				adminReply.setHtml(replyMSG);
				activeChar.sendPacket(adminReply);
			}
			else if (actualCommand.startsWith("admin_event_control_begin"))
			{
				// Starts the event and sends a message of the result
				activeChar.sendMessage(L2Event.startEvent());
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_finish"))
			{
				// Finishes the event and sends a message of the result
				activeChar.sendMessage(L2Event.finishEvent());
			}
			else if (actualCommand.startsWith("admin_event_control_teleport"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					int teamId = Integer.parseInt(st.nextToken());

					for (L2PcInstance player : L2Event._teams.get(teamId))
					{
						player.setTitle(L2Event._teamNames.get(teamId));
						player.teleToLocation(activeChar.getLocation(), true);
						player.setInstanceId(activeChar.getInstanceId());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_sit"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					// Integer.parseInt(st.nextToken()) == teamId
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						if (player.getEventStatus() == null)
						{
							continue;
						}

						player.getEventStatus().setSitForced(!player.getEventStatus().isSitForced());
						if (player.getEventStatus().isSitForced())
						{
							player.sitDown();
						}
						else
						{
							player.standUp();
						}
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_kill"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.reduceCurrentHp(player.getMaxHp() + player.getMaxCp() + 1, activeChar, null);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_res"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						if ((player == null) || !player.isDead())
						{
							continue;
						}
						player.restoreExp(100.0);
						player.doRevive();
						player.setCurrentHpMp(player.getMaxHp(), player.getMaxMp());
						player.setCurrentCp(player.getMaxCp());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_poly"))
			{
				int teamId = Integer.parseInt(st.nextToken());
				String[] polyIds = new String[st.countTokens()];
				int i = 0;
				while (st.hasMoreElements()) // Every next ST should be a polymorph ID
				{
					polyIds[i++] = st.nextToken();
				}

				for (L2PcInstance player : L2Event._teams.get(teamId))
				{
					player.getPoly().setPolyInfo("npc", polyIds[Rnd.get(polyIds.length)]);
					player.teleToLocation(player.getLocation(), true);
					CharInfo info1 = new CharInfo(player);
					player.broadcastPacket(info1);
					UserInfo info2 = new UserInfo(player);
					player.sendPacket(info2);
					player.broadcastPacket(new ExBrExtraUserInfo(player));
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_unpoly"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.getPoly().setPolyInfo(null, "1");
						player.decayMe();
						player.spawnMe(player.getX(), player.getY(), player.getZ());
						CharInfo info1 = new CharInfo(player);
						player.broadcastPacket(info1);
						UserInfo info2 = new UserInfo(player);
						player.sendPacket(info2);
						player.broadcastPacket(new ExBrExtraUserInfo(player));
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_transform"))
			{
				int teamId = Integer.parseInt(st.nextToken());
				int[] transIds = new int[st.countTokens()];
				int i = 0;
				while (st.hasMoreElements()) // Every next ST should be a transform ID
				{
					transIds[i++] = Integer.parseInt(st.nextToken());
				}

				for (L2PcInstance player : L2Event._teams.get(teamId))
				{
					int transId = transIds[Rnd.get(transIds.length)];
					if (!TransformData.getInstance().transformPlayer(transId, player))
					{
						AdminData.getInstance().broadcastMessageToGMs("EventEngine: Unknow transformation id: " + transId);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_untransform"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.stopTransformation(true);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_kick"))
			{
				if (st.hasMoreElements()) // If has next token, it should be player name.
				{
					while (st.hasMoreElements())
					{
						L2PcInstance player = L2World.getInstance().getPlayer(st.nextToken());
						if (player != null)
						{
							L2Event.removeAndResetPlayer(player);
						}
					}
				}
				else
				{
					if ((activeChar.getTarget() != null) && (activeChar.getTarget() instanceof L2PcInstance))
					{
						L2Event.removeAndResetPlayer((L2PcInstance) activeChar.getTarget());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_prize"))
			{
				int[] teamIds = new int[st.countTokens() - 2];
				int i = 0;
				while ((st.countTokens() - 2) > 0) // The last 2 tokens are used for "n" and "item id"
				{
					teamIds[i++] = Integer.parseInt(st.nextToken());
				}

				String[] n = st.nextToken().split("\\*");
				int itemId = Integer.parseInt(st.nextToken());

				for (int teamId : teamIds)
				{
					rewardTeam(activeChar, teamId, Integer.parseInt(n[0]), itemId, n.length == 2 ? n[1] : "");
				}
				showEventControl(activeChar);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			AdminData.getInstance().broadcastMessageToGMs("EventEngine: Error! Possible blank boxes while executing a command which requires a value in the box?");
		}
		return true;
	}

@Override
	public boolean useAdminCommand(String command, L2PcInstance activeChar)
	{
		StringTokenizer st = new StringTokenizer(command);
		String actualCommand = st.nextToken();
		try
		{
			if (actualCommand.equals("admin_event"))
			{
				if (L2Event.eventState != EventState.OFF)
				{
					showEventControl(activeChar);
				}
				else
				{
					showMainPage(activeChar);
				}
			}

			else if (actualCommand.equals("admin_event_new"))
			{
				showNewEventPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_add"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event info.
				tempBuffer += command.substring(10);
				showNewEventPage(activeChar);

			}
			else if (actualCommand.startsWith("admin_event_see"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				String eventName = command.substring(16);
				try
				{
					final NpcHtmlMessage adminReply = new NpcHtmlMessage();

					DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(Config.DATAPACK_ROOT + "/data/events/" + eventName)));
					BufferedReader inbr = new BufferedReader(new InputStreamReader(in));
					adminReply.setFile("en", "data/html/mods/EventEngine/Participation.htm");
					adminReply.replace("%eventName%", eventName);
					adminReply.replace("%eventCreator%", inbr.readLine());
					adminReply.replace("%eventInfo%", inbr.readLine());
					adminReply.replace("npc_%objectId%_event_participate", "admin_event"); // Weird, but nice hack, isnt it? :)
					adminReply.replace("button value=\"Participate\"", "button value=\"Back\"");
					activeChar.sendPacket(adminReply);
					inbr.close();
				}
				catch (Exception e)
				{

					e.printStackTrace();

				}

			}
			else if (actualCommand.startsWith("admin_event_del"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				String eventName = command.substring(16);
				File file = new File(Config.DATAPACK_ROOT + "/data/events/" + eventName);
				file.delete();
				showMainPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_name"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				tempName += command.substring(17);
				showNewEventPage(activeChar);
			}
			else if (actualCommand.equalsIgnoreCase("admin_delete_buffer"))
			{
				tempBuffer = "";
				showNewEventPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_store"))
			{
				try
				{
					FileOutputStream file = new FileOutputStream(new File(Config.DATAPACK_ROOT, "data/events/" + tempName));
					PrintStream p = new PrintStream(file);
					p.println(activeChar.getName());
					p.println(tempBuffer);
					file.close();
					p.close();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				tempBuffer = "";
				tempName = "";
				showMainPage(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_set"))
			{
				// There is an exception here for not using the ST. We use spaces (ST delim) for the event name.
				L2Event._eventName = command.substring(16);
				showEventParameters(activeChar, 2);
			}
			else if (actualCommand.startsWith("admin_event_change_teams_number"))
			{
				showEventParameters(activeChar, Integer.parseInt(st.nextToken()));
			}
			else if (actualCommand.startsWith("admin_event_panel"))
			{
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_announce"))
			{
				L2Event._npcId = Integer.parseInt(st.nextToken());
				L2Event._teamsNumber = Integer.parseInt(st.nextToken());
				String temp = " ";
				String temp2 = "";
				while (st.hasMoreElements())
				{
					temp += st.nextToken() + " ";
				}

				st = new StringTokenizer(temp, "-");

				Integer i = 1;

				while (st.hasMoreElements())
				{
					temp2 = st.nextToken();
					if (!temp2.equals(" "))
					{
						L2Event._teamNames.put(i++, temp2.substring(1, temp2.length() - 1));
					}
				}

				activeChar.sendMessage(L2Event.startEventParticipation());
				Broadcast.toAllOnlinePlayers(activeChar.getName() + " has started an event. You will find a participation NPC somewhere around you.");

				PlaySound _snd = new PlaySound(1, "B03_F", 0, 0, 0, 0, 0);
				activeChar.sendPacket(_snd);
				activeChar.broadcastPacket(_snd);

				final NpcHtmlMessage adminReply = new NpcHtmlMessage();

				final String replyMSG = StringUtil.concat("<title>[ L2J EVENT ENGINE ]</title>
", "The event ", L2Event._eventName, " has been announced, now you can type //event_panel to see the event panel control
", "");
				adminReply.setHtml(replyMSG);
				activeChar.sendPacket(adminReply);
			}
			else if (actualCommand.startsWith("admin_event_control_begin"))
			{
				// Starts the event and sends a message of the result
				activeChar.sendMessage(L2Event.startEvent());
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_finish"))
			{
				// Finishes the event and sends a message of the result
				activeChar.sendMessage(L2Event.finishEvent());
			}
			else if (actualCommand.startsWith("admin_event_control_teleport"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					int teamId = Integer.parseInt(st.nextToken());

					for (L2PcInstance player : L2Event._teams.get(teamId))
					{
						player.setTitle(L2Event._teamNames.get(teamId));
						player.teleToLocation(activeChar.getLocation(), true);
						player.setInstanceId(activeChar.getInstanceId());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_sit"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					// Integer.parseInt(st.nextToken()) == teamId
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						if (player.getEventStatus() == null)
						{
							continue;
						}

						player.getEventStatus().setSitForced(!player.getEventStatus().isSitForced());
						if (player.getEventStatus().isSitForced())
						{
							player.sitDown();
						}
						else
						{
							player.standUp();
						}
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_kill"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.reduceCurrentHp(player.getMaxHp() + player.getMaxCp() + 1, activeChar, null);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_res"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						if ((player == null) || !player.isDead())
						{
							continue;
						}
						player.restoreExp(100.0);
						player.doRevive();
						player.setCurrentHpMp(player.getMaxHp(), player.getMaxMp());
						player.setCurrentCp(player.getMaxCp());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_poly"))
			{
				int teamId = Integer.parseInt(st.nextToken());
				String[] polyIds = new String[st.countTokens()];
				int i = 0;
				while (st.hasMoreElements()) // Every next ST should be a polymorph ID
				{
					polyIds[i++] = st.nextToken();
				}

				for (L2PcInstance player : L2Event._teams.get(teamId))
				{
					player.getPoly().setPolyInfo("npc", polyIds[Rnd.get(polyIds.length)]);
					player.teleToLocation(player.getLocation(), true);
					CharInfo info1 = new CharInfo(player);
					player.broadcastPacket(info1);
					UserInfo info2 = new UserInfo(player);
					player.sendPacket(info2);
					player.broadcastPacket(new ExBrExtraUserInfo(player));
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_unpoly"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.getPoly().setPolyInfo(null, "1");
						player.decayMe();
						player.spawnMe(player.getX(), player.getY(), player.getZ());
						CharInfo info1 = new CharInfo(player);
						player.broadcastPacket(info1);
						UserInfo info2 = new UserInfo(player);
						player.sendPacket(info2);
						player.broadcastPacket(new ExBrExtraUserInfo(player));
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_transform"))
			{
				int teamId = Integer.parseInt(st.nextToken());
				int[] transIds = new int[st.countTokens()];
				int i = 0;
				while (st.hasMoreElements()) // Every next ST should be a transform ID
				{
					transIds[i++] = Integer.parseInt(st.nextToken());
				}

				for (L2PcInstance player : L2Event._teams.get(teamId))
				{
					int transId = transIds[Rnd.get(transIds.length)];
					if (!TransformData.getInstance().transformPlayer(transId, player))
					{
						AdminData.getInstance().broadcastMessageToGMs("EventEngine: Unknow transformation id: " + transId);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_untransform"))
			{
				while (st.hasMoreElements()) // Every next ST should be a team number
				{
					for (L2PcInstance player : L2Event._teams.get(Integer.parseInt(st.nextToken())))
					{
						player.stopTransformation(true);
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_kick"))
			{
				if (st.hasMoreElements()) // If has next token, it should be player name.
				{
					while (st.hasMoreElements())
					{
						L2PcInstance player = L2World.getInstance().getPlayer(st.nextToken());
						if (player != null)
						{
							L2Event.removeAndResetPlayer(player);
						}
					}
				}
				else
				{
					if ((activeChar.getTarget() != null) && (activeChar.getTarget() instanceof L2PcInstance))
					{
						L2Event.removeAndResetPlayer((L2PcInstance) activeChar.getTarget());
					}
				}
				showEventControl(activeChar);
			}
			else if (actualCommand.startsWith("admin_event_control_prize"))
			{
				int[] teamIds = new int[st.countTokens() - 2];
				int i = 0;
				while ((st.countTokens() - 2) > 0) // The last 2 tokens are used for "n" and "item id"
				{
					teamIds[i++] = Integer.parseInt(st.nextToken());
				}

				String[] n = st.nextToken().split("\\*");
				int itemId = Integer.parseInt(st.nextToken());

				for (int teamId : teamIds)
				{
					rewardTeam(activeChar, teamId, Integer.parseInt(n[0]), itemId, n.length == 2 ? n[1] : "");
				}
				showEventControl(activeChar);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			AdminData.getInstance().broadcastMessageToGMs("EventEngine: Error! Possible blank boxes while executing a command which requires a value in the box?");
		}
		return true;
	}

Try With Resources try(FileInputStream fis=new FileInputStream(Config.DATAPACK_ROOT + "/data/events/" + eventName); InputStreamReader isr=new InputStreamReader(fis); BufferedReader br=new BufferedReader(isr)) in method public useAdminCommand(command String, activeChar L2PcInstance) : boolean from class handlers.admincommandhandlers.AdminEventEngine


	@Override
	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		final QuestState st = getQuestState(player, false);
		if (st == null)
		{
			return null;
		}

		String htmltext = null;
		switch (event)
		{
			case "32593-04.htm":
			case "32593-06.htm":
			{
				htmltext = event;
				break;
			}
			case "32593-05.htm":
			{
				st.startQuest();
				htmltext = event;
				break;
			}
			case "32597-02.html":
			case "32597-06.html":
			{
				htmltext = event;
				break;
			}
			case "32597-07.html":
			{
				st.setCond(2, true);
				htmltext = event;
				break;
			}
			case "32784-02.html":
			{
				if (st.isCond(2))
				{
					htmltext = event;
				}
				break;
			}
			case "32784-03.html":
			{
				if (st.isCond(2))
				{
					st.setCond(3, true);
					htmltext = event;
				}
				break;
			}
			case "32784-06.html":
			{
				if (st.isCond(4) && hasItem(player, ELCADIAS_MARK))
				{
					playSound(player, QuestSound.ITEMSOUND_QUEST_MIDDLE);
					htmltext = event;
				}
				break;
			}
			case "32784-08.html":
			{
				if (st.isCond(4) && hasItem(player, ELCADIAS_MARK))
				{
					takeItem(player, ELCADIAS_MARK);
					st.setCond(5, true);
					htmltext = event;
				}
				break;
			}
			case "32784-12.html":
			case "32784-13.html":
			{
				if (st.isCond(6))
				{
					htmltext = event;
				}
				break;
			}
			case "32784-14.html":
			{
				if (st.isCond(6))
				{
					st.setCond(7, true);
					htmltext = event;
				}
				break;
			}
			case "SPAWN":
			{
				if (st.isCond(5))
				{
					isBusy = true;
					final L2Npc creature1 = addSpawn(CREATURE_OF_THE_DUSK1, 89440, -238016, -9632, 335, false, 0, false, player.getInstanceId());
					creature1.setIsNoRndWalk(true);
					final L2Npc creature2 = addSpawn(CREATURE_OF_THE_DUSK2, 89524, -238131, -9632, 56, false, 0, false, player.getInstanceId());
					creature2.setIsNoRndWalk(true);
					ThreadPoolManager.getInstance().scheduleGeneral(() ->
					{
						creature1.deleteMe();
						creature2.deleteMe();
						st.unset("ex");
						isBusy = false;
					}, 60000);
				}
				break;
			}
			case "30832-02.html":
			{
				if (st.isCond(7))
				{
					st.setCond(8, true);
					htmltext = event;
				}
				break;
			}
			case "30832-03.html":
			{
				if (st.isCond(8))
				{
					htmltext = event;
				}
				break;
			}
		}
		return htmltext;
	}

	@Override
	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		final QuestState st = getQuestState(player, false);
		if (st == null)
		{
			return null;
		}

		String htmltext = null;
		switch (event)
		{
			case "32593-04.htm":
			case "32593-06.htm":
			{
				htmltext = event;
				break;
			}
			case "32593-05.htm":
			{
				st.startQuest();
				htmltext = event;
				break;
			}
			case "32597-02.html":
			case "32597-06.html":
			{
				htmltext = event;
				break;
			}
			case "32597-07.html":
			{
				st.setCond(2, true);
				htmltext = event;
				break;
			}
			case "32784-02.html":
			{
				if (st.isCond(2))
				{
					htmltext = event;
				}
				break;
			}
			case "32784-03.html":
			{
				if (st.isCond(2))
				{
					st.setCond(3, true);
					htmltext = event;
				}
				break;
			}
			case "32784-06.html":
			{
				if (st.isCond(4) && hasItem(player, ELCADIAS_MARK))
				{
					playSound(player, QuestSound.ITEMSOUND_QUEST_MIDDLE);
					htmltext = event;
				}
				break;
			}
			case "32784-08.html":
			{
				if (st.isCond(4) && hasItem(player, ELCADIAS_MARK))
				{
					takeItem(player, ELCADIAS_MARK);
					st.setCond(5, true);
					htmltext = event;
				}
				break;
			}
			case "32784-12.html":
			case "32784-13.html":
			{
				if (st.isCond(6))
				{
					htmltext = event;
				}
				break;
			}
			case "32784-14.html":
			{
				if (st.isCond(6))
				{
					st.setCond(7, true);
					htmltext = event;
				}
				break;
			}
			case "SPAWN":
			{
				if (st.isCond(5))
				{
					isBusy = true;
					final L2Npc creature1 = addSpawn(CREATURE_OF_THE_DUSK1, 89440, -238016, -9632, 335, false, 0, false, player.getInstanceId());
					creature1.setIsNoRndWalk(true);
					final L2Npc creature2 = addSpawn(CREATURE_OF_THE_DUSK2, 89524, -238131, -9632, 56, false, 0, false, player.getInstanceId());
					creature2.setIsNoRndWalk(true);
					ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
					{
						@Override
						public void run()
						{
							creature1.deleteMe();
							creature2.deleteMe();
							st.unset("ex");
							isBusy = false;
						}
					}, 60000);
				}
				break;
			}
			case "30832-02.html":
			{
				if (st.isCond(7))
				{
					st.setCond(8, true);
					htmltext = event;
				}
				break;
			}
			case "30832-03.html":
			{
				if (st.isCond(8))
				{
					htmltext = event;
				}
				break;
			}
		}
		return htmltext;
	}

Replace Anonymous With Lambda quests.Q10292_SevenSignsGirlOfDoubt.Q10292_SevenSignsGirlOfDoubt.onAdvEvent.scheduleGeneral.new Runnable with () -> {creature1.deleteMe(); in method public onAdvEvent(event String, npc L2Npc, player L2PcInstance) : String from class quests.Q10292_SevenSignsGirlOfDoubt.Q10292_SevenSignsGirlOfDoubt


	@Override
	public synchronized String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
	{
		if (_hall.isInSiege())
		{
			final int npcId = npc.getId();
			for (int keys : _data.keySet())
			{
				if (_data.get(keys).npc == npcId)
				{
					removeParticipant(keys, true);
				}
			}

			synchronized (this)
			{
				// TODO: Zoey76: previous bad implementation.
				// Converting map.keySet() to List and map.values() to List doesn't ensure that
				// first element in the key's List correspond to the first element in the values' List
				// That's the reason that values aren't copied to a List, instead using _data.get(clanIds.get(0))
				final List<Integer> clanIds = new ArrayList<>(_data.keySet());
				if (_firstPhase)
				{
					// Siege ends if just 1 flag is alive
					// Hall was free before battle or owner didn't set the ally npc
					if (((clanIds.size() == 1) && (_hall.getOwnerId() <= 0)) || (_data.get(clanIds.get(0)).npc == 0))
					{
						_missionAccomplished = true;
						// _winner = ClanTable.getInstance().getClan(_data.keySet()[0]);
						// removeParticipant(_data.keySet()[0], false);
						cancelSiegeTask();
						endSiege();
					}
					else if ((_data.size() == 2) && (_hall.getOwnerId() > 0)) // Hall has defender (owner)
					{
						cancelSiegeTask(); // No time limit now
						_firstPhase = false;
						_hall.getSiegeZone().setIsActive(false);
						for (int doorId : INNER_DOORS_TO_OPEN)
						{
							_hall.openCloseDoor(doorId, true);
						}

						for (ClanData data : _data.values())
						{
							doUnSpawns(data);
						}

						ThreadPoolManager.getInstance().scheduleGeneral(() ->
						{
							for (int doorId : INNER_DOORS_TO_OPEN)
							{
								_hall.openCloseDoor(doorId, false);
							}

							for (Entry<Integer, ClanData> e : _data.entrySet())
							{
								doSpawns(e.getKey(), e.getValue());
							}

							_hall.getSiegeZone().setIsActive(true);
						}, 300000);
					}
				}
				else
				{
					_missionAccomplished = true;
					_winner = ClanTable.getInstance().getClan(clanIds.get(0));
					removeParticipant(clanIds.get(0), false);
					endSiege();
				}
			}
		}
		return null;
	}

	@Override
	public synchronized String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
	{
		if (_hall.isInSiege())
		{
			final int npcId = npc.getNpcId();
			for (int keys : _data.keySet())
			{
				if (_data.get(keys).npc == npcId)
				{
					removeParticipant(keys, true);
				}
			}

			synchronized (this)
			{
				// TODO: Zoey76: previous bad implementation.
				// Converting map.keySet() to List and map.values() to List doesn't ensure that
				// first element in the key's List correspond to the first element in the values' List
				// That's the reason that values aren't copied to a List, instead using _data.get(clanIds.get(0))
				final List<Integer> clanIds = new ArrayList<>(_data.keySet());
				if (_firstPhase)
				{
					// Siege ends if just 1 flag is alive
					// Hall was free before battle or owner didn't set the ally npc
					if (((clanIds.size() == 1) && (_hall.getOwnerId() <= 0)) || (_data.get(clanIds.get(0)).npc == 0))
					{
						_missionAccomplished = true;
						// _winner = ClanTable.getInstance().getClan(_data.keySet()[0]);
						// removeParticipant(_data.keySet()[0], false);
						cancelSiegeTask();
						endSiege();
					}
					else if ((_data.size() == 2) && (_hall.getOwnerId() > 0)) // Hall has defender (owner)
					{
						cancelSiegeTask(); // No time limit now
						_firstPhase = false;
						_hall.getSiegeZone().setIsActive(false);
						for (int doorId : INNER_DOORS_TO_OPEN)
						{
							_hall.openCloseDoor(doorId, true);
						}

						for (ClanData data : _data.values())
						{
							doUnSpawns(data);
						}

						ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
						{
							@Override
							public void run()
							{
								for (int doorId : INNER_DOORS_TO_OPEN)
								{
									_hall.openCloseDoor(doorId, false);
								}

								for (Entry<Integer, ClanData> e : _data.entrySet())
								{
									doSpawns(e.getKey(), e.getValue());
								}

								_hall.getSiegeZone().setIsActive(true);
							}
						}, 300000);
					}
				}
				else
				{
					_missionAccomplished = true;
					_winner = ClanTable.getInstance().getClan(clanIds.get(0));
					removeParticipant(clanIds.get(0), false);
					endSiege();
				}
			}
		}
		return null;
	}

Replace Anonymous With Lambda conquerablehalls.flagwar.FlagWar.onKill.scheduleGeneral.new Runnable with () -> {for(int doorId: INNER_DOORS_TO_OPEN){_hall.openCloseDoor(doorId,false); in method public onKill(npc L2Npc, killer L2PcInstance, isSummon boolean) : String from class conquerablehalls.flagwar.FlagWar


		public void scheduleRespawn(long waitTime)
		{
			ThreadPoolManager.getInstance().scheduleGeneral(() ->
			{
				// if the AI is inactive, do not spawn the NPC
				if (isSeedActive(_seedId))
				{
					// get a random NPC that should spawn at this location
					Integer spawnId = _spawnId; // the map uses "Integer", not "int"
					_spawnedNpcs.put(addSpawn(_npcIds[getRandom(_npcIds.length)], _loc, false, 0), spawnId);
				}
			}, waitTime);
		}

		public void scheduleRespawn(long waitTime)
		{
			ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
			{
				@Override
				public void run()
				{
					// if the AI is inactive, do not spawn the NPC
					if (isSeedActive(_seedId))
					{
						// get a random NPC that should spawn at this location
						Integer spawnId = _spawnId; // the map uses "Integer", not "int"
						_spawnedNpcs.put(addSpawn(_npcIds[getRandom(_npcIds.length)], _loc, false, 0), spawnId);
					}
				}
			}, waitTime);
		}

Replace Anonymous With Lambda ai.group_template.EnergySeeds.ESSpawn.scheduleRespawn.scheduleGeneral.new Runnable with () -> {if(isSeedActive(_seedId)){Integer spawnId=_spawnId; in method public scheduleRespawn(waitTime long) : void from class gracia.AI.EnergySeeds.ESSpawn


	@Override
	public synchronized String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
	{
		if (_hall.isInSiege())
		{
			final int npcId = npc.getId();
			for (int keys : _data.keySet())
			{
				if (_data.get(keys).npc == npcId)
				{
					removeParticipant(keys, true);
				}
			}

			synchronized (this)
			{
				// TODO: Zoey76: previous bad implementation.
				// Converting map.keySet() to List and map.values() to List doesn't ensure that
				// first element in the key's List correspond to the first element in the values' List
				// That's the reason that values aren't copied to a List, instead using _data.get(clanIds.get(0))
				final List<Integer> clanIds = new ArrayList<>(_data.keySet());
				if (_firstPhase)
				{
					// Siege ends if just 1 flag is alive
					// Hall was free before battle or owner didn't set the ally npc
					if (((clanIds.size() == 1) && (_hall.getOwnerId() <= 0)) || (_data.get(clanIds.get(0)).npc == 0))
					{
						_missionAccomplished = true;
						// _winner = ClanTable.getInstance().getClan(_data.keySet()[0]);
						// removeParticipant(_data.keySet()[0], false);
						cancelSiegeTask();
						endSiege();
					}
					else if ((_data.size() == 2) && (_hall.getOwnerId() > 0)) // Hall has defender (owner)
					{
						cancelSiegeTask(); // No time limit now
						_firstPhase = false;
						_hall.getSiegeZone().setIsActive(false);
						for (int doorId : INNER_DOORS_TO_OPEN)
						{
							_hall.openCloseDoor(doorId, true);
						}

						for (ClanData data : _data.values())
						{
							doUnSpawns(data);
						}

						ThreadPoolManager.getInstance().scheduleGeneral(new Runnable()
						{
							@Override
							public void run()
							{
								for (int doorId : INNER_DOORS_TO_OPEN)
								{
									_hall.openCloseDoor(doorId, false);
								}

								for (Entry<Integer, ClanData> e : _data.entrySet())
								{
									doSpawns(e.getKey(), e.getValue());
								}

								_hall.getSiegeZone().setIsActive(true);
							}
						}, 300000);
					}
				}
				else
				{
					_missionAccomplished = true;
					_winner = ClanTable.getInstance().getClan(clanIds.get(0));
					removeParticipant(clanIds.get(0), false);
					endSiege();
				}
			}
		}
		return null;
	}


private void listCharacters(L2PcInstance activeChar, int page)
	{
		final L2PcInstance[] players = L2World.getInstance().getPlayersSortedBy(Comparator.comparingLong(L2PcInstance::getUptime));

		final NpcHtmlMessage html = new NpcHtmlMessage();
		html.setFile(activeChar.getHtmlPrefix(), "data/html/admin/charlist.htm");

		final PageResult result = HtmlUtil.createPage(players, page, 20, i ->
		{
			return "Page " + (i + 1) + "	";
		}, player ->
		{
			StringBuilder sb = new StringBuilder();
			sb.append("
");
			sb.append("" + player.getName() + "	");
			sb.append("" + ClassListData.getInstance().getClass(player.getClassId()).getClientCode() + "	" + player.getLevel() + "	");
			sb.append("
");
			return sb.toString();
		});

		if (result.getPages() > 0)
		{
			html.replace("%pages%", "

" + result.getPagerTemplate() + "

");
		}
		else
		{
			html.replace("%pages%", "");
		}

		html.replace("%players%", result.getBodyTemplate().toString());
		activeChar.sendPacket(html);
	}

private void listCharacters(L2PcInstance activeChar, int page)
	{
		final L2PcInstance[] players = L2World.getInstance().getPlayersSortedBy(Comparators.PLAYER_UPTIME_COMPARATOR);

		final NpcHtmlMessage html = new NpcHtmlMessage();
		html.setFile(activeChar.getHtmlPrefix(), "data/html/admin/charlist.htm");

		final PageResult result = HtmlUtil.createPage(players, page, 20, new IProcedure<Integer, String>()
		{
			@Override
			public String execute(Integer i)
			{
				return "Page " + (i + 1) + "	";
			}
		}, new IProcedure<L2PcInstance, String>()
		{
			@Override
			public String execute(L2PcInstance player)
			{
				StringBuilder sb = new StringBuilder();
				sb.append("
");
				sb.append("" + player.getName() + "	");
				sb.append("" + ClassListData.getInstance().getClass(player.getClassId()).getClientCode() + "	" + player.getLevel() + "	");
				sb.append("
");
				return sb.toString();
			}
		});

		if (result.getPages() > 0)
		{
			html.replace("%pages%", "

" + result.getPagerTemplate() + "

");
		}
		else
		{
			html.replace("%pages%", "");
		}

		html.replace("%players%", result.getBodyTemplate().toString());
		activeChar.sendPacket(html);
	}

Replace Anonymous With Lambda handlers.admincommandhandlers.AdminEditChar.listCharacters.result.createPage.new IProcedure<L2PcInstance,String> with i -> {return "Page " + (i + 1) + "	"; in method private listCharacters(activeChar L2PcInstance, page int) : void from class handlers.admincommandhandlers.AdminEditChar


	private static void updateAttacker(int clanId, long count, boolean remove)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement;
			if (remove)
			{
				statement = con.prepareStatement("DELETE FROM rainbowsprings_attacker_list WHERE clanId = ?");
				statement.setInt(1, clanId);
			}
			else
			{
				statement = con.prepareStatement("INSERT INTO rainbowsprings_attacker_list VALUES (?,?)");
				statement.setInt(1, clanId);
				statement.setLong(2, count);
			}
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private static void updateAttacker(int clanId, long count, boolean remove)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			if (remove)
			{
				statement = con.prepareStatement("DELETE FROM rainbowsprings_attacker_list WHERE clanId = ?");
				statement.setInt(1, clanId);
			}
			else
			{
				statement = con.prepareStatement("INSERT INTO rainbowsprings_attacker_list VALUES (?,?)");
				statement.setInt(1, clanId);
				statement.setLong(2, count);
			}
			statement.execute();
			statement.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private updateAttacker(clanId int, count long, remove boolean) : void from class conquerablehalls.RainbowSpringsChateau.RainbowSpringsChateau


	private static void loadAttackers()
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement("SELECT * FROM rainbowsprings_attacker_list");
			ResultSet rset = statement.executeQuery();
			while (rset.next())
			{
				int clanId = rset.getInt("clan_id");
				long count = rset.getLong("decrees_count");
				_warDecreesCount.put(clanId, count);
			}
			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private static void loadAttackers()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT * FROM rainbowsprings_attacker_list");
			ResultSet rset = statement.executeQuery();
			while (rset.next())
			{
				int clanId = rset.getInt("clan_id");
				long count = rset.getLong("decrees_count");
				_warDecreesCount.put(clanId, count);
			}
			rset.close();
			statement.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private loadAttackers() : void from class conquerablehalls.RainbowSpringsChateau.RainbowSpringsChateau


	@Override
	public final void loadAttackers()
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement(SQL_LOAD_ATTACKERS);
			statement.setInt(1, _hall.getId());
			ResultSet rset = statement.executeQuery();
			while(rset.next())
			{
				final int clanId = rset.getInt("clan_id");

				if(ClanTable.getInstance().getClan(clanId) == null)
				{
					_log.warning(qn+": Loaded an unexistent clan as attacker! Clan Id: "+clanId);
					continue;
				}

				ClanData data = new ClanData();
				data.flag = rset.getInt("flag");
				data.npc = rset.getInt("npc");

				_data.put(clanId, data);
				loadAttackerMembers(clanId);
			}
			rset.close();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".loadAttackers()->"+e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public final void loadAttackers()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SQL_LOAD_ATTACKERS);
			statement.setInt(1, _hall.getId());
			ResultSet rset = statement.executeQuery();
			while(rset.next())
			{
				final int clanId = rset.getInt("clan_id");

				if(ClanTable.getInstance().getClan(clanId) == null)
				{
					_log.warning(qn+": Loaded an unexistent clan as attacker! Clan Id: "+clanId);
					continue;
				}

				ClanData data = new ClanData();
				data.flag = rset.getInt("flag");
				data.npc = rset.getInt("npc");

				_data.put(clanId, data);
				loadAttackerMembers(clanId);
			}
			rset.close();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".loadAttackers()->"+e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method public loadAttackers() : void from class conquerablehalls.flagwar.FlagWar


	private final void loadAttackerMembers(int clanId)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			ArrayList<Integer> listInstance = _data.get(clanId).players;

			if(listInstance == null)
			{
				_log.warning(qn+": Tried to load unregistered clan: "+clanId+"[clan Id]");
				return;
			}

			PreparedStatement statement = con.prepareStatement(SQL_LOAD_MEMEBERS);
			statement.setInt(1, clanId);
			ResultSet rset = statement.executeQuery();
			while(rset.next())
			{
				listInstance.add(rset.getInt("object_id"));

			}
			rset.close();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".loadAttackerMembers()->"+e.getMessage());
			e.printStackTrace();
		}
	}

	private final void loadAttackerMembers(int clanId)
	{
		Connection con = null;
		try
		{
			ArrayList<Integer> listInstance = _data.get(clanId).players;

			if(listInstance == null)
			{
				_log.warning(qn+": Tried to load unregistered clan: "+clanId+"[clan Id]");
				return;
			}

			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SQL_LOAD_MEMEBERS);
			statement.setInt(1, clanId);
			ResultSet rset = statement.executeQuery();
			while(rset.next())
			{
				listInstance.add(rset.getInt("object_id"));

			}
			rset.close();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".loadAttackerMembers()->"+e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private loadAttackerMembers(clanId int) : void from class conquerablehalls.flagwar.FlagWar


	private final void saveClan(int clanId, int flag)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement(SQL_SAVE_CLAN);
			statement.setInt(1, _hall.getId());
			statement.setInt(2, flag);
			statement.setInt(3, 0);
			statement.setInt(4, clanId);
			statement.execute();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".saveClan()->"+e.getMessage());
			e.printStackTrace();
		}
	}

	private final void saveClan(int clanId, int flag)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SQL_SAVE_CLAN);
			statement.setInt(1, _hall.getId());
			statement.setInt(2, flag);
			statement.setInt(3, 0);
			statement.setInt(4, clanId);
			statement.execute();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".saveClan()->"+e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private saveClan(clanId int, flag int) : void from class conquerablehalls.flagwar.FlagWar


	private final void saveNpc(int npc, int clanId)
	{
		try (Connection con = L2DatabaseFactory.getInstance().getConnection())
		{
			PreparedStatement statement = con.prepareStatement(SQL_SAVE_NPC);
			statement.setInt(1, npc);
			statement.setInt(2, clanId);
			statement.execute();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".saveNpc()->"+e.getMessage());
			e.printStackTrace();
		}
	}

	private final void saveNpc(int npc, int clanId)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement(SQL_SAVE_NPC);
			statement.setInt(1, npc);
			statement.setInt(2, clanId);
			statement.execute();
			statement.close();
		}
		catch(Exception e)
		{
			_log.warning(qn+".saveNpc()->"+e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
	}

Try With Resources try(Connection con=L2DatabaseFactory.getInstance().getConnection()) in method private saveNpc(npc int, clanId int) : void from class conquerablehalls.flagwar.FlagWar