#help-development
1 messages ยท Page 2043 of 1
XDD
no
hm
how do I know if methods are intensive?
looking at how many lines of code it has :kek:?
or nanoTime?
lines wont tell u that much
:(
but I suggest benchmarking
which can be done in combo with unit tests
if you for instance use mockbukkit
altho if u use paper (which if i remember you do) then eventexecutors are generated by asm or sth iirc
The basic Italian keyboard layout as shipped with Windows 7 has no way of typing the backtick (`) or the tilde (~)
You can use Alt + 96
so being afraid of playermoveevent lag is the least of your concerns
asm? what's that?
i'll go see what eventexecutors have. thanks!
better to just go sleep for me
public static UUID getUuidFromName(final String playerName) {
final Player player = Bukkit.getPlayerExact(playerName);
if(player != null) return player.getUniqueId();
final Optional<UUID> uuid = Arrays.stream(Bukkit.getOfflinePlayers()).filter(offlinePlayer -> {
final String name = offlinePlayer.getName();
if(name == null) return false;
return name.equalsIgnoreCase(playerName);
}).map(OfflinePlayer::getUniqueId).findFirst();
return uuid.isPresent() ? uuid.get() : null;
}
this get's the UUID without deprecated methods lol
is Bukkit.getOfflinePlayers and array?
all players who have connected once are mapped
@tender shard teye ill apply that tomorrow, tbh its like 4-5 years ago since ive worked with the bukkit/spigot api
yes
do any of u guys know why @p doesnt work on my server anymore
ah thats why
been trying to get around the issue but i cant have players teleport to towns with command blocks now and idk if theres a plugin to make @p @r and all that work
yes
can you block the "respawn point set" message or messages like it using a plugin
give lib ideas
replace the last line with uuid.orElse(null)
ez
i'm going to take this as a no
ternary cooler
๐คจ๐คจ๐คจ๐คจ๐คจ
orElse is NotNull
oh I thought they were using guava's optionals
in guava somehow null is not allowed in orElse lol
yeah i dont use guava except for things i cant remember right now
oh right
guava comes with Maps and Lists
iirc
yeah I was confused because I always use Enums.getIfPresent, and that doesn't accept null
ah yeah
i think for enums i check using apache commons io
its like EnumUtils.isValidEnum
I got this lol https://paste.jeff-media.com/?bbaf2861feadaa08#8197cL17vCTQasPs4tGhRo1xRPy3mtkVhMuqv6SqS2rX
Visit this link to see the note. Giving the URL to anyone allows them to access the note, too.
your website looks cool
imma build this in rust
ooohh
html builder in rust
htmlrs
same
hey so im using this tutorial [https://bukkit.fandom.com/wiki/Developing_a_World_Generator_Plugin] to learn world gen, and in the tree populator section they said to add this method to the main custom chunk generator class:
@Override
public List<BlockPopulator> getDefaultPopulators(World world) {
return Arrays.asList((BlockPopulator)new TreePopulator());
}```so i did that, but it doesn't seem to do anything and the `BlockPopulator` is gray in my IDE
thats sad
remove the (BlockPopulator) cast
so ig i know one thing
its redundant
i rly wanna make websites and shit
but it seems so hard to learn 3 coding languages
just for front end
doubt
if you learn languages with apps you're not learning anything
i literally learn every language with google
i learned java now i can learn any language i want to tbh
and js
still doesn't work
I learn every language by having a project and make it
it works but you wont see it do anything ๐ฎ
y
smh someone just make a click and drop website front end generator
js is very similar to java so should be easy to pick up
not every method has a printline telling you that its being ran ๐ฑ
html isnt that hard either
wat dat mean
css is doe
css is just very boring in my opinion
dude just follow the damn tutorial
:D
does it work?
does what work
i hate being a helper sometimes
i hate inpatient people sometimes
touche
Lmao
checkmate
lmao
:sunglas:
Development isn't for everyone that's for sure.
ouch
i hate your bio
i hate him as a whole
You don't like my websit?!
i dont like your existence
Why
Because I want to
i dont like ur mom
Fair can't please everyone
๐คทโโ๏ธ
because
?notworking
"Does not working" is a useless statement. Please describe what exactly is not working, what you expect it to do, and what actually happens. If you get any console errors, also ?paste the entire stacktrace.
it doesnt like you
thats useful
beg it to wowrk
fourteen i already said the problem like 2 mins ago
like we dont know that
just keep re compiling
im sure at one point it will work!
yes that is so big brain
Don't use Google throw your router out your window and set your pc on fire
y2k_ you were cool once
what is the treepopulator supposed to do?
make tree on world
@Override
public void populate(World world, Random random, Chunk chunk) {
if (random.nextBoolean()) {
int amount = random.nextInt(4) + 1; // Amount of trees
for (int i = 1; i < amount; i++) {
int X = random.nextInt(15);
int Z = random.nextInt(15);
int Y;
for (Y = world.getMaxHeight() - 1; chunk.getBlock(X, Y, Z).getType() == Material.AIR; Y--)
; // Find the highest block of the (X,Z) coordinate chosen.
world.generateTree(chunk.getBlock(X, Y, Z).getLocation(), TreeType.TREE); // The tree type can be changed if you want.
}
}
}```
imma be honest idk what im doing im just copying the code from the tutorial
then understand it
why are you overriding the old deprecated method?
try to use the proper method instead
public void populate(@NotNull WorldInfo worldInfo, @NotNull Random random, int x, int z, @NotNull LimitedRegion limitedRegion) {
}
the new method looks weird
Take a look at how essentials does it https://github.com/EssentialsX/Essentials/blob/2.x/Essentials/src/main/java/com/earth2me/essentials/commands/Commandtree.java
i copy paste teh thing from tutorial i know better
@lean gull worldgen changed this update so the tutorials kinda out of date
@tender shard you should update it
that has nothing to do with world generation / blockpopulaters
noOoOooOO
I have never done anything about world gen lol
i know i'm gonna get ratio'd and 1 million no's but can someone teach me how to do world gen then
who told me when what why
yeah but then i have to change the code and idk how to do that
then print out some text in that method to see if it actually gets called
well just look at the parameters
obviously you get an instance of WorldInfo, Random, and a LimitedRegion
and also x,z but you can ignore that
and then, well, obviously you can use the LimitedRegion to change blocks
btw this is not what im tryna do, i don't want to replace the main world of the server, i wanna make a customizable generator where it generates a different world than the main one with like presets and sliders and whatnot
๐คทโโ๏ธ
this is awesome
finally I can make people actually force to tell me the name of the plugin they opened a ticket for
only Text fields and paragraph fields
well at least my ticket bot only supports text and paragraph
maybe discord actually supports more
haven't tried, already removed it again lol
I'll do some testing tomorrow then change my ticket stuff to ask some questions first
so uh i wanna make a train sort of thing
so multiple minecarts followed by each other
in the front theres a player that can move all the carts with the keys (w,a,s,d)
any ideas?
reasking this question for the last time: can you suppress minecraft's messages to a player such as when you right click a bed and it says "Respawn point set"
I don't think so, it's client sided
alright i see
maybe you can cancel the interact event?
yeah but wouldn't that disallow them from sleeping?
you can make them sleep manually
how's that
do tell me because this is something i've been trying to figure out for a while
Player#sleep
Player has a method sleep(Location, boolean)
ok
so you cancel minecraft's default event and just make your own sleep thing
smart
probably would
doesnt that still set the respawn point?
as would happen when you try to sleep at day?
not when you just cancel the right-click event
cancelling the event still prints a message
yeah but that doesn't prevent the "Respawn point set" message
but what if they don't enter it
@desert musk do you just want to remove the message?
or the respawn being set as well
the respawn being set as well
but i conceded and decided that I could just hack in a way to sloppily reset the player's spawnpoint when they enter bed
but i want a more concise approach
There's also this, https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/player/PlayerBedLeaveEvent.html#shouldSetSpawnLocation() if you just want to cancel the bed setting the player's spawn
it should be simple, right?
oh hell yeah
why couldn't i find that??
what magic are you using
I don't know if that also does it when a player clicks a bed during daytime, but it might get called?
actually @desert musk u think u can use PlayerBedLeaveEvent
probably
Experience ๐ช
really?
u can set setspawn to false i believe
i'm a c++ andy doing plugins for the first time lol
huh,
why would that be in leave and not enter
so strange
well thanks guys
lol, apparently there's no setter for it either
declaration: package: org.bukkit.event.player, class: PlayerBedLeaveEvent
yea agreed
you would think that would take a location
and set the location instead
mmm
Based on the name yeah that's what I thought it implied heh
well don't write to mojang i don't wanna have to update my plugin lol
That'd be an us thing 
hehe
It'll stay though. We like to keep compat
respectable
md_5 does :d
my plugin is returning an exception even though im pretty sure this shouldnt cause an NPE
Ambiance.isMusicEnabled.putIfAbsent(e.getPlayer().getUniqueId(), true);
Bukkit.getScheduler().runTaskLater(Ambiance.plugin, () -> {
if (Ambiance.isMusicEnabled.get(e.getPlayer())) {
List tracks = Ambiance.config.getStringList("Soundtracks");
int trackCount = tracks.size();
int soundNumber = new Random().nextInt(trackCount);
Sound track = Sound.valueOf((String) tracks.get(soundNumber));
String volume = Ambiance.config.getString("volume");
e.getPlayer().playSound(e.getPlayer(), track, Float.parseFloat(volume), 1);
}
}, 3);
what's join event line 20?
if (Ambiance.isMusicEnabled.get(e.getPlayer())) {
your hashmap doesn't contain the player
except it should put it in the hashmap if its not there
Ambiance.isMusicEnabled.putIfAbsent(e.getPlayer().getUniqueId(), true);```
no, you add the UUID
hense this
your hashmap contains UUIDs and not players
:D
btw you can also use boolean enabled = map.computeIfAbsent
boolean enabled = map.computeIfAbsent(player.getUniqueId(), __ -> true);
this gets the stored value, or returns and stores true
yes it shows a warning ๐
yee thats what i thought
so thats what computeifabsent does
always been too lazy to find out
actually pretty usefull
yep I use that all the time for caching stuff
e.g. for namespacedKeys
public static NamespacedKey getValueKey(final String name) {
return VALUE_KEYS.computeIfAbsent(name, __ -> NamespacedKey.fromString("v:" + name));
}```
yea, thats pretty nice actually
is there a way to just return the number of achievements a player has?
sounds niche but
would be nice to put on a scoreboard
i guess u could loop all achievements and test with Player#hasAchievement
Achievements no longer really exist, I assume you mean advancements?
Does anyone know how to get the durability of an itemstack? ItemStack#getDurability() is depricated and returns 1
o yeah
I know you can retrieve advancements from the Player object
Cast the meta to Damageable
Not at all
I actually don't know if there's a way to get a list of all advancements 
At least I don't recall one
f
I could have sworn I had messed with advancements before
But it appears I am schizophrenic
๐คทโโ๏ธ
Cant cast to it
wrong one
Because realistically you'd have to do,
for (Advancement advancement : Bukkit.getAdvancements()) { // Which doesn't exist
if (!player.getAdvancementProgress(advancement).isDone()) {
return false;
}
}
return true;```
Gotcha now tahnks
Oh, wait, there is
Bukkit#advancementIterator
declaration: package: org.bukkit, class: Bukkit
Ouch too slow
Yep
Bukkit.getServer().advancementIterator(); ?
There's also the Registry.ADVANCEMENT you could iterate over but the Iterator works as well
you probably also have to get rid of all the Recipe "Advancements"
public static int getAchievements(final Player player) {
Iterator<Advancement> it = Bukkit.advancementIterator();
int advancements = 0;
while(it.hasNext()) {
Advancement advancement = it.next();
if (advancement.getKey().getKey().startsWith("recipe/")) continue;
if (hasAdvancement(advancement, player)) advancements++;
}
return advancements;
}
private static boolean hasAdvancement(Advancement advancement, Player player) {
return player.getAdvancementProgress(advancement).isDone();
}```
+1
or you could be really cute and add a method to get an advancement array from the player

Well, advancements aren't really stored like that. Only their progress is
So a player has all advancements on the server, but what's stored is how far they've progressed in it
Yeah I feel like if it were that simple, there would have already been a method for it
Hey, this might be a dumb question, but anyone knows why this isn't working?
NBTEditor isn't working at all.
sounds like you are not properly including whatever library that comes from
did you add that lib to your pom.xml or build.gradle?
uh what lib?
NBTEditor?
Do I need to download it?
there is no such thing as NBTEditor in bukkit
bruh thats why then
what do you need it for?
chances are high that you can use PDC instead, which is builtin since 1.14.1
I'm in 1.12.2
RIP then
where can I get it?
You mean how to update???
depends on what lib its from
Ah yeah the NBTEditor class
whoa
noteblockAPI is using java 7
now that's something I haven't seen in a long time
RIP lambdas
RIP everything
it does work but you also have to set back the changed itemmeta to the item
ItemMeta meta = itemStack.getItemMeta();
// change your meta
itemStack.setItemMeta(meta);
Hey guys, what's the right way to use external libraries in your plugin? Specifically, I'm trying to use Apache Cayenne ORM for persisting my data, but its dependency injection mechanism fails when I try to initialize it and execute a sample insert query. I do this in my onEnable hook. It's weird because everything works fine when I try and execute the plugin's jar through the main method, so it must be some runtime quirk of Spigot. I'm using maven-shadow-plugin to package deps into my jar. It seems that, somehow, the initialization code for the DI system is not executed and it has no instances to provide...
im wondering why u have to do that, isnt the meta passed by reference, so any changes should be applied to the original?
no it returns a copy
wtf why
thats so weird
weird design decision, i dont think any experienced developer would expect that method to return a copy
well I guess any experienced developer would check what the docs say and then it's pretty clear ๐
true lol
I think the reason is that
an ItemMeta object doesn't exist
it simply wraps around the NBT stuff etc
so it gets created once you need one
I guess
ah i see, that makes sense
np ๐
a good thing about rust is that- that wouldnt need to return a copy
just a &ItemMeta
what does & do
I mean, java could also just return a mutable reference
struct Food {
amount: usize
}
fn consume(food: Food) {
// this function now owns `food`
}
fn main() {
let food = Food { amount: 5 };
consume(food);
println!("{}", food.amount); // ERROR!
}
i wish someone taught it to me like this
this is all I can do in rust
fn main() {
println!("Hello, md_5!");
}
i can teach you
maybe some day ๐
Hi, I don't have much experience with spigot programming, but I made some plugins to spigiot, but I see that above version 1.18 the way you download spigots has changed, now you do it with buildTools, and I do not know how to do it. I did java -jar BuildTools.jar --rev 1.18.2, and I got file spigot-1.18.2.jar but I can't make plugin with this jar, this jar contains only 1 folder: org\bukkit\craftbukkit\bootstrap. So how I download jar that I can make plugin with.
I am using gitbash and BuildTools
Right way to use external libs?
?bootstrap
Bootstrap Jar
The main spigot-1.18.jar is now a bootstrap jar which contains all libraries. You cannot directly depend on this jar. You should depend on Spigot/Spigot-API/target/spigot-api-1.18-R0.1-SNAPSHOT-shaded.jar, or the entire contents of the bundler directory from your server, or use a dependency manager such as Maven or Gradle to handle this automatically.
Please read the release notes for further information: https://www.spigotmc.org/threads/9-years-of-spigotmc-spigot-bungeecord-1-18-1-18-1-release.534760/#post-4305163
do you actually need any NMS code?
I guess you're not using maven or gradle, right?
yes I am not, as I told I am not that experienced programmer and I don't know why I would need to use those
maven makes your life much easier by automatically handling all this dependency stuff for you. I once wrote a tiny tutorial on how to setup maven to use it with spigot: https://blog.jeff-media.com/how-to-create-your-first-minecraft-plugin-using-the-spigot-api-and-maven/
but sure, you don't have to do that, you can also use the proper "spigot-api-VERSION-shaded.jar" file
as explained here
because I'm so bright
ok thanks I will look up that
Im about to go crazy, I created a hashmap but when I try to do anything to it, it just errors out and says its null. Ive been using hashmaps for so long so maybe somthing is gettiing past me but Im going nuts trying to figure this out Please somone help.
what error message do you get
?paste the stacktrace
its a null pointer exception ik
but i have no clue why
i just tried hashmap.put(.....)
and bam error
@tender shard I have one more question, Where do I get 1.18.2 spigot jar for making server from?
if you run buildtools, there'll be a spigot-1.18.2.jar in the folder where you ran buildtools
but can this file be used to make server, or do I have to use 1.18.2-R0.1-SNAPSHOT
use the file that's called "spigot-1.18.2.jar" and is about 66mb in size
that's the one you can use to run a server
ok thanks
i think i figured it out
was trying to make multiple hashmaps in one statement
didnt realize that doesnt work
no that doesn't work
Object a, b = new Object();
// a is still null
what the?? Vector is a List?!
I always thought java.util.Vector was a math-like vector lmao
but it's actually a weird arraylist like thing
Yeah it's a List. One of the older collections in the stdlib
iirc this was pre-Collections API
There is actually a math vector API coming soon. It's been in incubation for like 3 releases now.
https://docs.oracle.com/en/java/javase/17/docs/api/jdk.incubator.vector/jdk/incubator/vector/package-summary.html
Though tbh, well-established libraries like JOML are pretty standard now for things like matrix and vector math in Java
Gotta love miss-importing the wrong vector
whoa who knew that this is valid syntax?
Rocket<String> rocket = hasRocket ? Rocket.<String>newInstance() : null;
I didn't
In some cases it's required
it looks weird to have the <> behind the dot
iirc there are some oddities with ImmutableMap builders from Guava
Where a type operator is required to specify key/value types
In fact...
If those types weren't there, it would throw a compile error
this hurts my eyes lol
I don't like this at all
But I love the exception message "This is a bug."
It's needed when the types aren't known on the called method ;p
That method for example, https://guava.dev/releases/23.0/api/docs/com/google/common/collect/ImmutableMap.html#builder--
Static method, declares types K and V, but no args to help imply what K or V is
yeah makes sense
very weird to read though, I agree lol
Just wait until you learn that this is valid as well,
public final class Main {
{
this.print("Hello!");
}
public void print(Main this, String message) {
System.out.println(this.getClass().getName() + ": " + message);
}
}```
does any1 know if its possible to show a fake beacon beam at a specific location?
Not to my knowledge. That's calculated by the client last I recall
i saw a server do it once im pretty sure
but maybe with packets
since it was player specific too
If there is a packet for it, I'm unfamiliar with it
Thatโs just explicitly declaring a parameter that is always there isnโt it
Yes
So you can annotate it
akin to Python's self that needs to be declared in every single method definition. It doesn't imply. Java does
Yeah that's valid afaik, though that's just a preference thing
C style
You can also do jagged arrays. private final int[][] array = new int[3][];
Java has some nice oddity features that rarely get used 
Wait how does that work
It's an array of variable-sized arrays
private final int[][] array = {
new int[] { 1, 2, 3 },
new int[] { 4, 5, 6, 7, 8, 9 },
new int[] { 10 },
};```
If that's any help
I see, so you donโt have to define the size of the second array
Mhmm
// rust translation
let rocket: Option<Rocket<String>, _> = if has_rocket { Some(Rocket::new()) } else { None };
or
let rocket = if has_rocket { Some(Rocket::<String>::new()) } else { None };
Hi looking to hired a Minecraft developer to create a tokenization project.
?services
If you wish to request or offer development/art/building/administration services, please do so at https://www.spigotmc.org/forums/services-recruitment-v2.54/
thank you
this site is pretty hard to sign up on ><
wdym?
Is there a benefit to reactive programming in Spigot?
i want to kill someone if he touchs water
which event will check that?
Move event
Check the block at the players location
I think there is a method for it too, but Iโm not sure if itโs for touching water or being underwater
You mean like making use of ReactorCore? Likely not. A lot of Bukkit is designed to be operated on the primary server thread, and anything that needs to be asynchronous (like IO and whatnot) can be done with the scheduler. Bukkit doesn't really design anything around asynchronous behaviour outside of events specifically labeled as async, and even that's fairly trivial
Unlike Discord APIs that make use of reactive programming patterns because most operations require some query to Discord's REST API
like this?
event.getPlayer().getLocation().getBlock().equals(Material.WATER);
event.getPlayer().setHealth(0);
event.getPlayer().spigot().respawn();
A block will not equal a material
how it should be
event.getPlayer().getLocation().getBlock().equals(Block.getByName("WATER"));???
hey guis i make a gui and how can i get if a item clicked send a message?
Use the InventoryClickEvent and sendMessage
how would I make it so the player gets a permenant elytra upon joining the server?
if(e.getCurrentItem()==null) {
}
or even give the player something upon joining
yes but how can i define the item
could i do that in on load?
beacon beam is client side
in null i put the display name of the item?
how do i make it so a player gets something upon joining?
pllllllllllllllsssssssssssss
@quaint mantle
You clearly do not understand Java well enough to tackle this yet
.
but you would use an inventory event and get the meta of the item to determine what is being clicked
I would recommend using PDC to identify said items
better yet- inventory gui frameworks are nice
they should probably start from scratch since they seem to have little understanding of how to approach it
but before that, from the questions they were asking earlier, they definitely need a better grasp on Java
how do i get around 10-25 players with mockbukkit, and make them run / jump around randomly? ||the same way i do when i am bored||
theres uh
PlayerMock player = server.addPlayer();
/// then just like, something..
and uhm, what's generally a some good resources to perfomance benchmark?
i can use mockbukkit for simulating, and JMH? junit?
Sup weebs.
So, I'm trying to get a specific a specific day every year via the following
private long computeDelayUntilNextStart() {
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
ZonedDateTime zonedNextTarget;
MonthDay monthDay = holiday.getMonthDay();
zonedNextTarget = zonedNow.withMonth(monthDay.getMonthValue()).withDayOfMonth(monthDay.getDayOfMonth())
.withYear(zonedNow.getYear() + 1);
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
The issue however is... what would be the best way to get the day after without copying the method.
Just return a hash-map with both values or what? This would be used for events that should only last a single whole day
So you want to return both the time stamp for the day itself and the day after
Yes, two different executors.
One to handle starting, one to handle stopping.
I however can't really think of a good way of handling it properly lol
Canโt you just return an array
true. I'll probably have to handle the scheduling differently in any case... hmm
public void startExecution() {
Runnable startRunnable = () -> {
// some code here, no spoilers!
startExecution();
};
long delay = computeDelayUntilNextStart();
executor.schedule(startRunnable, delay, TimeUnit.SECONDS);
}
Is how I'm doing it currently ๐
localdate.plusDays(1);
change the one to whatever is 1 year + 1 day
anyways not hard to get the next day
or which ever day ๐
oof, still doesn't help with how I should handle the runnables though ๐ค
I guess only have the end runnable call startExecution again? ๐คทโโ๏ธ
you can have a task or runnable self cancel or self reschedule
oh?
generally works most of the time
How would I go about that?
anyways if a condition is met before the runnable completes or if you just want it to keep getting rescheduled you put the code to schedule the runnable initially at the end of the runnable
if that method is located outside of the class where that runnable is at, then you need a method in that class that is static capable of doing it
so that the runnable can still invoke it
It would all be in a single class, so that's not an issue
then yeah shouldn't have any issues then
this is one of the few times where statics are handy
private long[] computeStartAndEndDelays() {
long[] delays = new long[2];
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
MonthDay monthDay = holiday.getMonthDay();
ZonedDateTime zonedNextTarget = zonedNow.withMonth(monthDay.getMonthValue()).withDayOfMonth(monthDay.getDayOfMonth()).plusYears(1);
delays[0] = Duration.between(zonedNow, zonedNextTarget).getSeconds();
delays[1] = Duration.between(zonedNow, zonedNextTarget.plusDays(1)).getSeconds();
return delays;
}
Yea?
though.. that does mean it would still have to re-call the method..
where is the code that schedules the runnable?
or is that what we are not looking at yet
separate method.
delays[][] would work
true, but it would still have to be self-updating & self-running.
since you only have 2 items, you can do it with a single array ๐
well technically it is still 2, but just one object
i.e. once one scheduler is finished, it's re-scheduled for the next time.
The fun part however, is this is setup for a specific day only, which means starting & ending that day or at least the beginning of the next lol
I can easily half-ass it by breaking DRY and doing an extra method, but I wanna try to make it as clean as possible lol
idk what that is
I mean, I could just do this https://paste.md-5.net/ugiturahiq.cs assuming it works lol
I don't follow that principle
it works for refactoring, but when creating something a pain to follow
I am of the mind set, just get it working. If you can't get it working nothing else really matters ๐
private long[] computeStartAndEndDelays() {
long[] delays = new long[2];
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
MonthDay monthDay = holiday.getMonthDay();
ZonedDateTime zonedNextTarget = zonedNow.withMonth(monthDay.getMonthValue()).withDayOfMonth(monthDay.getDayOfMonth()).plusYears(1);
delays[0] = Duration.between(zonedNow, zonedNextTarget).getSeconds();
delays[1] = Duration.between(zonedNow, zonedNextTarget.plusDays(1)).getSeconds();
return delays;
}
Would be following it, however having two methods with almost the exact same code but with a .plusDays(1) breaks it
so use a different api
there is like 5-6 different ways you could do this I believe before resorting to some outside API lol
I know, but Java's API isn't always nice
Well yea, I know this
I could probably find a dependency, but I don't want to add a bunch of dependencies if not needed
but if this is a task that is delayed by days
wouldn't the code I used work without needing all the extra stuff you have?
I mean, not sure why the time zone even matters here, if its local anyways
Removing the time-zone in this case removes only two lines of code. It would still leave the need for an array lol
two delays, two different executors. One for starting & one for stopping, seeing as it's a single day thing and must end at the end of the day
you don't know how many seconds in a day?
well I guess some people don't have it memorized
Meh, i could just add it to the initial delay but either way I'd still have to deal with two delays and two executors lol
anyways, if you do a lot of networking and dns stuff you get accustomed to knowing how many seconds in 1-2-3 days
same with milliseconds
why do you need a delay for stopping?
86400000ms in a day
86400 seconds in a day
in case you were curious
What happens is a single day thing, which means it shouldn't last more than a single day. This means there'd have to be some way to stop it after said day is up
Could be anything, in this case a specific event that should only last a single day
create a condition in the runnable that would return true only when you want said runnable to stop. If condition is met, runnable cancels itself
in this case, compare the time
if the time reaches a day, stop
you know when you started it, and you know already with math when 1 day from that time is.
sure, but the Runnable runs once per specified day.
I could use a while loop, but that's a lot of pointless code execution
that is fine? Not sure why that would affect the stop condition then if the whole point is to not have the task last more then a day
if the runnable isn't running who cares, its not running lol
That my dude is a full 24 hours of non-stop loop just to check to see if it should end
Why would it be looping unnecessarily?
If we're using a single Runnable that runs once per specified day, we'd need a loop to see when it should end
you already said you want it to end when a day has elapsed
however I assume the task shouldn't last that long
so you can have 2 conditions
It should however, in this case it would be used for a day long event lol
i.e. entire day
No
It runs once, then sets a new delay for when it should be ran again
All the runnable does is handle starting the event
does anyone know why i get this error?
from https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
tried to go a little deeper using https://docs.oracle.com/javaee/7/api/javax/json/Json.html
but still i get this
is Json not a thing or smth?
It's part of the enterprise API, you'd need to import it via your buildsystem
Don't use javax.json anyway
Use Gson
(you don't need to import Gson as a dependency manually either since it's a dependency of MC)
then you are going to want something like this then
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
Future future = executor.submit(new LongRunningTask());
executor.schedule(new Runnable(){
public void run(){
future.cancel(true);
}
}, 1000, TimeUnit.MILLISECONDS);
executor.shutdown();
Cool, however both the stop and start have to be given new delays for the next time they should be run, not shut down entirely
then tweak it
This would be for things like birthdays and such.
So the executor has to be ran once a specified day with a way to start/stop the event without doing some loop constantly, and then re-scheduled for the same day the following year.
well, unless you plan to not have the application ever quit, then you could just use a single task for that
otherwise, you are going to need to save the day it is supposed to run and have some function method upon load up that checks the day
then this thing isn't really an issue
not sure why you are making it seem like it is harder then it really is
Yea?
I'd still need some way to stop it when needed, shockingly servers can run ages without being turned off
true, so the easiest way is to make use of an event in the server that doesn't happen often
like, day night cycle, where every so often you check the day of the actual host
or..i just use schedulers and don't go about it in a hacky method that could result in things start/stopping at the wrong times
it won't?
and it's still unnecessary checking, seeing as the day/night cycle would have no purpose other than this specific use case
I don't want to do unnecessary stuff when there's a better solution
solves your issue of having an unnecessary task scheduled that only runs once a year or something
and instead I'm doing multiple unnecessary checks a day instead ๐
as if the day night cycle stops?
It still has to pick a specific point in the cycle to check
event only gets thrown when the cycle completes
not hard to know what time it is for the host and have it record an offset so you are always accurate
Cool, every 20-ish minutes then
Thereโs an event for that?
you are only using the event to schedule a task because the event is predictable
Which is still an unnecessary check every 20-ish minutes
better then a task
Shockingly, that shit adds up ๐
and no it does't add up
Yea, depending on the amount of events that specific day
this isn't going to consume much resources hardly any at all
That's still more and more unncessary calls ๐
still better then a task occupying memory and being useless the entire time
I guarantee you, the event is more optimal then scheduling a task or two, that do nothing except on a specified day whenever that day is
There could easily be 100s of checks every 20-ish minutes
72
the check is a native call
since that is what Java would use
and adds no extra resources to it
Dude, the limit depends on how many events there are
since your method only compares the current time with the time you want to run something, if they don't match
don't do anything
there is 72 day night cycles in a 24 hour period in minecraft
the event doesn't get ran if someone changes the time either
since the way MC commands work, it rewinds time, not make it go forward
but that isn't really relevant because a 1 line method isn't resource intensive to begin with
Cool, so 72 times + however many other calls that need to be made.
Bare minimum it's still 72 unnecessary calls
that don't add much to the resources, not exactly what you are worried about here o.O
I still wanna know what event this is
Could be anything really
I'm also doing the bare minimum currently
so I looked, thought there was an event for the daylight cycle, could have sworn there was one. However there is a SkipTimeEvent ironically
TimeSkipEvent *
maybe should make a PR to add such an event lol
so not even possible under your idea lol
Yeah Iโve used a timer to make such an event several times
Maybe I should do some PRs again
Still gotta use Executors lol
make one for day/night changes ๐
What exactly would that entail
basically would just at certain tick intervals, throw the event because it is day or it is night
or full mc day completed one of those
I mean the server already keeps track of that so not like much needs to be added except that an event gets thrown lol
Yeah full day competed should be easy
since the day/night cycle is pretty regular it would just be a handed utility in the server you could use instead of scheduling stuff
since that event would happen at regular intervals that would be predictable ๐
Annoyingly an issue if too much memory is taken up.
might help to use the api method that lets you get the time in MC
could be implemented in the server where you might need to inject into
guess I could just half-ass it and wait for the maybe eventual PR that's like Yo, fix this shit
lol
Timer wouldn't really be useful in this case, unless it can be re-ran but at that point it's just a scheduled executor lol
Use ZonedDateTime class to handle Time Zone specific calculation including Daylight Saving issues.
ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times. For example, the value "2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris time-zone" can be stored in a ZonedDateTime.
I know what it is for. Just don't think time zone matters, unless this is something the user can schedule?
Might allow it
if this isn't something the user schedules then the time is always local to the application
Kinda need something that works first before allowing it to be configurable..
Guess I could also just reset the list of active events every day, regardless of if there's one running or not lol
Can't really think of a better method xD
with something like this, I would probably just utilize the OS
linux already has a system in place for such things
windows does too but a bit more pain to access
setup a cron job while the application is alive, if its shutting down remove the cron job
Cool, doesn't deal with the java code...
I'm pretty sure you forgot that part when writing that response
I didn't forget about cron jobs lol
most people just want something in code so I generally provide to facilitate that
cron jobs don't run java code afaik ๐
personally I am all for dropping out of java if there is something better while also being able to use it from java
not directly no
but you can make use of unix sockets however which both can access
for old java versions similar thing would be using memory mapped file to communicate with each other
with unix socket you are always listening for input
cron job sends input, voila you now do something
...so...an even hackier way
it isn't an hack
Compared to pure java ways yes
don't see why it would need to be pure java
just because you drop out of a language doesn't mean it is a hack
cron just invokes commands at specidied times, which can include bash scripts
bash supports using utilities to connect via a socket even unix ones
java supports unix sockets since Java 17
there is no hack in that, you didn't change how either of them work
all I did was identified a medium in which both could communicate with each other
and there is 2
unix sockets or memory mapped files
which memory mapped files are actually designed to be used by more then just the process that created it
(of a piece of computer code) that provides a quick but often badly designed solution to a problem, allowing the user to continue working until a better solution can be provided. It's just a hacky workaround.
I don't see how it is badly designed
cron jobs are native to linux, its like saying lets not use cruise control in a car because you can just push the gas yourself
all temporary workarounds just become permanent at some point
I'd have to do extra work to support windows, and it means I'd have to test on both OS's
it doesn't need to be temporary, cron job is built into linux, specifically designed to do something at a specified time
in this case all you need it to do, is just tell the java process hey do something
hey guys, i m trying to make a plugin which checks the version of all plugins in the server, what my current system is the user enters all the resource IDs into the plugin.yml and then execute the cmd /versionChecker checkYML and that loops through all the resource IDs, gets their latest version, their name, now the problem is, how can I get the version isntalled on the server using the plugin's name
Spiget
Dude, I'd still have to make sure both work properly and properly implemented. This means checking the OS, figuring out how to do this mess with both windows & linux, and other dumb shit like macos. A lot of work just for something that should be simple
on linux it is super easy
if you know how to use bash you can use cron jobs
not hard to communicate from bash to a socket
Yea i am using that, but now I need to get the version I have installed on the server
Even then I'm still stuck massively overcomplicating something that should be simple
its not complicated o.O
I suppose its complicated if you don't know how sockets work
or if you never messed with memory mapped files
dude... compared to an executor it is complicated
I'm not too sure why you think this is easier than two runnables
lol
well you are the one that wants to have this runnable hanging around consuming resources doing nothing
I would never use something like that
Sockets and having to do per-os support isn't any better ๐
I also tried PluginManager#getPlugin but that gave me a NullPointer
both windows and linux support scheduled events natively
they have them built in, the OS routinely already checks them
This is still something I'd have to implement different per-os, and have a socket constantly open among other dumb stuff for something that could be simple
not overengineered
unix socket
this is something implemented in many programs
where they use unix socket or memory mapped file for timed events
from the OS
anyways, its your application ๐
not that I use it anyways, just this is the primary reason I don't use other people's stuff as well. I wouldn't bother holding an object for something that will happen 1 year from now
it is just a waste
you have the OS that already checks the scedule/tasks and it probably will do it more efficiently then the JVM itself
and you are not wasting space with a useless object for however long
You could say the same for your idea, since the socket would have to be running all the time.
what resources does that socket use?
do you know?
unix socket uses up just a file descriptor
Still needs some way to interact with java ๐
unix sockets are implemented into Java
Cool, so a useless object that'll only be used a small amount of time
and even if I were to implement it, I'd still have to do a windows equivalent. This doubles the amount of testing I have to do, even more so if I expand on functionality
Can you show code?
so shockingly memory will be wasted either way
shrug not finished or public yet, so I'm not surprised
you don't need persistent objects to make a cron job
Yes gimme a sec
but like I said it is your thing
I'd still have to have persistent objects java side I'm sure
for making a cron job?
sender.sendMessage("Starting Search");
ArrayList<String> resources = (ArrayList<String>) getConfig().getList("versionID.versionList");
for (String s : resources) {
JSONObject info = getInfo(s);
if(info.containsKey("code")){
sender.sendMessage("Error: " + info.toString());
return false;
}
String latestVersion = info.get("current_version").toString();
String currentVersion = getInstalledVersion(info.get("title").toString());
if (latestVersion != currentVersion) {
sender.sendMessage(ChatColor.GOLD + info.get("title").toString() + " " +
ChatColor.GREEN + latestVersion + " | " +
ChatColor.RED + currentVersion);
sender.sendMessage(ChatColor.GOLD + info.get("title").toString() + " Link: " + getPluginLink(s));
} else {
sender.sendMessage(ChatColor.GOLD + info.get("title").toString() + " " +
ChatColor.GREEN + latestVersion + " | " +
ChatColor.GREEN + currentVersion);
}
}
handling them java side
public JSONObject getInfo(String resourceId) {
try {
String sURL = "https://api.spigotmc.org/simple/0.1/index.php?action=getResource&id=" + resourceId;
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
JSONParser jp = new JSONParser();
JSONObject root = (JSONObject) jp.parse(new InputStreamReader((InputStream) request.getContent()));
return root;
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
public String getInstalledVersion(String name) {
return Bukkit.getPluginManager().getPlugin(name).getDescription().getVersion();
}
public String getPluginLink(String resourceId) {
try {
String sURL = "https://api.spiget.org/v2/resources/" + resourceId;
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
JSONParser jp = new JSONParser();
JSONObject root = (JSONObject) jp.parse(new InputStreamReader((InputStream) request.getContent()));
return ((JSONObject) root.get("file")).get("externalUrl").toString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
well, not sure why you would be worried about it. You want everything pure java
when not all problems have to be solved with pure java
Maybe because that's easier than having to add support for two different operating systems and having to deal with the mess that comes with that?
Yeah ^
hey guys do u mind moving to #general or dms?
this still applies to my question actually lol
just focus on ur convo smh
I could do it, but then I have to make it work with multiple events that may or may not be the same day every year for both operating systems.
Not only doubling the amount of code needed, but the amount of testing too.
ok i am sorry
or do a thread, those exist as well
that could go for both of u
Eh, bit late now. Too much of it wouldn't be able to be moved to a thread
Too much context lost at this point I'm afraid
How are you getting the resourceid's?
also kinda off-topic but wtf URLConnection#getContent? why not just like getInputStream, or is that introduced by HttpsURLConnection instead
through the plugin.yml
ids: [9089,....]
and tbf @buoyant viper didn't think it was going to be this long of a convo.
idk found that as the first result, I thought of trying HTTPClient but too lazy ๐ญ
yes
unix socket works exactly the same on windows as it does on linux, scheduling events hasn't changed in windows or linux
Even then, I'd still have a complete mess for the first half of that message.
what mess?
I have to make it work with multiple events that may or may not be the same day every year
This of course doesn't even take into account the possibility of there being events that last longer than a day
they haven't changed
not sure how to say that more simpler
one year from now, odds are they still won't change
even in linux
That does not have anything to do with the part I quoted
I would just loop the plugins and put them on a hashmap (name,version) then get the create connections to get the "latest version" and compare that to the ones in the hashmap.
Most likely the better option.
You can even loop them and get the version from the plugin description
Assuming that last part wasn't hinted at lol
though tbf I still have people that manage to miss big red text, so who knows anymore ๐คทโโ๏ธ
I was not :p I'm not that familiar with spigot/bukkit api.
plugin.getDescription().getVersion()
better yet, do this and instead just grab the plugin.ymls as resources, this would grab plugins that haven't been loaded at all or in the rare occasion a lib ๐
proper spigot/bukkit libs don't get loaded
at least I don't recall they do ๐ค anyways proper libs extend BasePlugin instead of JavaPlugin
for those curious
A lot get loaded as plugins actually, e.g CMI's CMILib
even something like vault gets loaded as a plugin lol
Vault does a lot though that would require being such
of course, however it's still a proper lib ๐
I get sad with my lib on the limitations of not being a plugin.
Make it a plugin then lol
just risk getting called not a proper lib by frost
lol
Then I'd have to add it to the plugins folder
that's a lot of work
but the freedom ๐
proper libs don't do anything on their own
library is different from an API
some libraries do have to load spigot stuff though ๐
yes and they can when a plugin needs it
said plugin would grab an instance of the library which then allows it to do such
or they just be a plugin and load that stuff on load that way a plugin isn't waiting for that to all be initalized
Meh
There is a reason BasePlugin exists still, and its for those libraries that don't require to do anything until something needs it
mostly for utility purposes
What's BasePlugin
As the name implies, it is the Base for making a plugin
If I can't solve it with reflection I'll make it an actual plugin
the bare minimum required
Something outside of spigots api?
no
Why is it not in the javadocs then
It is
?jd-s
Ah, PluginBase
or be a plugin and not have to deal with reflection lol
declaration: package: org.bukkit.plugin, class: PluginBase
yeah sorry
I was saying it backwards
Yeah np
My library is about automating the boring stuff with reflection. Command registration? Listener registration? Dependency injection? Check check check
Using java methods that would get it labeled as a virus on the spigot site? Check
:p
guys how would you get doors from PlayerInteractEvent and then opening/closing it?
How much would I be willing to bet the first google result has an answer to this. Hmmmm
I googled it already bruh
The code I found on google doesn't work either
I'm not new to spigot, I always take a look on google before requesting help here
I am trying to show a player an armor stand via packets, but my ide keeps saying Cannot resolve symbol 'PacketPlayOutSpawnEntityLiving'
The getClickedBlock is null?
have u imported nms?
idk which class to import
what version are u on
how are u importing spigot
native api support for per-player entities when?
maven?

gradle dsl
have u imported the minecraft dependency
Cancel Event
Get clicked Block
Get BlockState
Cast to openable
Set Open to value
Apply BlockState
Do the same with the other Dior block
using that weird paper thing
or just the spigot
yea
oh
because that has the packets
i should import that then
oke
thanks!
np
thats air then
no, i made sure i rightclicked the door
gives me an error when i try to cast the clicked block to a Door
You might have been to far away
yeah
What is the Error?
want the full error?
Yes
Ideally yes, but the top Line suffices
My guess ist that you casted the Block to an openable, which Resultat in a CCE
Forgot to
Door door = (Door) event.getBlock().getBlockData()
Yep, you did that
Just went to cast the block to a door
ok , so i should get the door in this way?
and then use BlockState?
yes, because then its a matter of doing door.setOpen(boolean);
Beware to apply it though
And updating the block
^
Alr, ty guys
I wonder if mc still has a problem with door halves
They still have
I do recall there sometimes being some weird bugs with doors requiring to set the halves XD
You need to cast to bisected and get the other half that way
well at least there is a way to resolve that then if such issue is encountered
Doors, beds and double chests in code are โค๏ธ๐
(technically door extends bisected so the cast is Not need, but eh)
I don't think that there will ever be a Block larger than a block
hmmm
Not vanilla anyways 
It probably gets stacked as two
just starts a new snow block pretty sure
Otherwise breaking the top layer would Break all layers
Door door = (Door) e.getClickedBlock().getBlockData();
door.setOpen(true);
e.getClickedBlock().setBlockData(door);
does the block get updated like this?
(I'm sorry that i'm not formatting the code correctly but EU keybard doesn't have those weird apostrophes)
Door door = (Door) e.getClickedBlock().getBlockData();
door.setOpen(true);
BlockState state = e.getClickedBlock().getState();
state.update(); ```
like this?
``
```java
code here
```
What keyboard doesn't have a backtick 
mine
that specific key is called a tilde
almost looks like there is a second key
in the top left
by that backslash
but I can't tell because of how dark pic is XD
If you have numlock on use alt+96
or do what some sane programmers do, keep a list of special characters in a file ๐

i just did that
anyway is this how to update the block?