#help-development

1 messages · Page 2101 of 1

echo basalt
#

because I'm an idiot

#

so I suffer

little cradle
#

wtf did i do to my computer im on windows 10 XD

ivory sleet
#

lol, I mean groovy isnt all that bad

#

🥲

little cradle
#

oh 99% of my cpu is being used... that explain it

ivory sleet
#

oof

little cradle
#

lmfao i just closed half my tabs and it dropped to 29%

ivory sleet
#

x)

little cradle
#

kinda impressive tho bc besides for that there was nothing else that made it seems like i was using that much cpu

minor garnet
little cradle
#

doubt it i just updated a few days ago

minor garnet
#

🙄

little cradle
#

couldn't imagine they'd already be forcing me to update

crude loom
#

Any idea as to why am I getting index out of bounds here?

 Location[] locs = new Location[3];
 Chest[] chests = new Chest[3];

 for(int i=0;i<9;i+=3) {
    locs[i/3] = new Location(w, Integer.parseInt(split[i]), Integer.parseInt(split[i + 1]), Integer.parseInt(split[i + 2]));          
    chests[i/3] = (Chest) w.getBlockAt(locs[i]).getState();
}
ivory sleet
#

ugh its a bit intricate to see as you're doing quite many array accesses in one line

#

but one of them would be w.getBlockAt(locs[i])

crude loom
#

Oh I didn't notice the locs[i]😅

ivory sleet
#

ye

#

perhaps the accesses from split also yield IOOB

crude loom
#

Whats IOOB?

ivory sleet
#

IndexOutOfBounds

crude loom
#

Oh, no these should be fine if im correct

ivory sleet
#

aight

noble lantern
#

hey guys im back

little cradle
#

wb bro

noble lantern
#

and ready to give you all the most scuffed code solutions youve ever seen

little cradle
#

lmao

little cradle
flat olive
#

choose or die is such a scary movie on netflix

#

holy shit im watching it and I already got jump scared twice and almost broke my monitor

little cradle
#

lmfaoi

torn vale
#
package de.leleedits.ffahardcore.listener;

import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;

public class PlayerDamageListener implements Listener {

    @EventHandler
    public void onPlayerDamage(EntityDamageEvent e) {
        Player p = (Player) e.getEntity();
        Location coord1 = new Location(p.getWorld(), -13, 190, -13);
        Location coord2 = new Location(p.getWorld(), 13, 150, 13);
        if ((p.getLocation().getBlockX() > coord1.getBlockX()) && (p.getLocation().getBlockX() < coord2.getBlockX())) {
            if ((p.getLocation().getBlockY() > coord1.getBlockY()) && (p.getLocation().getBlockY() < coord2.getBlockY())) {
                if ((p.getLocation().getBlockZ() > coord1.getBlockZ()) && (p.getLocation().getBlockZ() < coord2.getBlockZ())) {
                    e.setCancelled(true);
                }
            }
        }
        if (e.getCause().equals(EntityDamageEvent.DamageCause.FALL)) {
            e.setCancelled(true);
        }
    }
}
#

why can I still pvp inside of the area where I cancel the event?

worldly ingot
#
  1. Please, make some variables and constants
  2. EntityDamageEvent#getEntity() gets the entity that was damaged, not the one inflicting the damage. You want EntityDamageByEntityEvent and #getDamager()
quaint mantle
#

choco so nice

torn vale
# worldly ingot 1. Please, make some variables and constants 2. EntityDamageEvent#getEntity() ge...
    @EventHandler
    public void onPlayerDamage(EntityDamageByEntityEvent e) {
        Player p = (Player) e.getDamager();
        Location coord1 = new Location(p.getWorld(), -13, 190, -13);
        Location coord2 = new Location(p.getWorld(), 13, 150, 13);
        if ((p.getLocation().getBlockX() > coord1.getBlockX()) && (p.getLocation().getBlockX() < coord2.getBlockX())) {
            if ((p.getLocation().getBlockY() > coord1.getBlockY()) && (p.getLocation().getBlockY() < coord2.getBlockY())) {
                if ((p.getLocation().getBlockZ() > coord1.getBlockZ()) && (p.getLocation().getBlockZ() < coord2.getBlockZ())) {
                    e.setCancelled(true);
                }
            }
        }
        if (e.getCause().equals(EntityDamageEvent.DamageCause.FALL)) {
            e.setCancelled(true);
        }
    }```
Like this? Idk what you mean with variables, I have enough lol
worldly ingot
#

Should work fine but you're going to get exceptions because getDamager() isn't always a Player. It might be a zombie or anything else that can inflict damage

#

Check first, cast after

#
if (!(e.getDamager() instanceof Player player)) {
    return;
}

// Continue using the player variable```
#

Or if you're not using J16/17

Entity entity = e.getDamager();
if (!(entity instanceof Player)) {
    return;
}

Player player = (Player) entity```
torn vale
#

okay, thank you

#

ill test it tomorrow, now no1 is online

worldly ingot
#

(the fall damage part is going to need to be in EntityDamageEvent though)

torn vale
#
        Location coord1 = new Location(p.getWorld(), -13, 190, -13);
        Location coord2 = new Location(p.getWorld(), 13, 150, 13);
        if ((p.getLocation().getBlockX() > coord1.getBlockX()) && (p.getLocation().getBlockX() < coord2.getBlockX())) {
            if ((p.getLocation().getBlockY() > coord1.getBlockY()) && (p.getLocation().getBlockY() < coord2.getBlockY())) {
                if ((p.getLocation().getBlockZ() > coord1.getBlockZ()) && (p.getLocation().getBlockZ() < coord2.getBlockZ())) {
                    e.setCancelled(true);
                }
            }
        }```
this part should work? Because like 1 hour ago it didnt worked
#

its like a spawn protection

sharp flare
#

Can re use some stuffs in there by storing them in a variable

worldly ingot
#

