Minecraft Forge 1.7.10: WorldEvent.load not working? - java

I have an eventhandler class where I am trying to chat a message to the server chat, once it is loaded, however, the WorldEvent.Load never seems to get called! Code:
package com.dropthevase.motdchanger;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraftforge.event.world.WorldEvent;
public class EventHandler {
#SubscribeEvent
public void onLoad(WorldEvent.Load event)
{
System.out.println("testing");
MinecraftServer.getServer().addChatMessage(new ChatComponentText("MOTDChanger started."));
}
}

Related

Import greyed out in Java

I've just started using Java today and have created some tests but I want to use JavascriptExecutor to be able to report tests passing or failing to Sauce Labs. I've imported the library I believe I need but it doesn't recognise the import either way. I believe I am doing it correctly but evidently I'm not and would like some help to understand where I'm going wrong.
My code looks like this:
package tests;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.RegisterExtension;
import pageobjects.Login;
import org.junit.jupiter.api.extension.TestWatcher;
import org.openqa.selenium.JavascriptExecutor;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TestLogin extends BaseTest {
private Login login;
#RegisterExtension
public SauceTestWatcher watcher = new SauceTestWatcher();
#Before
public void setUp() {
login = new Login(driver);
}
#Test
public void succeeded() {
login.with("tomsmith", "SuperSecretPassword!");
assertTrue("success message not present",
login.successMessagePresent());
}
#Test
public void failed() {
login.with("tomsmith", "bad password");
assertTrue("failure message wasn't present after providing bogus credentials",
login.failureMessagePresent());
}
#Test
public void failed2() {
login.with("tomsmith", "bad password");
assertFalse("success message was present after providing bogus credentials",
login.successMessagePresent());
}
public class SauceTestWatcher implements TestWatcher {
#Override
public void testSuccessful(ExtensionContext context) {
driver.executeScript("sauce:job-result=passed");
driver.quit();
}
#Override
public void testFailed(ExtensionContext context, Throwable cause) {
driver.executeScript("sauce:job-result=failed");
driver.quit();
}
}
}
I use import org.openqa.selenium.JavascriptExecutor; to get and I'm referencing it at the bottom: driver.executeScript("sauce:job-result=failed"); or the passed just above it.
Invalidating cache and restarting resolved. Also changed the code slightly.
((JavascriptExecutor) driver).executeScript("sauce:job-result=passed");
This resolved my issue

Cannot make a static reference to the non-static method --- from the type --- Java Bukkit Minecraft

I know there have been plenty of other posts like this from people trying to find their problem in their static class and I have read them but to no avail. I am trying to make a minecraft bukkit plugin for bedwars and when trying to use world.--- I constantly get these errors(Cannot make a static reference to the non-static method getPlayers from the type World) and cannot find where the static class is originating from. Here is my code:
package me.fitch.bedwars.timers;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.World;
import org.bukkit.entity.Player;
import me.fitch.bedwars.main;
public class starttimer implements Listener {
private main plugin;
public starttimer(main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void startjoin(PlayerJoinEvent e)
{
Object [] players = World.getPlayers().toArray(); //error here
if(players.length == 8)
{
//start countdown
}
}
}
Hope you can help and that I'm not just blind
Thanks :)
Edit: after instantiating World server = new World(); I am now getting "Cannot instantiate the type World" errors, thanks for the help so far guys, hope you can help with this :)
Edit 2: so e.getPlayer().getWorld() works now so thanks but I'm now having issues in my main class where e is not a thing
package me.fitch.bedwars;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import me.fitch.bedwars.listeners.beddestroy;
public class main extends JavaPlugin {
private main plugin;
public main(main plugin) {
this.plugin = plugin;
}
#Override
public void onEnable()
{
World.setSpawnLocation(Integer.parseInt( plugin.getConfig().getString("respawn_pointx")), Integer.parseInt( plugin.getConfig().getString("respawn_pointx")) + 1,Integer.parseInt( plugin.getConfig().getString("respawn_pointz")));
new beddestroy(this);
}
}
You will want your listener in its own class myListener.java.
From within the listener events in that class you should be able to do everything you need to do.
I like to create a public static Plugin object in case you ever need to reference the specific instance of the Plugin object from any other class in your plugin.
You will register the listener like this in Main.onEnable()
package myPlugin;
import myPlugin.myListenerClass;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public static Plugin instance;
#Override
public void onEnable() {
instance = this;
PluginManager my_pm = getServer().getPluginManager();
my_pm.registerEvents(new myListenerClass(), this);
}
}
Your myListenerClass.java will be setup something like the following:
package myPlugin;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
public class myListenerClass implements Listener {
#EventHandler
public void onJoin(PlayerJoinEvent event) {
System.out.println("PlayerJoinEvent was triggered!");
int playerCount = Bukkit.getServer().getOnlinePlayers().size();
if (playerCount == 8) {
// start countdown
}
}
}

