Giving a player an item (minecraft plugin) - plugins

my code is
package me.Doloro.FerretSBPlugin;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class YourMistakesHelpMe {
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("bruh")) {
Player player = (Player) sender;
player.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD));
sender.sendMessage(org.bukkit.ChatColor.BLUE + "Check Your Inventory");
return true;
} //If this has happened the function will return true.
// If this hasn't happened the value of false will be returned.
return false;
}
}
I want to to give a Diamond_Sword when the command is typed
there is no error only a {player} has used the command /bruh
, Also I am new to coding this so any help would help me a LOT

So it might be because you forgot the "implements CommandExecutor" after "public class YourMistakesHelpMe". I can't check it rn but idk why it wouldn't work.
package me.Doloro.FerretSBPlugin;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class YourMistakesHelpMe implements CommandExecutor {
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("bruh")) {
Player player = (Player) sender;
player.getInventory().addItem(new ItemStack(Material.DIAMOND_SWORD));
sender.sendMessage(org.bukkit.ChatColor.BLUE + "Check Your Inventory");
return true;
} //If this has happened the function will return true.
// If this hasn't happened the value of false will be returned.
return false;
}
}

Related

Costum Event Handling

I issue I am trying to get rid off is the following:
I intend to setup a costum event handling chain as a workaround for JavaFX's lack of actioncommands.
The issue in particular is, that a menuitem upon clicking it, still fires an ActionEvent instead of the self-written MilvaLabActionEvent.
The code:
Event class
package jpt.gui.items;
import javafx.event.ActionEvent;
public class MilvaLabActionEvent extends ActionEvent {
private static final long serialVersionUID = 6757067652205246280L;
private String actionCommand ="";
public MilvaLabActionEvent(String actionCommand2) {
setActionCommand(actionCommand2);
}
public MilvaLabActionEvent() {}
public String getActionCommand() {
return actionCommand;
}
public void setActionCommand(String actioncommand) {
this.actionCommand = actioncommand;
}
}
My EventHandler:
package jpt.gui.items;
import javafx.event.EventHandler;
import jpt.MilvaLabGlobal;
import jpt.MilvaLabKonst;
import jpt.handle.MilvaLabDateiHandle;
import jpt.handle.MilvaLabEinHandle;
import jpt.handle.MilvaLabHilfeHandle;
import jpt.handle.MilvaLabMilvaHandle;
import jpt.handle.MilvaLabRvAnwendungHandle;
import jpt.handle.MilvaLabrvTextHandle;
import jpt.log4j.MilvaLabLogger;
public class MilvaLabEventHandler implements EventHandler<MilvaLabActionEvent>{
#Override
public void handle(MilvaLabActionEvent event) {
// the command string of the menu item
final String sCmd = event.getActionCommand();
if (sCmd.charAt(0) == 'M')
{//doing something here
}
}
The costum MenuItem-Class I figured out I gotta write.
package jpt.gui.items;
import javafx.event.Event;
import javafx.scene.control.MenuItem;
public class MilvaLabMenuItem extends MenuItem {
private String actionCommand;
public MilvaLabMenuItem(String sText) {
this.setText(sText);
}
#Override
public void fire() {
Event.fireEvent(this, new MilvaLabActionEvent(getActionCommand()));
}
public String getActionCommand() {
return actionCommand;
}
public void setActionCommand(String actionCommand) {
this.actionCommand = actionCommand;
}
}
And the initialization of the costum MenuItem:
final MilvaLabMenuItem jmi = new MilvaLabMenuItem("I am a menuItem");
jmi.addEventHandler(evtype, new MilvaLabEventHandler());
jmi.setOnAction((event) -> {
System.out.print("I have fired an ActionEvent!");
});
Well, as of now, I got "I have fired an ActionEvent" when I click on the MilvaLabMenuItem, nothing else happens. (Looked into that thing already using the debugger).
What I want to happen is that, obviously, the MilvaLabEventHandler is called.
I figured it out again.
I declared two EventTypes, though, only one was necessary.
This helped me finding the solution, though, they use Nodes instead of MenuItems.
How to emit and handle custom events?

Bukkit Plugin: Listener in the main class

I'm trying to make a plugin where you type the command /settings and it toggles the boolean set. If set is true, I want it so when players join it says 'hi' to them but if it's 'false' it does nothing. (Btw im the only one who can use the command). I tried making two classes, one the main and the second the listener, But I couldn't access the boolean from the listener class so I tried making it all in one class. When using the code I've provided, everything works except for the PlayerJoinEvent. I either need to work out how to access the boolean from another class or how to fix this.
package me.jakegeyer28;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Main extends JavaPlugin implements Listener{
public boolean set = true;
#Override
public void onEnable() {
getLogger().info("Done");
}
#Override
public void onDisable() {
getLogger().info("Done");
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("settings")) {
Player player = (Player) sender;
if (player.getName().equalsIgnoreCase("jakegeyer27")) {
if(set == true) {
set = false;
player.sendMessage(ChatColor.RED + "Off");
}
else if (set == false) {
set = true;
player.sendMessage(ChatColor.GREEN + "On");
}
}
return true;
}
return false;
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
if (set == true) {
player.sendMessage("hi");
}
}
}
Thanks
It seems that you haven't registered your listener. Even though the listener is your main class you still need to register it in your onEnable method with this.getServer().getPluginManager().registerEvents(this, this);.