Other than that, you can clean things up a lot.

    private static final int MIN_X = -13, MIN_Y = 150, MIN_Z = -13;
    private static final int MAX_X = 13, MAX_Y = 190, MAX_Z = 13;

    @EventHandler
    public void onPlayerDamage(EntityDamageByEntityEvent event) {
        if (!(event.getDamager() instanceof Player player) {
            return;
        }

        Location location = player.getLocation();
        double x = location.getX(), y = location.getY(), z = location.getZ();

        if (x < MIN_X || x > MAX_X || y < MIN_Z || y > MAX_Y || z < MIN_Z || z > MAX_Z) {
            return;
        }

        e.setCancelled(true);
    }```
#

See how much easier that is to read? PES_Blush

#

Can do one better and create a BoundingBox which has a method to check if a location is within it

torn vale
#

ill test it tomorrow :)

sharp flare
#

Don't just test it, learn from it

#

You get a valuable pattern there

wet spindle
#

hellooo how can i spawn a random Entity, doenst have to be living or non living, both i guess. thanks

#

o rhow cna i get a list of all the entities available in the spigot api

#

anyone?

noble lantern
#

choco how are you so nice

worldly ingot
#

Canadian

worldly ingot
#

Can get spawnable ones with EntityType spawnableEntities = Arrays.stream(EntityType.values()).filter(EntityType::isSpawnable).toArray(EntityType[]::new)

noble lantern
wet spindle
#

tysm

wet spindle
#

in other words, how can i get a random itemstack

worldly ingot
#

Material

#

Same sort of statement, only you'll want to filter isItem instead

wet spindle
#

thank you

vast plinth
#

my plugin cannot connect with mariaDB

delicate lynx
#

then you did something wrong

vocal tundra
#

Is there a built in way to check if a player punches a Falling sand block? (Before I have to implement my own) and no entity attack event doesn't work

noble lantern
#

entity smack event

#

jk

#

i dont think there is

vocal tundra
#

Lmaoo

#

I'll just make my own patch then

noble lantern
#

PlayerSmackSandEvent

quaint mantle
#

you can raytrace

#

probably

#

check if theres a sand infront

vocal tundra
#

Yeah but that's naughty for people with high ping

noble lantern
#

kick players with 400 ping +

vocal tundra
#

I care too much about my high ping players

sharp osprey
#

Hello, I have a small problem, I need to check if the player is standing in a lily pad. I have tried multiple ways of doing it but nothing works, can someone help me?
And please ping me if you've got an answer

sharp flare
fleet pier
#

Is it possible to send custom achievements?

vocal tundra
#

yes

fleet pier
#

or is it limited to higher versions

vocal tundra
#

Ah, not in 1.8 sorry bro, only 1.12+ with advancements

short raptor
#

Hi guys, what's the easiest way for me to implement vanilla selectors into my plugin? Like full minecraft logic including [type= or distance=]?

glossy venture
#

how do i get the server type and version?

#

like Spigot 1.18.2-rev69420 or something

#

or Paper MCVER+VERSION

radiant cipher
#

how to break out of this Bukkit.getScheduler().scheduleSyncRepeatingTask(test.getInstance(), () -> { Bukkit.broadcastMessage("This message is shown immediately and then repeated every second"); }, 10L, 60L);

#

lets say after 5 times running

chrome beacon
glossy venture
#

for what will i have to use regex

chrome beacon
undone axleBOT
chrome beacon
glossy venture
#

nah i want the whole string

#

like Paper MCVER+PAPERVERSION or something

chrome beacon
#

Alright then just use the method I sent without using Regex on it

glossy venture
#

aight thanks

radiant cipher
sharp flare
chrome beacon
#

?paste

undone axleBOT
sharp flare
#

task -> {

Condition
task.cancel

}

radiant cipher
#
                        Bukkit.broadcastMessage("This message is shown immediately and then repeated every second");
                        task.cancel();
                        
                    }, 0L, 60L);``` how to make task.cancel work
chrome beacon
#

As I said use a BukkitRunnable

#

?scheduling Read the wiki

undone axleBOT
sharp flare
#

Use run task timer

radiant cipher
#

task.cancel(); still not working

#
                        public void run() {
                            Bukkit.broadcastMessage("Mooooo!");
                            task.cancel();
                        }
                    }.runTaskTimer(test.getInstance(), 20L * 10L /*<-- the initial delay */, 20L * 5L /*<-- the interval */);```
chrome beacon
#

It's just cancel()

#

skip the task.

radiant cipher
#

ok so

#
                        public void run() {
                            Bukkit.broadcastMessage("Mooooo!");
                            cancel();
                        }
                    }.runTaskTimer(test.getInstance(), 20L * 10L);``` this will cancel after 1 time? I'm confused
chrome beacon
#

Yes it will cancel after first time

radiant cipher
#

ok so to break it after x times

#

i could do something like this right?

#

                    new BukkitRunnable() {
                        public void run() {
                            Bukkit.broadcastMessage("Mooooo!");
                            counter = counter + 1;
                            if (counter == 10) {
                                cancel();
                            }
                        }
                    }.runTaskTimer(test.getInstance(), 20L * 10L);```
chrome beacon
#

You should put the counter inside the BukkitRunnable

#

You can also use counter++ and >= instead of ==

radiant cipher
#

                    new BukkitRunnable(counter = counter + 1) {
                        public void run() {
                            Bukkit.broadcastMessage("Mooooo!");
                            if (counter == 10) {
                                cancel();
                            }
                        }
                    }.runTaskTimer(test.getInstance(), 20L * 10L);```?
chrome beacon
#

The counter variable should be defined inside your BukkitRunnable class but outside the run method

radiant cipher
#

very confused again

#

can I just get an example that works

chrome beacon
#

?scheduling 🙂

undone axleBOT
chrome beacon
#

It has an example that works

#

If you read it

#

Anyways I have a feeling you're not very experienced with Java. And I highly recommend to keep practicing it so you know what you can do and what you cannot do

radiant cipher
#

very cool

#

can someone give me an example that works please?

sharp flare
#

And their inside a anonymous

#

Much better if u have a seperate class extends BukkitRunnable if its a complex task

#

Can reuse the object too

vocal tundra
#

true

vocal tundra
#

is there a 1 liner to play a block breaking sound that correlates with the block id

versed mango
#
    public Mudwalker (String namespace) {
        super(new NamespacedKey(MudwingCustomEnchant.getPlugin(), key:"namespace"));
    }