How to create a cron job in Play Framework

I'm creating a simple cron job that run a task in a specific time (for example 3AM) with Play Framework 2.6.x.
But now I'm stucking in a simple schedule task:
I created an Actor:
package actors;
import akka.actor.UntypedActor;
import org.slf4j.LoggerFactory;
public class DoSomethingActor extends UntypedActor {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(DoSomethingActor.class);
#Override
public void onReceive(final Object message) throws Throwable {
log.info("Write your crone task or simply call your method here that perform your task " + message);
}
}
Then I created a Schedule class that call Actor each time I've set:
package tasks;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import scala.concurrent.duration.Duration;
#Singleton
public class DoSomethingScheduler {
#Inject
public DoSomethingScheduler(final ActorSystem system,
#Named("do-something-actor") final ActorRef doSomethingActor) {
final Cancellable scheduler;
final int timeDelayFromAppStart = 0;
final int timeGapInSeconds = 1; //Here you provide the time delay for every run
system.scheduler().schedule(
Duration.create(timeDelayFromAppStart, TimeUnit.MILLISECONDS), //Initial delay when system start
Duration.create(timeGapInSeconds, TimeUnit.SECONDS), //Frequency delay for next run
doSomethingActor,
"message for onreceive method of doSomethingActor",
system.dispatcher(),
null);
}
}
Finally, I bind these class in a Module class:
package modules;
import actors.DoSomethingActor;
import com.google.inject.AbstractModule;
import play.libs.akka.AkkaGuiceSupport;
import tasks.DoSomethingScheduler;
public class SchedulerModule extends AbstractModule implements AkkaGuiceSupport{
#Override
protected void configure() {
this.bindActor(DoSomethingActor.class, "do-something-actor");
this.bind(DoSomethingScheduler.class).asEagerSingleton();
}
}
After these things, I run the application but it doesn't work as I expected. I expected it shows a logging every 1 SECOND but there is nothing happen.
Could you please help me to fix it?
Thank you so much!
The solution is in dev mode, I have to send a HTTP request to the application to load the module. In production mode, they will be loaded immediately.

ContextStartedEvent not firing in custom listener

I am trying to hook into the creation of the context using a custom application listener like this
#Component
public class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {
#Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("Context started"); // this never happens
}
}
But the onApplicationEvent method never fires. If I use a different event such as ContextRefreshedEvent then it works just fine, but I need to hook into before it is created. Any advice? Thanks!
[Edit]
Editing answer adding more info because of the downvote.
The reason why you are not getting a callback by the listener is because you are not explicitly calling the LifeCycle start() method (JavaDoc).
This cascades down to your ApplicationContext normally via the AbstractApplicationContext on in Spring Boot case via the ConfigurableApplicationContext.
Example of working code below demonstrating how your callback would work (just explicitly call the start() method)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
applicationContext.start();
}
#Component
class ContextStartedListener implements ApplicationListener<ContextStartedEvent> {
#Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("Context started");
}
}
}
The reason why I suggested below the ContextRefreshedEvent callback instead is because behind the scenes the refresh() code is getting invoked.
If you drill down the SpringApplication#run() method you'll eventually see it.
Again here's a working example of how this would work using the ContextRefreshedEvent:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Component
class ContextStartedListener implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("Context refreshed");
}
}
}
[Before Edit]
Change the Generic type to ContextRefreshedEvent instead and then it should work.
For more details read this article from the Spring Blog. Just to quote the part about the ContextRefreshedEvent:
[..]This allows MyListener to be notified when the context has refreshed
and one can use that to run arbitrary code when the application
context has fully started.[..]

Minecraft Bukkit Events