The operator - under defined for the arguement type(s) EditText, int

Im trying to create an activity which adds name, age, and maxhr to sqlite and will be displayed in a listview in Eclipse. name and age is an input text. Maxhr is age(input text) minus 220. But im getting "The operator - under defined for the arguement type(s) EditText, int" error. I can't seem to find the answer for this error. Does anyone know how to fix it?
package com.heartrate.monitoring.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.heartratemonitoringapp.R;
import com.heartrate.monitoring.dao.UserDAO;
import com.heartrate.monitoring.model.User;
public class AddUserActivity extends Activity implements OnClickListener {
public static final String TAG = "AddUserActivity";
private EditText mTxtName;
private EditText mTxtAge;
private Button mBtnAdd;
private UserDAO mUserDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
getActionBar().setDisplayHomeAsUpEnabled(true);
initViews();
this.mUserDao = new UserDAO(this);
}
private void initViews() {
this.mTxtName = (EditText) findViewById(R.id.txt_name);
this.mTxtAge = (EditText) findViewById(R.id.txt_age);
this.mBtnAdd = (Button) findViewById(R.id.btn_add);
this.mBtnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Editable name = mTxtName.getText();
Editable age = mTxtAge.getText();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)){
// add the user to database
double mhr;
double maxhr;
mhr = Double.parseDouble(mTxtAge.getText().toString());;
maxhr = mhr - 220;
User createdUser = mUserDao.createUser(
name.toString(), age.toString(),
maxhr.toString());
Log.d(TAG, "added user : "+ createdUser.getName());
Intent intent = new Intent();
intent.putExtra(ListUserActivity.EXTRA_ADDED_USER, createdUser);
setResult(RESULT_OK, intent);
Toast.makeText(this, R.string.user_created_successfully, Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mUserDao.close();
}
}
Remove the extra ; on this line: mhr = Double.parseDouble(mTxtAge.getText().toString());;

Eclipse 4 RCP - application does not have active window