``` does anyone know y this doesn't work? it is telling me that "key has privet accesse in org.bukkit.enchantments.Enchant how do i fix that?
eternal night
#

Please don’t randomly access the enum lol

vocal tundra
#

We lose 1.18

eternal night
#

What do you mean loose 1.8

vocal tundra
#

Do you know of a 1.12 technique

eternal night
#

Does that method not exist in 1.12

#

Right that is pre flattening

#

Well rip people living in the past

versed mango
#

what is the eventhandler i am targeting for when a player walks on a block?

vocal tundra
#

1.12 is the future

versed mango
#

thx

vocal tundra
#

every other version requires so much ram to even have the server exist with 0 people on 😦

versed mango
#

i am making a enchant that works like soulspeed for a different block and i want to track when they are ontop of it to get them a speed boost

vocal tundra
#

it was over 1gb for no players when I tested

versed mango
#

ok

#

i would need to use @EventHandler public void onPlayerMoveEvent or would it be just PlayerMoveEvent?

vocal tundra
#

it is when a 2gb vps can't support it

#

how so

versed mango
#

ik how some work i am still learning how this works

vocal tundra
#

My servers all work insanely smooth with 1gb 1.12 and under

versed mango
#

ah

#

thx

vocal tundra
#

Minigames tho

#

You underestimate the power of 1.12

#

I do I'm a hater

glossy venture
#

bro 2b2t test was running 1.18 at 20 tps @ ~120 people online vs like 14 tps on 1.12

vocal tundra
#

I'm not complaining 😦

eternal night
#

Some haters would say that a certain forks of spigot also just has a lot of optimisation, even now including Timothy

#

Tunity LOL

versed mango
vocal tundra
#

what version of java is that

eternal night
#

The "java with named parameter" fork obviously

glossy venture
#

is there a way to carry data with an event through the handlers?

#

i want to check if the event was previously handled

#

by one of my other handlers

#

if its not possible ill need to make a custom pipeline to broadcast the events and then carry data with them

versed mango
vocal tundra
#

I rage quit plugin development, I had the solution to my problem like an hour ago but I had block sounds off on my client

glossy venture
#

lmfao

eternal night
#

no

#

the event is a plain java class

#

dunno how you want to attach data to it directly

#

you can obviously just throw it at a map

#

or abuse the fact that event handler logic is guaranteed to be in order, e.g. just have a single field you set/read from

crimson terrace
#

is it possible to set the ai of a snowman to another entity?

vocal tundra
#

yes

thin venture
#

How would I fill all slots of a gui with a block ( dark gray stained glass )

crimson terrace
#

for loop

thin venture
#

this doesnt really help me

#

i am new to plugin dev

crimson terrace
#

just make a for loop with i=0 and then fill the slot with the index i with the item you want

#

of course you have to limit the for loop to the amount of slots in the inventory

sharp osprey
small current
#

guys im trying to edit someone's code wtf is this

#

idk what is EbeanServer and there is no EbeanServer in the code

noble lantern
small current
#

i know where it is

#

i know what it is

noble lantern
#

and it doesnt show any errors in the ide?

small current
#

and its an object in the code

#

its a lombok @Getter

noble lantern
#

does the implementing class already have a getDatabase method

#

the 2 could be conflicting (lombok + implementing class)

small current
#

if i make the getter manual

#

what is getDatabase

noble lantern
#

Looks like Database is a invalid object too

river oracle
#

It's the wrong return type

noble lantern
#

check the import of Database as well as the returning value

small current
#

🧠

#

javaplugin class

#

it clashes

noble lantern
#

yep figured something along the lines of that was happening

#

kind of odd that plugin compiled for the OG author

#

maybe hes built different

small current
#

yes

noble lantern
small current
#

and doesn't know what is isString

#

and is a null check

noble lantern
#

well I would assume it would check the API of the ConfigurationSection, maybe not

#

not sure if theres a setting for that either

#

big brain

#

made fromString argument nullable

echo basalt
#

I believe the common implementation is MemorySection

#

not sure

#

So it can't magically guess each implementation

glossy venture
#
public void registerNextPermutation(
        IngredientNodeLike node,
        int depth,
        List<Ingredient> ingredients,
        List<Integer> usedIndexes,
        Recipe recipe
) {
    if (depth >= ingredients.size() - 1) {
        ((RecipeMatchTree.Node)node).setRecipe(recipe);
        return;
    }

    int il = ingredients.size();
    int ui = 0;
    for (int i = 0; i < il; i++) {
        if (usedIndexes.get(ui) == i) {
            ui++;
            continue;
        }

        Ingredient in = ingredients.get(i);
        RecipeMatchTree.Node n = node.getIngredientChild(in);

        usedIndexes.add(i);
        registerNextPermutation(
                n,
                depth + 1,
                ingredients,
                usedIndexes,
                recipe
        );
        usedIndexes.remove(usedIndexes.size() - 1);
    }

}

@Override
@SuppressWarnings("unchecked")
public void register(Recipe recipe) {
    registerNextPermutation(
            tree,
            0,
            recipe.ingredients(),
            new ArrayList<>(),
            recipe
    );
}
``` bruh
#

anyone know a better way of doing this lmao

noble lantern
# echo basalt

yes but in a sence the MemorySection class does a null check

echo basalt
#

the IDE doesn't know if what you're calling will return whatever you ask for

#

isString could do some heavy operation

#

and null values could break it

#

sure it could be slightly smarter and look at all implementations of it

#

but then someone could make a new implementation, inject shit via reflections and break everything

noble lantern
#

Ngl i can see what you mean since it is calling get() which returns and object and instead getString returns a string directly i think

echo basalt
#

Not that

#

if you call MemorySection#isString your IDE will recognize it

#

if you call ConfigurationSection#isString, your IDE won't due to polymorphism

#

best way to make your IDE stop screaming is annotating isString with @NotNull

#

but neither of us are spigot maintainers afaik so that's annoying

noble lantern
#

What if i use MemorySection object directly instead of the ConfigurationSection interface?

#

Or would it still cause the same thing

echo basalt
#

also calling get... again could produce a different result

#

best way is just

Object value = get("path");

if(!(value instanceof String text))
  return;

text...
#

your ide doesn't yell at you unless the config is nuill

#

and it does the job

noble lantern
#

not a bad idea, I think in a later version ill implement that

#

for now i just added @smoky tinsel to my method argument and null check it in there

#

slightly more messy but I need to refactor this whole project i think anyway

#

I would really love to use Json and i could shorten this by ten-folds

#

But then im gonna force people to use json and I feel like it may make my plugin less popular

echo basalt
#

why do you have both @Getter and public 🤦

#

also getStringList returns an empty list if the path is invalid so you can avoid some console logs

noble lantern
#

probably slight miss by me when typing and tab completions like with this

echo basalt
#

was looking at the wordconfig

#

you know you can annotate the entire class and all fields will have getters right

noble lantern
#

Like @Getter at the top of the class file?

echo basalt
#
@Getter
public class ...
noble lantern
#

oh damn

#

-40 lines of code right there

echo basalt
#

also @AllArgsConstructor makes a constructor with all args

#

@RequiredArgsConstructor makes a constructor with args that do not have a pre-defined value

eternal night
#

@Data is even cooler here no?

echo basalt
#

@Data sometimes causes issues

#

I remember having issues for having a data class within another data class

eternal night
#

Lombok is the issue xd

noble lantern
echo basalt
#

Changing it to
@Getter
@Setter
@EqualsAndHashCode

fixed it for me

noble lantern
#

thing is

#

would i be able to select only certain variable to be part of the AllArgsConstructor?

echo basalt
#

no

eternal night
#

„AllArgs“

echo basalt
#

there's also NoArgsConstructor which you can stack with others

noble lantern
#

I have some things that arent even variables as well, so i dont thing that annotation would work very well for me

echo basalt
#

you can shorten this to 2 lines

noble lantern
#

ohh yes i could for that class ty for pointing that out

echo basalt
#
@Getter
@AllArgsConstructor
private static class LoreValue {
  private final List<String> lore;
  private final ItemQualityField quality;
}
#

that's all

#

if you're storing values on hashsets or as keys of a hashmap

#

annotate with @EqualsAndHashCode

noble lantern
#

Nah LoreValue is just a list of Strings for the Lore, and item quality stores +50 in a sense as a Operation + Integer

fading lake
#

ew lombok

echo basalt
#

¯_(ツ)_/¯

#

man really likes spamming alt+insert

noble lantern
#

i prefer it just to keep my code base relatively short and not bloat it with getters and setters

small current
#

on top of the class

lavish hemlock
#

Have you considered reading the rest of the convo

noble lantern
#

where tf did my Statistic refresh button go

summer scroll
#

How can I make a cooldown item but only decrease the cooldown time If player is holding the item?

noble lantern
#

Youll need a runnable for that more than likely and check the players main/offhand during the runnable

summer scroll
#

What to store?

noble lantern
#

UUID of players that are in that specific "need to hold item" cooldown

summer scroll
#

Is it okay to store the time in pdc?

noble lantern
#

Your API you showed me the other day should be able to handle to rest

#

should be i dont really see and issue with it

noble lantern
summer scroll
#

The thing is with using System#currentTimeMillis the time will still keep running even If player isn't holding the item right?

