How to fire events using Bukkit API? - java

I was looking at how to create and fire events using Bukkit API.
public class PlayerDisconnect implements Listener {
#EventHandler
public void onQuit(PlayerQuitEvent event){
//code
}
}
I mean, doesn't matter the name of the method (in this case onQuit, I can use onDisconnect, onLeave, etc. and it will still be called by PlayerQuitEvent), it calls every method using PlayerQuitEvent as a parameter. I want to be able to replicate that behaviour.

You can create and call your own custom events using the Bukkit Event API. Spigot has a good starting tutorial on the Event API.
A simple example of a Cancellable event that takes a Player:
...
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class MyCustomEvent extends Event implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
private final Player player;
private boolean cancelled;
public MyCustomEvent(Player player)
{
this.player = player;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public Player getPlayer()
{
return this.player;
}
public HandlerList getHandlers()
{
return handlers;
}
#Override
public boolean isCancelled()
{
return cancelled;
}
#Override
public void setCancelled(boolean cancelled)
{
this.cancelled = cancelled;
}
}
Which you can then call elsewhere in your custom event like so
...
MyCustomEvent event = new MyCustomEvent(player);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
return;
...
Finally, you would listen for the event like you would any other event:
...
#EventHandler
public void onMyCustomEvent(MyCustomEvent event){
Player player = event.getPlayer();
...
}

You should use PluginManager#callEvent(Event).
public class CustomEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final String a;
private final int b;
private boolean cancelled;
public CustomEvent(String a, int b) {
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public int getB() {
return b;
}
#Override
public boolean isCancelled() {
return cancelled;
}
#Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
#Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
CustomEvent event = new CustomEvent("some data", 5);
Server server = ...
server.getPluginManager().callEvent(event);
if (event.isCancelled()) return;
// Do event
See the official tutorial and this community tutorial.
If you want to use the Bukkit event system in a non-Bukkit plugin project, you can add the Bukkit API as dependency (just the API, not the server implementing it).

Related

Persist RxJava calls between activities using Dagger2

I have a BehaviorRelay object in ExecutionStream class which handles network calls. Please refer to ExecutionStream class.
I can call requestTrackingAndExecution() method from any activity. I have implemented Dagger2 dependency such that I can inject ExecutionStream instance in any activity.
My dagger2 configuration:
#PerApplication
#Provides
public ExecutionStream provideExecutionStream(PmsApi pmsApi) {
return new ExecutionStream(pmsApi);
}
#PerApplication annotation
#Scope
#Retention(RUNTIME)
public #interface PerApplication { }
WHAT I NEED TO DO:
I want to call requestTrackingAndExecution() method from Activity A and subscribe to its emitted data in Activity B.
Currently, suubscriber in Activity B is not getting any data emitted from activity A<--- SEE HERE
I have injected ExecutionStream class in both activities like #Inject ExecutionStream executionStream;
For emitting observable, I am calling internshipAndTrackingRelay.accept(data); in requestTrackingAndExecution() method after getting data from a network call.
Code for subscribing to relay:
executionStream.internshipAndTracking()
.subscribe(
new Consumer<ExecutionStream.InternshipAndTrackingContainer>() {
#Override
public void accept(ResponseData data){
//do some stuff with responsedata
}
});
My ExecutionStream class:
public class ExecutionStream {
#NonNull private PmsApi pmsApi;
#NonNull private final BehaviorRelay<InternExecutionContainer> internExecutionRelay = BehaviorRelay.create();
#NonNull private final BehaviorRelay<InternshipAndTrackingContainer> internshipAndTrackingRelay = BehaviorRelay.create();
public ExecutionStream(#NonNull PmsApi pmsApi) {
this.pmsApi = pmsApi;
}
#NonNull
public Observable<InternshipAndTrackingContainer> internshipAndTracking() {
return internshipAndTrackingRelay.hide();
}
public void requestTrackingAndExecution(String internshipExecutionId, String internExecutionId) {
// Do some network call
// Get response
internshipAndTrackingRelay.accept(new InternshipAndTrackingContainer(responseData));
}
});
}
/**
* This function returns combined response of both apis
* This returns when both apis are finished calling
* #return Observable response
*/
private BiFunction<
InternshipExecutionResponse,
TrackingDataResponse,
TrackingAndExecution>
getMergingBiFuntionForTrackingAndExecution() {
return new BiFunction<InternshipExecutionResponse, TrackingDataResponse, TrackingAndExecution>() {
#Override
public TrackingAndExecution apply(#io.reactivex.annotations.NonNull InternshipExecutionResponse internshipExecutionResponse, #io.reactivex.annotations.NonNull TrackingDataResponse trackingDataResponse) throws Exception {
return new TrackingAndExecution(internshipExecutionResponse,trackingDataResponse);
}
};
}
public class InternshipAndTrackingContainer {
public boolean isError;
public boolean isEmpty;
public TrackingAndExecution trackingAndExecution;
public InternshipAndTrackingContainer() {
this.isError = true;
this.trackingAndExecution = null;
this.isEmpty = false;
}
public InternshipAndTrackingContainer(TrackingAndExecution trackingAndExecution) {
this.trackingAndExecution = trackingAndExecution;
this.isError = false;
this.isEmpty = false;
}
public InternshipAndTrackingContainer(boolean isEmpty) {
this.trackingAndExecution = null;
this.isError = false;
this.isEmpty = isEmpty;
}
}
}
Finally found a solution.
I was reinitializing my ApplicationModule again and again.
Changed this:
public ApplicationComponent getComponent() {
ApplicationComponent component = DaggerApplicationComponent.builder()
.networkModule(new NetworkModule())
.ApplicationModule(new ApplicationModule(this))
.build();
return component;
}
To this:
public synchronized ApplicationComponent getComponent() {
if(component == null) {
component = DaggerApplicationComponent.builder()
.networkModule(new NetworkModule())
.ApplicationModule(new ApplicationModule(this))
.build();
}
return component;
}
Does Activity B subscribe to the internshipAndTrackingRelay before Activity A runs the requestTrackingAndExecution() method?