I want to have some helper functions for manipulating UI.
I don't want to pass to them any parameters except what is necessary by my domain model (i don't want to pass EModelService, EPartService etc.)
Question: The problem is i am getting exception application does not have active window.
I found where the problem is.
It happend because i am manipulating parts via EPartService accessed from the application context IWorkbench.getApplication().getContext().get(EPartService.class).
THIS IS IMPORTANT: Currently i am getting that exception when i am trying to modify my UI AFTER i read inputs from dialog. Pleas note that the error does not happened when i am trying to modify the UI just BEFORE i
opened the dialog. Look at the code, i added some comments.
NewFromDirectoryDialog.java
package cz.vutbr.fit.xhriba01.bc.handlers;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import cz.vutbr.fit.xhriba01.bc.BcModel;
import cz.vutbr.fit.xhriba01.bc.resolvers.filesystem.FileSystemResolver;
import cz.vutbr.fit.xhriba01.bc.ui.dialogs.NewFromDirectoryDialog;
import cz.vutbr.fit.xhriba01.bc.ui.UI;
public class NewFromDirectoryHandler {
#Execute
public void execute(MApplication application, EPartService partService, #Named(IServiceConstants.ACTIVE_SHELL) Shell shell) {
FileSystemResolver fsr = new FileSystemResolver("/home/jara/git/cz.vutbr.fit.xhriba01.bc/bc/src",
"/home/jara/git/cz.vutbr.fit.xhriba01.bc/bc/bin");
BcModel.setResolver(fsr);
// THIS CALL IS OK AND EVERYTHING WORKS
UI.changeExplorerView("bc.partdescriptor.filesystemview", fsr);
NewFromDirectoryDialog dialog = new NewFromDirectoryDialog(shell);
dialog.create();
if (dialog.open() == Window.OK) {
String sourceDir = dialog.getSourceDir();
String classDir = dialog.getClassDir();
FileSystemResolver fsr = new FileSystemResolver(classDir, sourceDir);
//THIS CALL LEADS TO EXCEPTION: application does not have active window
UI.changeExplorerView("bc.partdescriptor.filesystemview", fsr);
}
}
}
That EPartService from application context is based on org.eclipse.e4.ui.internal.workbench.ApplicationPartServiceImpl
and not on org.eclipse.e4.ui.internal.workbench.PartServiceImpl
as EPartService instance you get when injected to #PostConstruct annotated method on Part's view.
org.eclipse.e4.ui.internal.workbench.ApplicationPartServiceImpl (not entire source code)
You can see that the error probably happened because at the time ApplicationPartServiceImpl.createPart is called in my UI.changeExplorerView, the Eclipse runtime does not know what window
is currently active.
package org.eclipse.e4.ui.internal.workbench;
import java.util.Collection;
import javax.inject.Inject;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder;
import org.eclipse.e4.ui.model.application.ui.basic.MInputPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.e4.ui.workbench.modeling.IPartListener;
public class ApplicationPartServiceImpl implements EPartService {
private MApplication application;
#Inject
ApplicationPartServiceImpl(MApplication application) {
this.application = application;
}
private EPartService getActiveWindowService() {
IEclipseContext activeWindowContext = application.getContext().getActiveChild();
if (activeWindowContext == null) {
throw new IllegalStateException("Application does not have an active window"); //$NON-NLS-1$
}
EPartService activeWindowPartService = activeWindowContext.get(EPartService.class);
if (activeWindowPartService == null) {
throw new IllegalStateException("Active window context is invalid"); //$NON-NLS-1$
}
if (activeWindowPartService == this) {
throw new IllegalStateException("Application does not have an active window"); //$NON-NLS-1$
}
return activeWindowPartService;
}
#Override
public MPart createPart(String id) {
return getActiveWindowService().createPart(id);
}
}
LifeCycleManager.java (how i initialize the UI helper class)
You can see i am injecting IWorkbench to my UI class.
IWorkbench allows me to access MApplication, so that is all i should
need to modify app UI.
package cz.vutbr.fit.xhriba01.bc;
import javax.inject.Inject;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.UIEvents;
import cz.vutbr.fit.xhriba01.bc.ui.UI;
public class LifeCycleManager {
#Inject
#Optional
private void appCompleted(#UIEventTopic(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE) Object event, IWorkbench workbench) {
ContextInjectionFactory.inject(UI.getDefault(), workbench.getApplication().getContext());
}
}
UI.java
package cz.vutbr.fit.xhriba01.bc.ui;
import javax.inject.Inject;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPartStack;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.e4.ui.workbench.modeling.EPartService.PartState;
import org.eclipse.jface.text.IDocument;
import cz.vutbr.fit.xhriba01.bc.BcModel;
import cz.vutbr.fit.xhriba01.bc.resolvers.ISourceAndClassResolver;
public class UI {
public static final String PART_EXPLORER_ID = "bc.part.inspector";
public static final String PART_EXPLORER_CONTAINER_ID = "bc.partstack.explorer_stack";
public static final String PART_JAVA_SOURCE_VIEWER_ID = "bc.part.javasourceview";
private static UI fInstance = new UI();
#Inject
private IWorkbench fWorkbench;
private UI() {
}
public static void changeExplorerView(String partDescriptorId, ISourceAndClassResolver resolver) {
EModelService modelService = fInstance.fWorkbench.getApplication().getContext().get(EModelService.class);
EPartService partService = fInstance.fWorkbench.getApplication().getContext().get(EPartService.class);
MApplication application = fInstance.fWorkbench.getApplication();
MPart part = partService.createPart(partDescriptorId);
MPart oldPart = partService.findPart(UI.PART_EXPLORER_ID);
MPartStack partStack = (MPartStack) modelService.find(UI.PART_EXPLORER_CONTAINER_ID, application);
partStack.setVisible(true);
if (oldPart != null) {
partService.hidePart(oldPart);
}
part.setElementId(UI.PART_EXPLORER_ID);
partStack.getChildren().add(part);
BcModel.setResolver(resolver);
partService.showPart(part, PartState.VISIBLE);
}
public static UI getDefault() {
return fInstance;
}
public static void setJavaSourceLabel(String label, EPartService partService) {
MPart part = partService.findPart(UI.PART_JAVA_SOURCE_VIEWER_ID);
if (part != null) {
part.setLabel(label);
}
}
public static void setJavaSourceText(String source) {
IDocument document = BcModel.getJavaDocument();
if (document != null) {
document.set(source);
}
}
}
I think the problem is when i open the dialog, the activeChild changes somehow to that new opened dialog and when i close it and try immediately change my UI, it does not work because the activeChild is still not properly setup back. Otherweise i don't know why it works fine just before i opened the dialog and doesn't work just after the dialog is closed.
Does anyone know if it is bug?