noble lantern
#

Yep, youll need to store a milli value of how long player was holding the item for

glossy venture
#

since when is this possible?

#

the <boolean>

noble lantern
#

what the fuck

#

i would assume its some type of revamped casting?

glossy venture
#

no i mean since when can you use boolean

summer scroll
glossy venture
#

but i used a primitive

#

in a generic type

#

tf

noble lantern
#

if player isnt holding that item simply dont increase the time

lavish hemlock
#

loreConfig.get<String>("shit")

glossy venture
#

yeah

#

but since when can you specify primitives there

#

its generics

lavish hemlock
#

Like it continues to make no sense that explicit type args are before the method name

#

That's a good question

#

Consult the JLS to see what it actually means, maybe?

noble lantern
lavish hemlock
#

Okay

summer scroll
noble lantern
summer scroll
frigid rock
#

how should i make a deserializeString() method that gets a String and turns it into milliseconds? the string should contain like "1m 29s" or "2h 30m"

#

does anyone know if there is like a premade java or bukkit method for that?

noble lantern
eternal night
#

Pretty certain there isn’t an inbuilt method that for that format

#

Jods time had a period parser

noble lantern
#

^ i always just did it myself

eternal night
#

Java now has iso format Parsing on duration (Java 8)

#

So you might be able to convert your string to that format

frigid rock
#

can u turn duration into milliseconds?

eternal night
#

Yes

frigid rock
#

i dont really know how to get the string and turn it to duration

#

because i tried but didnt actually understand much

eternal night
summer scroll
frigid rock
#

thank you so much

noble lantern
#

like itemsInCooldown Map

#

<String, Long>

#

String = config name of item

#

unless your item is hard coded in

summer scroll
noble lantern
#

So then store the cooldown inside PDC

#

and while player is holding an item with that PDC tag do something

summer scroll
#

yeah i'm trying to figure out that something

noble lantern
#

if (hasPdc) {
reduceCooldownPdc(item);
}

#

inside a runnable

#

then after reducing check if value <=0

#

if true remove that pdc tag

summer scroll
#

so to check if player is on cooldown don't use the System#currentTimeMillis?

#

reduce the time manually

noble lantern
#

No for that type of system youll have to manually do it

#

since you only want it while the players holding the item

summer scroll
#

ahh okay

noble lantern
#

only thing i dont know

#

is what 1 tick is to millis

#

youll have to figure that part out

#

i think its 50

#

yeah

summer scroll
#

i'm gonna use integer i guess

noble lantern
#

50 * 20 = 1000

#

You could but

#

If the player keeps switching items

#

theyre cooldown may not cooldown properly

#

so youll have to check very often

#

like 5-10 ticks in time

summer scroll
#

hmm, okay

#

so if i use integer, that means i need to reduce every 20 ticks right

noble lantern
#

yeah since i assume since your using integer it will be in seconds

summer scroll
#

and doing that can cause issue if player switches item very often?

noble lantern
#

yeah say theyre constantly switching every second and they held it for most of the second, it could lead to cooldown being longer than expected

#

i would say do one tick check BUUUUUT performance might hinder

#

5 ticks is probably the magic spot

#

after all you are only checking a PDC tag and decrementing a long value

summer scroll
#

my way right now is start a task as soon as player hold the item

#

and stop the task if player is no longer hold the item

#

is that worse than having 1 runnable and loop through all players and check the item that they're currently hold?

noble lantern
#

should be fine

#

way your doing it rather scuffed

#

as youd constantly re-initing runnables

summer scroll
#

okay, i'll do that then

noble lantern
#

if you are concerned for performance

#

./timings on and /timings paste

#

and you can check its performance there

#

but IMO shouldnt really be an issue

summer scroll
#

i mean having 1 runnable than a runnable for every player is better i guess

noble lantern
#

indeed it is

#

Probably best to have a tick loop if 5 rather than 1 though, im sure 1 would be fine but if this is a public plugin it could cause issues

#

you could make it a config option too

#

check-item-cooldown-in-ticks: 5

And larger servers can make the delay higher if they do run into issues with it, but they honestly shouldnt

summer scroll
#

of course it will change how i decrease the cooldown right?

noble lantern
#

Yep!

summer scroll
#

let's say if i want to put the cooldown in seconds

#

600 seconds

#

how can i decrease it if the task is running every 5 tick?

noble lantern
#

millis are btter for cooldowns like that

#

600 * 1000

summer scroll
#

I can convert it I guess, but for just readability I'll put the initial values to seconds

noble lantern
#

config cooldown is in seconds

#

but ill convert to milli on the actual code

summer scroll
sand vector
#

Is this as far as you can go for a blank item?

summer scroll
sand vector
#

Is that with with ItemFlag

summer scroll
#

yup

sand vector
#

ok cheers

noble lantern
#

so 5 * 50

sacred mountain
#
double angle = Math.random() * 360;
double radius = Math.random() * config.getSpawnRadius();
Location location = player.getLocation().add(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
#

this should get a random location in a radius around the player right

sacred mountain
#

hey how would i pick a random one from here and use it's chance? i'm spawning 5 mobs in a radius and i want them to be picked with chances

#

should i not use an enum

crisp steeple
#

EntityEnum.values()[<random number>]

sacred mountain
#

yeah but how would i pick with teh chance too

#

just use the random function

#

i guess

crisp steeple
#

chance is the chance it has to spawn after it’s picked?

quiet ice
#

I'd just create an array of the length of all chances combined and add the values with the amount of their chance

#

I.e. something like

int len = 0;
final EnityEnum values = EntityEnum.values();
for (EntityEnum val : values) {
    len += val.getChance();
}
EntityEnum[] weightedValues = new EntityEnum[len];
int x = 0;
for (int i = 0; i < values.length; i++) {
    EntityEnum val = values[i];
    for (int j = 0; j < val.getChance(); j++) {weightedValues[x++] = val;} /* or just use arrays#fill */
}
noble lantern
#

seems weird to hardcode that

noble lantern
#

you need to use Random class or ThreadLocalRandom and generate a random number 0 - 100 for each mob

quiet ice
#

It would be random

#

Provided you access a random element of weightedValues my approach is as random as I assume is wanted

summer scroll
#

will giving potion effect override the current potion?

#

even when the new effect is worse?

glossy venture
# sacred mountain yeah but how would i pick with teh chance too

i always just do something like

static final int averageWeight = 35; // or something
static final List<EntityEnum> weighted;

static {
  // preallocate a rough estimation of how many values you might need
  weighted = new ArrayList<>(averageWeight * EntityEnum.values().length);
  // initialize weighted values
  for (EntityEnum e : EntityEnum.values())
    // if we say x is the chance,
    // we will add x elements of the instance to the list
    // as that makes it x times more likely to
    // occur than a single element
    for (int i = 0; i < e.getChance(); i++)
      weighted.add(e);
}

public static EntityEnum getRandomEntityType(Random r) {
  return weighted.get(r.nextInt(weighted.size()));
}
#

you could put that in your EntityEnum class

quiet ice
#

Yeah, basically my approach

glossy venture
#

oh yea

#

optimized

sacred mountain
sacred mountain
glossy venture
#

yeah

#

the averageWeight is just to estimate how much memory should be allocated

#

completely unneccesary optimization

#

but i like it

sacred mountain
#

oh ok damn

#

how lol

#

i dont really understand that weighted bit

#

so it will add that item to a list, chance times and make the program more likely to choose it?

quiet ice
#

Yes, which is why it is best to keep the chances rather low

#

I.e. once you have a combined chance of like 8 000 000, you'll have a really large array that is kinda pointless if all chances are a multiple of let's say 4 000

#

A) What sort of GUI
B) What the player clicked or which player clicked?
C) Sure that you cannot use a library for that - there is a high risk involved in GUIs
D) There is rarely a univerally best method