I'm trying to get into bukkit programming for minecraft, but for some reason I'm stuck with events. Here's my code:
Main class file:
package com.plugin1;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
//import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Plugin extends JavaPlugin {
public int songStage;
public static Plugin plugin;
public void OnEnable () {
PluginDescriptionFile pluginDesc = getDescription();
Logger logger = getLogger();
plugin = this;
registerEvents(this, new BlockBreak());
logger.info(pluginDesc.getName() + " is enabled! (V. " + pluginDesc.getVersion() + ")");
}
public void OnDisable () {
PluginDescriptionFile pluginDesc = getDescription();
Logger logger = Logger.getLogger("Plugin");
plugin = null;
logger.info(pluginDesc.getName() + " is disabled! (V. " + pluginDesc.getVersion() + ")");
}
public static void registerEvents(org.bukkit.plugin.Plugin plugin, Listener... listeners) {
for (Listener listener : listeners) {
Bukkit.getServer().getPluginManager().registerEvents(listener, plugin);
}
}
public static Plugin getPlugin() {
return plugin;
}
}
Event class file:
package com.plugin1;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class BlockBreak implements Listener {
#EventHandler(priority = EventPriority.HIGH)
public void OnBlockBreak (BlockBreakEvent e) {
Player p = e.getPlayer();
p.sendMessage("Block broken.");
}
}
Basically, this returns no errors. I've gone through console and there's nothing. When I break a block, literally nothing happens!
I've tried a few of things: I've gone through it, tried multiple video tutorials and tried a text tutorial on the minecraft forums but still nothing. I also contacted a server owner who codes bukkit plugins, but he couldn't fix this...
If there's anyone who can help me with this, PLEASE LET ME KNOW!!!!
Thanks in advance!
Here is a code example to start the server in a process:
package me.Nightfighter001.GlobalSystem.Listener;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import me.Nightfighter001.GlobalSystem.Main.main;
public class Join implements Listener {
public Join(main main) {
plugin = main;
plugin.getServer().getPluginManager().registerEvents(this, main);
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("");
}
main plugin = main.getPlugin();
}
I think you aren't registering the Listeners in the right way...
Try this code and tell me if it works... I'm really wanting to help you
First of all don't use "Plugin" as the name for your Main Class... Use "Main" instead.
Enable:
public class Main extends JavaPlugin {
public void onEnable() {
Bukkit.getPluginManger().registerEvents(new Join(this),this);
}
}
Listener:
public class Join implements Listener {
private Main plugin;
public Join(Main plugin) {
this.plugin = plugin;
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("Just another test");
}
}
Hope it works...
I've tested your code and it really doesn't work. I think your Eventregistration isn't working. For my plugins I use this in the mainClass:
package me.Nightfighter001.GlobalSystem.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import me.Nightfighter001.GlobalSystem.Listener.Join;
public class main extends JavaPlugin {
public static main getPlugin() {
return plugin;
}
private static main plugin;
#Override
public void onEnable() {
plugin = this;
new Join(this);
ConsoleCommandSender console = Bukkit.getConsoleSender();
console.sendMessage(new StringBuilder("\247c[\2476GlobalSystem\247c] \247bVersion \247c")
.append(getDescription().getVersion()).append(" \247bdes Plugins wurde aktiviert!").toString());
console.sendMessage(
"\247c[\2476GlobalSystem\247c] \247bDieses Plugin darf nur benutzt werden, wenn der Entwickler \247cNightfighter001 \247bes erlaubt!");
return;
}
#Override
public void onDisable() {
ConsoleCommandSender console = Bukkit.getConsoleSender();
console.sendMessage(new StringBuilder("\247c[\2476GlobalSystem\247c] \247bVersion \2474")
.append(getDescription().getVersion()).append(" \247bdes Plugins wurde deaktiviert!").toString());
}
}
And in the EventClass:
package me.Nightfighter001.GlobalSystem.Listener;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import me.Nightfighter001.GlobalSystem.Main.main;
public class Join implements Listener {
public Join(main main) {
plugin = main;
plugin.getServer().getPluginManager().registerEvents(this, main);
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent ev) {
ev.setJoinMessage("");
}
main plugin = main.getPlugin();
}
As you can see in my example I use the PlayerJoinEvent, but it also works with the BlockBreakEvent. I hope this helps :) And sorry for my bad English ;D
Your code will work if you don't capitalize the names of the onEnable (and onDisable) methods. onEnable and OnEnable are two different methods since java is case sensitive, and since you're trying to override specific methods in the JavaPlugin super class, you'll need to spell them the exact same way.
Common convention is, as far as I know, that you start your methods with lowercase letters anyway though. The #Override annotation is very useful in catching these kinds of bugs, because it lets the compiler know that you mean to override an existing method, and if that method doesn't exist (for example if you misspelled the name or added different parameters), it will alert you (it also lets anyone reading the code immediately know you're overriding an existing method or implementing an interface).

Categories