Return a value after thread finish its work

I tried to implement Observer pattern in java with threads. What I am trying to do is return a value from the new thread.
In this question, someone recommend to use Observer pattern and I want to use it.
I have the following code:
/*Observable*/
public class QRExplorer extends Observable implements Runnable {
private String md5;
public String getMD5()
{
return md5;
}
private void setMD5(String value)
{
this.md5 = value;
setChanged();
notifyObservers();
}
#Override
public void run() {
// do some stuff
// here I should obtain a string and I want return that
setMD5("value");
}
}
/*Observer*/
public class Observador implements Observer {
private QRExplorer observado = null;
public Observador(QRExplorer observado)
{
this.observado = observado;
}
#Override
public void update(Observable o, Object arg) {
if(o == observado)
{
System.out.println("Something has changed ¬¬: "+observado.getMD5());
}
}
}
/*Principal class*/
public class MainView extends javax.swing.JFrame implements ThreadFactory{
private RKeyListener listener;
private Webcam camara;
private Executor creador = Executors.newSingleThreadExecutor(this);
private Observador observador;
private QRExplorer explorer;
/*Nothing relevant*/
private void pCamaraMouseClicked(java.awt.event.MouseEvent evt) {
creador.execute(explorer);
}
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
Observable obs = (Observable)t;// but Netbeans tells me: incompatible types: Thead cannot be converted to Observable
obs.addObserver(observador);
return t;
}
}
Try
#Override
public Thread newThread(Runnable r) {
explorer = new QRExplorer(); // extends Observable
observador = new Observador(explorer); //implements Observer
explorer.addObserver(observador);
Thread t = new Thread(r);
return t;
}

Java using akka to publish commands to server

I'm new with akka, so want to ask how to add event to event bus and catch it called. There is code sample.
localEventBus = new com.google.common.eventbus.EventBus(new ExceptionHandler());
Object listener = new Object()
{
#Subscribe
public void witingCommand(SomeCommand cmd)
{
//Here I want to catch call
}
};
...
localEventBus.register(listener);
...
client = system.actorOf(Props.create(ClientActor.class, localEventBus, receptionists));
...
client.tell(new Publish(Constants.COMMAND, someCommand), noSender());
Types:
private final ActorSystem system;
private ActorRef client;
ClientActor.java
final class ClientActor extends UntypedActor
{
ClientActor(final EventBus eventBus, final List<ActorSelection> receptionists)
{
localEventBus = eventBus;
clusterReceptionists.addAll(receptionists);
}
#Override
public void preStart()
{...}
#Override
public void postStop()
{...}
#Override
public void onReceive(final Object msg)
{...}
}
Problem is that 'witingCommand' is not being called, maybe someone can tell me what I do wrong?

Java Event Listener to detect a variable change