tender shard
#

I use PDC stuff for that

quiet ice
#

You could also use indices

#

(Assuming you want an inventory GUI and the player cannot manipulate the inventory)

midnight shore
#

Hi! I'm stuck here. I have the game profile with the custom texture from the head value and i want to set it to block data (Skull). I've seen the methods of that class and there aren't any. My guess is that it is a private field like SkullMeta (see second image).
Could anyone help me?

quiet ice
#

?jd

quiet ice
#

Oh you are using NMS. Bad boy!

midnight shore
#

i'm not using SkullMeta

quiet ice
#

Oh that other thing

midnight shore
#

yeah

quiet ice
#

You'd need to yeet NMS however

midnight shore
#

yeah but thats a 1.18 thing

opal juniper
#

yes

midnight shore
#

i don't have it

opal juniper
#

what version are you using

midnight shore
#

i'm on 1.17

opal juniper
#

why

#

there is no real reason to use 1.17

quiet ice
#

"performance"

opal juniper
#

lol

#

i doubt its that different

midnight shore
#

Actually thats not my concern

opal juniper
#

enlighten me

midnight shore
#

my question was if the field of Skull for the profile is named profile or what?

eternal night
#

probably not during runtime

quiet ice
#

?stash

undone axleBOT
eternal night
#

oh

#

you are just on craftbukkit

midnight shore
eternal night
#

source code management for spigot

#

e.g. there is your impl for the Skull interface

midnight shore
#

so yes

midnight shore
#

is this website new?

#

never seen this before

eternal night
#

no

#

it is ages an eternity old

quiet ice
#

Probably been there ever since the DMCA happened

opal juniper
eternal night
#

there xD

#

fixed it

summer scroll
#

Umm, I'm trying to put a pdc into item but when I check it using PersistentDataContainer#has it says that it doesn't have even tho I already set it.

#

Basically the isShard method is returning false

midnight shore
#

w class org.bukkit.craftbukkit.v1_17_R1.block.impl.CraftSkullPlayer cannot be cast to class org.bukkit.block.Skull (org.bukkit.craftbukkit.v1_17_R1.block.impl.CraftSkullPlayer and org.bukkit.block.Skull are in unnamed module of loader 'app') uhm

eternal night
#

skulls are block state

#

not block data

#

or at least the player profile etc is stored in the block state

midnight shore
#

like this?

summer scroll
#

Does one NamespacedKey can only store 1 type of data?

eternal night
#

you cannot store different data under the same key

midnight shore
#

in my experience yes

summer scroll
#

ah im dumb

eternal night
#

I mean

#

you could but like good luck

#

it is a map in the end

#

your key has one and only one value

summer scroll
#

got it, thank you

midnight shore
#