Control Netbeans from Commandline: attach Debugger from Shell-script

I'm using a daemon-script which is monitoring a remote server. When the remote server is up, i want that Netbeans automatically connects it's Debugger to the remote Server.
Is it possible to control this behavior from commandline?
To type Something like
netbeans --attach-debugger 192.168.178.34:9009
inside a terminal to do that? Or what other ways do i have to get access to Netbeans-internal stuff? (until now, i was just a "user" of Netbeans so i don't know the internals and how to access them very well)
Or will i have to write a Netbeans Plugin to do that? If yes, can you give me a good starting point to add that functionality?
Ok since there is no option to attach the Debugger from commandline, i wrote a Netbeans Plugin with the help of this blog entry and this thread from the NB-mailinglist. Now i'm able to call my plugin actions from the Commandline.
So build a simple NetBeans Module, which contains 2 important classes.
This is the class which gets the commandline parameters and forwards them to my Action:
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
#ServiceProvider(service = OptionProcessor.class)
public class TriggerActionCommandLine extends OptionProcessor {
//Here we specify "runAction" as the new key in the command,
//but it could be any other string you like, of course:
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "debug");
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
#Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
#Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = (String[]) values.get(action);
if (args.length > 0) {
//Set the value to be the first argument from the command line,
//i.e., this is "GreetAction", for example:
final String ip = args[0];
//Wait until the UI is constructed,
//otherwise you will fail to retrieve your action:
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
#Override
public void run() {
//Then find & perform the action:
Action a = findAction(AttachDebugger.ACTION_NAME);
// forward IP address to Action
ActionEvent e = new ActionEvent(this, 1, ip);
a.actionPerformed(e);
}
});
}
}
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/PSFActions");
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
logger.info(fileObject.getName());
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
return null;
}
}
This is my Plugin Action which attaches the Debugger to the given remote address:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.debugger.jpda.DebuggerStartException;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.python.util.PythonInterpreter;
#ActionID(category = "PSFActions", id = "de.mackaz.AttachDebugger")
#ActionRegistration(displayName = "#CTL_AttachDebuggerAction")
#ActionReferences({
#ActionReference(path = "Menu/Tools", position = 1800, separatorBefore = 1750, separatorAfter = 1850)
})
public final class AttachDebugger implements ActionListener {
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
public static final String ACTION_NAME="AttachDebugger";
#Override
public void actionPerformed(ActionEvent e) {
String ip;
if (!e.getActionCommand().contains("Attach Debugger")) {
ip = e.getActionCommand();
} else {
ip = lookupIP();
}
try {
logger.log(Level.INFO, "Attaching Debugger to IP {0}", ip);
JPDADebugger.attach(
ip,
9009,
new Object[]{null});
} catch (DebuggerStartException ex) {
int msgType = NotifyDescriptor.ERROR_MESSAGE;
String msg = "Failed to connect debugger to remote IP " + ip;
NotifyDescriptor errorDescriptor = new NotifyDescriptor.Message(msg, msgType);
DialogDisplayer.getDefault().notify(errorDescriptor);
}
}
}
Now i can attach the Netbeans debugger to a specific address by calling netbeans/bin/netbeans --debug 192.168.178.79