I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?
Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events
Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.
public class MyClassWithText {
protected PropertyChangeSupport propertyChangeSupport;
private String text;
public MyClassWithText () {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void setText(String text) {
String oldText = this.text;
this.text = text;
propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class MyTextListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("MyTextProperty")) {
System.out.println(event.getNewValue().toString());
}
}
}
public class MyTextTest {
public static void main(String[] args) {
MyClassWithText interestingText = new MyClassWithText();
MyTextListener listener = new MyTextListener();
interestingText.addPropertyChangeListener(listener);
interestingText.setText("FRIST!");
interestingText.setText("it's more like when you take a car, and you...");
}
}
Just like you need to create an event listener, you will also need to create the event firer -- since there is nothing automatic that will do this for you. I've provided sample code that shows you how to implement such a firer.
This test implementation isn't perfect. It only includes a way to add listeners. You may wish to include a way to remove listeners who are no longer interested in receiving events. Also note that this class is not thread-safe.
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class BooleanChangeTest implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() {
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
BooleanChangeTest test = new BooleanChangeTest(false);
test.addBooleanChangeListener(listener);
test.setFlag(false); // no change, no event dispatch
test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public BooleanChangeTest(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
you can also try to implement an Observer.
First create the observable object:
import java.util.Observable;
public class StringObservable extends Observable {
private String name;
public StringObservable(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
}
Then the observer:
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String) arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}
And in your main (or wherever else):
public class TestObservers {
public static void main(String args[]) {
// Create the Subject and Observers.
StringObservable s = new StringObservable("Test");
NameObserver nameObs = new NameObserver();
// Add the Observer
s.addObserver(nameObs);
// Make changes to the Subject.
s.setName("Test1");
s.setName("Test2");
}
}
Mostly found here
Very late to answer, but this is a problem that can be solved with Observer/Observable. Example
The boolean you are setting should be allowed to do only through a setter method like:
public void setFlag(boolean flag){
//Method code goes here
}
Now in now set method, you can decide based on what value comes in, what event needs to be fired. I am explaining in simple terms without introducing complex terms so you can understand better, so code snippet would look like:
public void setFlag(boolean flag){
//if flag is TRUE do something
//If flag is FALSE then do something
//And finally do what you needed to do with flag
}
Ask questions if you need more info
you create a listener when you want to listen for I/O changes. mostly on graphics.
the answer to your question is to keep state of the running program, then check if variables change from the state inside the infinite loop of your program.
You can use AOP for that, perhaps AspectJ? Check a few examples here (if you use Eclipse, then using AspectJ is really simple with their plugin).
For you, you would have a pointcut similar to the one used in the SampleAspect, but one that will only be used when someone makes a new SET to a boolean variable (this doesn't mean that the value has changed, just that someone loaded a value to the variable).

Detecting a change in an integer

Is there any way to detect change in an integer? Such as creating a listener to listen to the integer to detect and change in value it has. I know this is possible with booleans with a few tricks but I cannot seem to adapt this to an int value. Does anyone have any idea how this could be done? I need to know how to do this in the Java language. Below is code that I found online that allows for a boolean listener. How can I convert this to an integer listener?
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
//can u see this austin? can u see this i typed this at 9:33 my time
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class test1 implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() { // add this to the class
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
test1 test = new test1(false);
test.addBooleanChangeListener(listener);
// test.setFlag(false); // no change, no event dispatch
// test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public test1(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
I would create a class capable of registering listeners. Below is a mocked up example. It might even compile as is (assuming you write the corresponding VocalIntegerListener interface exists and is implemented somehow... it's pretty simple).
class VocalInteger {
private int value;
private final Object lock = new Object();
Set<VocalIntegerListener> listeners; // assume interface exists - it's easy
public VocalInteger() {
this(0);
}
public VocalInteger(int value) {
this.value = value;
listeners = new HashSet<VocalIntegerListener>();
}
public int getValue() {
return value;
}
public void setValue(int value) {
synchronized(lock) {
int oldValue = this.value;
this.value = value;
for(VocalIntegerListener listener : listeners) {
listener.fireChangedEvent(oldvalue, value); // assume exists
}
}
}
public void registerListener(VocalIntegerListener listener) {
synchronized(lock) {
listeners.add(listener);
}
}
}
Have a look at "Java Beans" and "bound properties" for the standard approach how to listen for property changed events:
http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html
http://docs.oracle.com/javase/tutorial/javabeans/

Categories