you could store two values under the same namespace by probably serializing a class that holds that two values (if i'm wrong correct me) to a byte

midnight shore
sharp flare
summer scroll
#

Each key can only store 1 data type

sand vector
#

Is there a way of getting the block location from the InventoryOpenEvent? Needing to find the chest clicked

eternal night
#

get the inventory holder

#

check if the holder is an instance of a Chest

#

and then there ya go

sharp flare
summer scroll
midnight shore
sand vector
sharp flare
summer scroll
#

wdym?

noble lantern
midnight shore
#

So basically now it kinda works @eternal night . No error is thrown but the skull doesn't change its texture

sharp flare
midnight shore
rough drift
#

I found the fix

#

Dumb me

midnight shore
#

okay

midnight shore
noble lantern
#

whoever said you cant iterate over something and remove it you are correct

#

you need to use iterators

rough drift
#

add*

#

but yeah i found my fix

sharp flare
# summer scroll really?

Oh my bad, wdym by really though, is it the different values i mentioned? Me being dumbass cuz im sleepy af

noble lantern
#

remove or add, either way gives a CME

rough drift
#

Just add everything to a list and add it at the end

#

lol

midnight shore
eternal night
#

or just use removeIf(Predicate)

rough drift
#

I need

eternal night
#

or an iterator

rough drift
#

to

#

add

#

not remove

#

but I found my solution

midnight shore
summer scroll
sacred mountain
#

what does it change in the long run

rough drift
#

SkullMeta#setOwner

midnight shore
#

look at the photo please

#

i need a custom skull not a player skull

rough drift
#

oh

midnight shore
#

and it is for blocks

rough drift
#

ooooooooooooo

#

k

sharp flare
summer scroll
#

@noble lantern this is what I got right now, following your suggestion to update every 5 ticks, but I got this ugly problem when the item is updated, is there any workaround or fix?

summer scroll
sharp flare
summer scroll
#

You can see the video I sent above.

glossy venture
#

for pre allocation

#

performance

#

its an unneccessary optimization

sacred mountain
#

so it doesnt actually affect the

#

chance picking

glossy venture
#

no

midnight shore
#

anyoneee?

#

is this right??

noble lantern
noble lantern
#

there should be a setBlockState or similar

summer scroll
midnight shore
noble lantern
#

It looks like its working?

summer scroll
#

It's working yes, but the animation is very bad, looks very scuffed.

noble lantern
#

you not want it to do that dippy thing huh

#

not do*

summer scroll
#

yup

noble lantern
#

cancel interact event

midnight shore
#

this is block state

noble lantern
#

well

#

SKull is deprecated

#

so im not sure why you use that class

#

You should be using BlockData to manipulate skulls

midnight shore
#

Skull is a BlockState thing

#

not a BlockData

#

finally got it working

summer scroll
noble lantern
noble lantern
#

You should be using BlockData/BlockDataMeta

summer scroll
noble lantern
#

unless your developing on ancient 1.8

noble lantern
#

or only updating the meta

summer scroll
#

And I set the ItemMeta quite often, every 5 ticks.

#

Only updating the meta

midnight shore
noble lantern
noble lantern
#

im not sure why Skull isnt showing deprecated to you

#

oh fuck

#

mb

#

duck duckgo is stupid

#

it showed me old asf javadocs

#

ignore everything i said, my apologies

midnight shore
#

oookkk

#

don't worry

midnight shore
#

what kind of pizza is this could you try to guess?

#

i don't understand

noble lantern
#

You might need to use packets @summer scroll and cancel the packet the plays the re-equip packet

summer scroll
#

Uh oh

noble lantern
#

theres this thread

#

according to the last post you might not be able to cancel it :c

summer scroll
#

If it's not possible to cancel, then I might have to change how to store the item's data then.

#

I'm thinking about having a uuid each item, and store the data into yaml when server stops and load them on server start.

noble lantern
#

meh i wouldnt worry about storing cooldowns on server start/stop for items especially if there some type of skill

#

You might have to just handle this in your UserData class as mentioned earlier

#

I would try canceling the packet first

#

thats the only singular i post i saw where someone said you cant cancel it

summer scroll
#

On the last post it says that the animation is played first before sending the packet.

noble lantern
#

theres this post here

#

you might be able to

#

its worth a try

sacred mountain
#

how do i get HOW an entity was killed?

#

as in like, shot, fall damage, etc

#

is it getLastDamageCause()

noble lantern
#

that returns the EntityDamageEvent, which in turn should get the reason

sacred mountain
#

yeah but there's just 'ENTITY_ATTACK'

#

not a specific one

summer scroll
#

Alright, I'll try to cancel the animation packet

sacred mountain
#

nothing like entity_attack_melee or entity_attack_ranged

#

or any specific thing

noble lantern
#

are you just listening to EntityDeathEvent right or something else

#

ah

noble lantern
#

SHould be a method that returns this enum: getCause()

celest scaffold
#

how do i remove this thing for only one log

#

it comes out ugly

quiet ice
#

Why not not use newline?

noble lantern
#

I dont think you can modify spigots logger

celest scaffold
#

this is why

quiet ice
#

Your probably can, but I'd advise against it

celest scaffold
quiet ice
celest scaffold
#

well

#

i got a idea

#

i will put this thing in string and i will put before the database login check

quiet ice
#

And don't use Sysout, you'll get a bug report at some point

#

Don't use the newline char

celest scaffold
#

yeah it's better than before i think

quiet ice
#

If you really want do something like for (String ln : line.split("\n")) {getLogger().info(ln);}

noble lantern
#

why not just send these all as seperate logs instead of appending like above ^

celest scaffold
#

because i want to look like this

quiet ice
#

And beware that huge banner messages aren't well liked by the admin community

celest scaffold
#

but i can keep data in left side

noble lantern
celest scaffold
#

well

quiet ice
#

Yeah

celest scaffold
#

well

noble lantern
#

plus its gonna look super funky in server log files

celest scaffold
#

got a idea again

quiet ice
#

It might even break a few log parsers

celest scaffold
#

brb

quiet ice
#

As soon as you use somethign other than monospace your message will look ugly

celest scaffold
#

i think it's better

noble lantern
#

no need for \n doing that

steel swan
#

hey, from an online website, i have this code for a custom world.

Where do i put it when the world is creating (im using worldcreator btw)

celest scaffold
noble lantern
#

if its a java question

#

you need to go through that json object

noble lantern
#

and go through each field and set it as a settings in WorldCreator class

noble lantern
celest scaffold
#

well

#

i think i want to know how to plug the json in java

noble lantern
#

Gson#fromString

#

returns an object

celest scaffold
#

it's uneditable thing

#

for user

noble lantern
# celest scaffold

i hope this wont be a public plugin and your hard coding database info in

celest scaffold
#

it wont be lol

river oracle
#

You should use a config for this tbh

celest scaffold
#

ik..

#

wait

#

i do remember you from somewhere

river oracle
#

If you need a config tool I can give you one

river oracle
celest scaffold
#

well

steel swan
# steel swan hey, from an online website, i have this code for a custom world. ```{"useCaves"...

if it can help, here is my code :

if (command.getName().equalsIgnoreCase("roofed")) {
            Player player = (Player) sender;
                WorldCreator worldcreator = new WorldCreator("Monde_Jeu");
                worldcreator.type(WorldType.NORMAL);
                worldcreator.generateStructures(true);
                worldcreator.createWorld();
                WorldBorder worldBorder = worldcreator.createWorld().getWorldBorder();
                Location location = new Location(Bukkit.getWorld("Monde_Jeu"), 0,0,0);
                worldBorder.setCenter(location);
                worldBorder.setSize(500);
                worldbordersize = 250;
                for (Player playerr : Bukkit.getOnlinePlayers()){
                    playerr.teleport(new Location(Bukkit.getWorld("Monde_Jeu"), getRandomNumber(-200,200), 200, getRandomNumber(-200,200)));
                }
        }

ik that i would need to use the Customized world type i just havnt changed it rn

celest scaffold
#

no mutual servers, friends or dm

river oracle
#

Where would it be from lmao

celest scaffold
#

idk lol

noble lantern
#

you need to go through that json object and apply it to WorldCreator class for every field in that json object

steel swan
#

ok lemme check

noble lantern
#

Gson is built into Spigot you can use the fromString method

celest scaffold
#

ok i think it's ok

noble lantern
celest scaffold
#

thanks :)

#

also what you mean admin community?

#

if i will make private server?

noble lantern
#

well since its just a plugin for your server i assume dont worry about it

celest scaffold
#

ok

steel swan
celest scaffold
#

so you meant by server devs, not spigot admins

steel swan
#

like u mean in the code of worldcreator?

noble lantern
steel swan
#

but how would i use worldcreator to put it in the json object ? like wich method

noble lantern
#

Do you want

#

WorldCreator -> Json

or

Json -> WorldCreator

steel swan
#

lemme explain, i have those parameters for a world. I create a world with world creator. what i want is to add those parametres to the world. But idk how to do that

noble lantern
#

Then you need to loop through those parameters you have and apply them to WorldCreator

steel swan
#

like is there a special method?

noble lantern
#

Its not very simply

#

you have custom block settings it seems

steel swan
#

yes

noble lantern
steel swan
#

ok imma read that out

steel swan
#

OH

noble lantern
#

that should help for the block settings

steel swan
#

i should of said one thing

#

i m using 1.8.8 ( i know very bad version but i dont have a choice)

noble lantern
#

Hmm

#

might need to use NMS idk if that class exists in 1.8.8

#

idk if thats an official javadoc though

steel swan
#

yeah it is

#

im already using that

noble lantern
steel swan
#

hmmmm

#

smth like that for instance?

#

worldcreator.generatorSettings("usecaves"= true; )

noble lantern
#

you should be able to shove your whole json object in that argument

steel swan
#

there is an error lmao

#

event when putting 1 argument

noble lantern
#

whats the error

#

send the full error

steel swan
#

okeeey

marble granite
#

So, when i create a custom item with an extra NBT tag, but it has the material of a Diamond Block, how can i prevent that custom item being turned into normal diamonds in the crafting table?

marble granite
#

i know i can override the default recipe with my own, but thats not ideal

noble lantern
#
  1. prevent the diamond block with NBT from being put into a crafting GUI's slots
  2. Cancel result slot click if the ingredient in the table is the item with your NBT tag
lean gull
steel swan
noble lantern
#

send your code too

#

?paste

undone axleBOT
steel swan
#

or just that part

marble granite
noble lantern
#

just that part where your getting the Json object and inputting it into WOrldCreator

steel swan
#

ik i might have made a stupid mistake

vivid hill
#

CraftHumanEntity does not work for me how can i fix that?

noble lantern
#

encapsulate that json object as a string

#

"thatobject"

steel swan
noble lantern
noble lantern
vivid hill
#

and I already found a workaround but i dont now how to implemt this in my code

#
"org.bukkit.craftbukkit." + Bukkit.getServer().getClass().getPackage().getName().split( "\\." )[3] + ".entity.CraftHumanEntity" 
);
Field field = craftHumanEntity.getDeclaredField( "perm" );
field.setAccessible( true );
field.set( player, new CustomPermissibleBase( player ) );
field.setAccessible( false );```
#

thats whta i found on github

steel swan
#

?paste

undone axleBOT
steel swan
lean gull
#

version of?

steel swan
#

minecraft

lean gull
#

1.18.2

granite owl
#

if i cast ```java
ItemStack.getItemMeta().toString()

steel swan
#

ok so there is a built in way to do it

lean gull
#

which is?

steel swan
#

i used to use 1.18.2 so lemme think

#

uuuuuh

#

ok so

lean gull
#

:proccessing:

steel swan
#

biomeProvider(String biomeProvider)

lean gull
#

how- how do i use that

#

sorry i do not got the big of the brain

steel swan
#

been a long time so

#

try out worldgenerator.biomeProvider("name of ur biome")

lean gull
#

what's worldgenerator? the chunk in the 2 for loops?

steel swan
#

oh my

#

send ur code

#

?paste

undone axleBOT
lean gull
#

pretty much the code from the tutorial lol

steel swan
#

ok so

#

ooooh

#

i see

#

there is a setBiome() thing

#

try it for the chunk

#

imma be back

lean gull
#

nop

#

only getBiome

steel swan
#

100% sure there is

#

imma be back later

lean gull
#

also there is no .getBiome().set()or whatever

#

wait i think i got it

#

there's a biome parameter in the method

steel swan
sacred mountain
#

hey, what is the CUSTOM and CONTACT death types?

#

in the DamageCause enum sorry

#

not the death type

#

is contact like entity cramming?

#

nvm the docs say

#

sorry

quaint mantle
#

Hey there guys, new to Java dev, I'm trying to extract some data from the console when an event happens from Economshop GUI, I'm looking to tax players when they sell stuff by parsing data logged to console

18:14:31
[EconomyShopGUI]: User sold 1 x Diorite for $0.18 with the sell screen.

is an example of what I will be using to extract into a plugin, does anyone recommend any approach for trying to see what is logged and then using the data here? I want to parse 0.18 from console and apply a tax on the value

jagged thicket
granite owl
#

well rip me i guess

quaint mantle
#

hey, it is not directly an question to spigot programming itself. But it is the first time that i downloaded source code from github and edit it. it is an spigot plugin that i want to edit for my server. If i build the plugin, will it automatically upload the changes to the github repository? because i dont want that. i dont want to update the github repository of this plugin with my changes.

compact haven
#

no

quaint mantle
#

i dont know how this git(hub) stuff works.

compact haven
#

Even if it did, git is a Version control system, you’d be able to revert it

quaint mantle
#

Okay thanks for the quick answer. The changes i made would not make sense in the main repository.

compact haven
#

It won’t push or commit automatically

kind hatch
#

Also, if you download from someone else’s repository, you’d have to create a pull request if you wanted your changes to be submitted to the repo.

quaint mantle
#

Okay. then its fine. i only want to build the plugin locally

compact haven
#

oh yeah didn’t even catch that part

#

you aren’t added to the repo aha

quaint mantle
#

Okay and how can i build source code in gradle? i only work with maven normally. thats why i dont have experience with gradle

normal isle
#

is someone kind enough to make a plugin that stops mushrooms blocks to generate?

#

(:

sand vector
#

So I have a PlayerInteractEvent which checks to see if a chest is left clicked. I then set the block clicked to Chest by casting Chest. However, when running this code I get an error which says that block.CraftBlock cant be casted to block.Chest. How do I do this?

kind hatch
#

Why are you setting the block to a chest if the block you’re checking for is already a chest?

sand vector
#

I need to get the inventory title of the chest

mossy prairie
#

Anyone knows why would this happen when trying to refresh my project?

#

Spigot

kind hatch
kind hatch
#

I think you need to cast the blockstate to a chest instead.

quartz valve
#

Why do I get this error?

Code:

public static Boolean isEnoughPlayer()
    {
        Boolean bool = false;
        Integer count = 0;
        Integer teams = Main.TEAMS;

        for(Player p : Bukkit.getOnlinePlayers()){ //ERROR LINE
            if(!Main.PLAYERTEAM.containsKey(p)){
                count++;
            }
        }
        while(teams > 0){
            if(Main.TEAMLIST.get(teams).size() > 0){
                count++;
            }
            teams--;
        }

        if(count >= Main.MINPLAYERSTART){
            bool = true;
        }else{
            bool = false;
        }

        return bool;
    }

Error:

Caused by: java.lang.StackOverflowError
    at com.google.common.collect.Lists$TransformingRandomAccessList.listIterator(Lists.java:579) ~[SPIGOT_1_8_8.jar:git-Spigot-db6de12-18fbb24]
    at java.util.AbstractList.listIterator(AbstractList.java:299) ~[?:1.8.0_312]
    at com.google.common.collect.Lists$TransformingRandomAccessList.iterator(Lists.java:576) ~[SPIGOT_1_8_8.jar:git-Spigot-db6de12-18fbb24]
    at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:1041) ~[?:1.8.0_312]
    at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:1040) ~[?:1.8.0_312]
    at de.vinemc.plugin.mine2death.GameFunctions.isEnoughPlayer(GameFunctions.java:125) ~[?:?]
kind hatch
#

Which should be available as chest is a block, so you can just use #getBlockState() on it.

sand vector
#

ok let me try that quickly

glossy venture
#

how do minecraft furnaces work?

#

does it re-evaluate the recipe every tick for every block

#

or does it store the recipe in the nbt tag or something like that

#

and rematch that every time the input is modified

sand vector
granite owl
#
21.04 17:47:14 [Server] INFO Caused by: java.lang.ClassCastException: class java.lang.ClassNotFoundException cannot be cast to class java.util.ArrayList (java.lang.ClassNotFoundException and java.util.ArrayList are in module java.base of loader 'bootstrap')
``` why? ```java
public static void onPlayerJoin(Player p)
    {
        File invDir = new File(Utils.getOwnDir + "inv");
        
        if (invDir.exists())
        {
            if (new File(invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin").exists())
            {
                ArrayList<Item> itemFile = (ArrayList<Item>) Utils.deserializeFromFile(invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin");
                //itemFile = (ArrayList<Item>) obj;
                if (itemFile instanceof ArrayList)
                {
                    Bukkit.broadcastMessage("IS INSTANCE");
                }
                else
                {
                    Bukkit.broadcastMessage("IS NOT INSTANCE");
                }
                
                //ArrayList<Item> itemFile = (ArrayList<Item>) Utils.deserializeFromFile(invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin");
                //ItemStack[] itemList = new ItemStack[41];
                //int i = 0;
                //for (Item item : itemFile)
                //{
                    //itemList[i] = new ItemStack(item.getType(), item.getAmount());
                    //i++;
                //}
                
                //p.getInventory().setContents(itemList);
            }
        }
    }
#

it serializes correctly

#

but it fails to cast into the type

eternal night
#

your utils thing is doing something not good

sharp bough
crisp steeple
quaint mantle
#

its not the full thing but it tells everything you need to know

quiet ice
#

Unless you serialised a CNFE

eternal night
#

lol

#

Yea pretty much, please paste your deserializaion

#

?paste

undone axleBOT
crisp steeple
#

i mean it’s pretty obvious a classnotfoundexception can’t get cast to an arraylist

granite owl
#

okay wait

#

first off

#

this is what i use

quiet ice
#

I'd assume that in case of an exception, the deserialize method returns the exception. Which is a bit strange but eh

eternal night
#

yea but either it actually serialized a CNFE or the deserialize method returns a CNFE

granite owl
#
public static Object serializeToFile(Object obj, String str)
        {
            try
            {
                return (Object)SerializePtr.invoke(UtilsPtr, obj, str);
            } 
            catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
            {
                e.printStackTrace();
            }
            
            return null;
        }
        
        public static Object deserializeFromFile(String str)
        {
            try
            {
                return (Object)DeserializePtr.invoke(UtilsPtr, str);
            }
            catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
            {
                e.printStackTrace();
            }
            
            return null;
        }
quiet ice
#

Oh no wtf

granite owl
#
public static Object serializeToFile(Object obj, String str)
    {
        try
        {
            ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(str));
            s.writeObject(obj);
            s.flush();
            s.close();
            
            return 0;
        }
        catch (Exception e)
        {
            return e;
        }       
    }
    
    public static Object deserializeFromFile(String str)
    {
        try
        {
            ObjectInputStream s = new ObjectInputStream(new FileInputStream(str));
            Object ret = s.readObject();
            s.close();
            return ret;
        }
        catch (Exception e)
        {
            return e;
        }
    }
eternal night
#

👀

#

you are actually returning the exception

#

wtf

granite owl
#

that is what i use to serialize

#

only if it fails

eternal night
#

you don't return an exception

#

that isn't the point of exceptions

#

you throw them

quiet ice
#

Yeah, Propagate the exception

eternal night
#

this isn't golang 😅

granite owl
#

so thats why i cant i deserialize ahhh

eternal night
#

Well it is failing somewhere

granite owl
#

it works just fine

#

using ArrayList<String> as type

#

oh and btw thats my Item

#
package admin.commands;

import java.io.Serializable;

import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class Item implements Serializable
{
    private static final long serialVersionUID = -338300065334497259L;
    
    public String type = "";
    public String meta = "";
    public int amount = 0;
    
    public Item(ItemStack is)
    {
        super();
        this.type = is.getType().toString();
        if (is.hasItemMeta()) this.meta = is.getItemMeta().toString();
        this.amount = is.getAmount();
    }
    
    public void setType(Material type)
    {
        this.type = type.toString();
    }
    
    public Material getType()
    {
        if (!this.type.equals(""))
        {
            return Material.valueOf(this.type);
        }
        
        return null;
    }
    
    public void setMeta(ItemMeta meta)
    {
        this.meta = meta.toString();
    }
    
    public ItemMeta getMeta()
    {
        if (!this.meta.equals(""))
        {
            ItemStack dummy = new ItemStack(Material.AIR, 1);
            ItemMeta meta = dummy.getItemMeta();
            //return this.meta;
            return null;
        }
        
        return null;
    }
    
    public void setAmount(int amount)
    {
        this.amount = amount;
    }
    
    public int getAmount()
    {
        return this.amount;
    }
}
eternal night
#

Yea that doesn't matter. properly throw the error

#

and see what goes wrong

granite owl
#

its an error thrown by the bukkit layer

#

and btw it serializes just fine

#
¬í sr java.util.ArrayListxÒ™Ça I sizexp   )w   )sr admin.commands.ItemûNâ
>ð I amountL metat Ljava/lang/String;L typeq ~ xp   t IUNSPECIFIC_META:{meta-type=UNSPECIFIC, enchants={DAMAGE_ALL=1}, Damage=1}t NETHERITE_SWORDsq ~    @t  t 
DIAMOND_BLOCKsq ~    q ~ t WOODEN_SWORDsq ~    q ~ t  CHICKENsq ~    q ~ t  FEATHERsq ~    t 0UNSPECIFIC_META:{meta-type=UNSPECIFIC, Damage=1}q ~ 
sq ~    q ~ t 
GRASS_BLOCKsq ~    q ~ t AIRsq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ sq ~    q ~ q ~ x
#

otherwise id throw an error in the file

#

this represents an arrraylist filled with the player invs content using my wrapper class

crisp steeple
#

send the actual classnotfoundexception

granite owl
#

from the server?

crisp steeple
#

yes?

granite owl
crisp steeple
#

that’s not the exception

granite owl
#

then wdym

crisp steeple
#

you are trying to cast

#

the classnotfoundexception to your arraylist

#

because it’s getting returned from your util method instead of thrown/printed

granite owl
#

wait

#

sure ive rewritten it

#
 public static Object serializeToFile(Object obj, String str)
    {
        try
        {
            ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(str));
            s.writeObject(obj);
            s.flush();
            s.close();
            
            return null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }     
        
        return null;
    }
    
    public static Object deserializeFromFile(String str)
    {
        try
        {
            ObjectInputStream s = new ObjectInputStream(new FileInputStream(str));
            Object ret = s.readObject();
            s.close();
            return ret;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
```+
crisp steeple
#

ok

#

so run it again

#

and see what message it prints this time

granite owl
eternal night
#

(but generally, you will need to use BukkitObjectInputStream instead of ObjectInputStream)

granite owl
#

bukkit independent

#

good to know tho i can try that i guess

eternal night
#

Yes but that class contains bukkit instances

#

does it not

granite owl
#

hm

eternal night
#

BukkitObjectInputStream extends ObjectInputStream

#

it still does the same thing

crisp steeple
eternal night
#

just also properly works with bukkit things

granite owl
granite owl
#

to adapt

#

i need to rewrite it because my serializer is accessed using reflection

#

i suppose using the BukkitObjectOutputStream i can just serialize the entire player inventory?

eternal night
#

yes

#

wewll

#

their ItemStack[]

granite owl
eternal night
#

ye

granite owl
#

ive only written the wrapper class because

#

i wasnt able to store bukkit objs

#

sure lemme try

#

problem is i cant reflect bukkit instances from loading a class

#

so i need a sec to rewrite it

eternal night
#

take your time 👍

granite owl
#

@eternal night so like this?

#
public static boolean serializeBukkitObjectToFile(Object obj, String str)
    {
        try
        {
            BukkitObjectOutputStream s = new BukkitObjectOutputStream(new FileOutputStream(str));
            s.writeObject(obj);
            s.flush();
            s.close();
            
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }     
        
        return false;
    }
    
    public static Object deserializeBukkitObjectFromFile(String str)
    {
        try
        {
            BukkitObjectInputStream s = new BukkitObjectInputStream(new FileInputStream(str));
            Object ret = s.readObject();
            s.close();
            return ret;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
eternal night
#

That should work ye

granite owl
#
ItemStack[] itemList = p.getInventory().getContents();
        
        NonReflectables.serializeBukkitObjectToFile(itemList, invDir.getPath() + '/' + p.getUniqueId().toString() + ".bin");
```trying this implementation
#

sec

eternal night
#

Quick suggestion, you could just use a try-resource

#

closing a file stream iirc also flushes it