Bukkit plugin Syntax error, multiple classes - java

i'm trying to create plugin with multiple classes, but when I type the command in Minecraft, it shows me command syntax error msg (Syntax error! Simply type /ct create.). I think it is silly misstake somewhere, but i can't find it.
My core.java:
public class Core extends JavaPlugin {
public ArrayList<Block> chests = new ArrayList<>();
public boolean createMode = false;
public void onEnabled() {
getCommand("ct").setExecutor(new Commands(this));
getServer().getPluginManager().registerEvents(new Listeners(this), this);
}
}
My Commands.java:
public class Commands implements CommandExecutor {
private Core plugin;
public Commands(Core core) {
this.plugin = core;
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("ct")) {
sender.sendMessage("lol");
if(args.length > 0) {
sender.sendMessage("hi");
if(args[0].equalsIgnoreCase("create")) {
plugin.createMode = true;
sender.sendMessage(ChatColor.GOLD + "[ChestTreasure] " + ChatColor.RESET + "Now rightclick the chest");
}
} else {
sender.sendMessage(ChatColor.GOLD + "[ChestTreasure] " + ChatColor.RESET + "Too few arguments!");
}
}
return false;
}
}
My plugin.yml:
name: ChestTreasure
description: this plugin...
main: me.sudoman281.chestTreasure.Core
version: 1.0
author: sudoman281
commands:
ct:
description: ...
permission: ct.create
usage: Syntax error! Simply type /ct create.

You have to correctly override the method by having the same exact name and method signature/return type. To do this you must do the following:
Your onEnabled method should be onEnable per the Bukkit API
You should always use the #Override annotation to signify that you are overriding a superclass method. (Optional but highly recommended for finding errors and convention. It will work without this)
Your onEnable should look like this:
#Override
public void onEnable() {
/* Do stuff when plugin starts */
}

Related

printf error can't launch java eclipse

My printf contains an error. The rest of my code is done, but because of the error in my printf, I can't launch Java. Please help. My main class already done.
package id.web.aditya;
public class Roda {
private int diameter;
private String warna;
private String Merk;
private String Keterangan;
public String getMerk() {
return Merk;
}
public void setMerk(String merk) {
Merk = merk;
}
public int getDiameter() {
return diameter;
}
public void setDiameter(int diameter) {
this.diameter = diameter;
}
public String getWarna() {
return warna;
}
public void setWarna(String warna) {
this.warna = warna;
}
public String getKeterangan() {
return Keterangan;
}
public void setKeterangan(String keterangan) {
this.Keterangan = keterangan;
}
public void tampilanKeterangan(){
System.out.printf("Roda %s Merk: %s Warna: %s Diameter: %d \n ",
Keterangan, Merk, warna, diameter);
}
public void Berhenti(){
tampilanKeterangan();
System.out.println("Kurangi Kecepatan");
System.out.println("mulai berhenti..");
System.out.println("Akhirna berhenti");
System.out.println("--------------------");
}
public void berputar(){
tampilanKeterangan();
System.out.println("mulai berputar");
System.out.println("berputar");
System.out.println("berputar makin cepat");
System.out.println("----------------------");
}
}
package id.web.aditya;
public class Mobil {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Roda rodaUntukDitest = new Roda();
rodaUntukDitest.setDiameter(80);
rodaUntukDitest.setMerk("Achiles");
rodaUntukDitest.setWarna("Hitam");
rodaUntukDitest.setKeterangan("");
rodaUntukDitest.Berhenti();
rodaUntukDitest.berputar();
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: The method printf(Locale, String, Object[]) in the type
PrintStream is not applicable for the arguments (String, String,
String, String, int)
String format feature is introduced in java 1.5. You are apparently using a java version or a compilation option prior to that version.
If you are using eclipse open the project properties (ALT + Enter on the project). Look at the tab java compiler.
Here you can set your compiler compliance level. You probably have a newer java version installed. In this case eclipse shows you the above mention error.
I would expect to show you something like "The method printf(String, String, String, String, Integer) is undefined for the type PrintStream". but it doesn't so this might be a little bit confusing.

unable to watch java local class instance in eclipse

Here is a small sample:
public class LocalClassSample {
public static void main(String[] args) {
class Utils {
public void printHello(String name) {
System.out.println("Hello " + name);
}
public String outHello(String name) {
return "hello " + name;
}
}
Utils util = new Utils();
util.printHello("World");
}
}
I put a break point at the last line. I am able to view util in the Variables window...
I try to view the same variable in the expressions window...it is unable to evaluate:
Update:
Even tried inspecting the variable in the Display View...it does not evaluate:
Expression eval a java expression like 'util.printHello("World")'
and return the result ("Hello World"). 'util' is not an 'expression' but just a variable name, if you want to inspect it, use the Variables view or the Inspect command.

How do I make an annotation, that adds all classes of that type to a list

Ok, so i have a kind of command manager for one of my programs.
Theres a abstract baceclass called Command which is, really simple
public abstract class Command {
protected String commandheader;
protected int requiredlevel;
protected Random rand;
public Command(RANK rank,String command)
{
commandheader = command;
requiredlevel = rank.level;
}
}
Then in each of the classes that inherit this, i just so some oop magic.
public class MyCommand extends Command {
public MyCommand()
{
super(RANK.PLAYER,"blablabla");
}
}
Then i also have a command helper class, which keeps each of these commands in a list so i can easily find if the command, is valid when i pass it in, aswell as get a lsit of all commands that are avalable.
public class CommandHelper {
public enum RANK{
PLAYER(0);
public int level;
private RANK(int i)
{
level = i;
}
}
static List<Command> commandlist;
private static void initTheCommands()
{
//Add the commands to the list here.
commandlist.add(new MyCommand());
}
//Called by my main class
public static void Init()
{
if(commandlist == null)
{
//Were safe to initalise the stuff brah.
commandlist = new ArrayList<Command>();
initTheCommands();
for(Command cmd : commandlist)
{
System.out.println("Loaded command: " + cmd.commandheader);
}
System.out.println("[INFO] Initalised the command helper");
}
else
{
System.out.println("[INFO] Command list is already populated.");
}
}
}
As of right now, this system works completely fine. But it has a flaw, for each command i or the other editors add, we have to manually add it to the list, and that seems tedious and can lead to problems as we sync files. So i was wondering, is there any way i can add each command to the list without having to manually put it there? Perhaps annotate my method, or something to just add it to the list? I seen something about reflection, but i don't think that's what i want exactly although im not sure about it. Iv never used nor made annotations before so im not sure weather or not this is plausible.
If thats what you really want to do you can do something like this...
Declare your annotation
#Target (ElementType.TYPE)
#Retention (RetentionPolicy.RUNTIME)
public #interface CommandAnnotation {
}
Annotate your commands
#CommandAnnotation
public class MyCommand {
Then check for them something like this
...
import org.reflections.Reflections;
...
public void loadCommands() {
Reflections reflections = new Reflections("com.my.package");
Set<Class<?>> allClasses = reflections.getSubTypesOf(Command.class);
for (Class<?> outerClazz : allClasses) {
CommandAnnotation annotation = outerClazz.getAnnotation(CommandAnnotation.class);
if (annotation == null)
continue;

Java8, how discover the class and method name in visitMethodInvocation?

With Java7 and Java8, I would like to generate a warning if some methods was called.
The warning will be print if a specific jar is present when then user compile.
I write an Annotation Processor and catch the visitMethodInvocation(). Now, I want extract the class and method names will be invoked.
Is it possible to do that ?
Or how to approach this?
You can do something like:
package mystuff;
import com.sun.source.tree.*;
import com.sun.source.util.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.element.*;
import javax.tools.*;
#SupportedAnnotationTypes("*")
public class Proc extends AbstractProcessor{
#Override
public boolean process(Set<?extends TypeElement>annotations,RoundEnvironment roundEnvironment){
final Trees trees=Trees.instance(processingEnv);
for(Element element:roundEnvironment.getRootElements()){
TreePath path=trees.getPath(element);
final CompilationUnitTree compilationUnit=path.getCompilationUnit();
compilationUnit.accept(new TreeScanner<Object,Object>(){
#Override
public Object visitMethodInvocation(MethodInvocationTree tree,Object data){
tree.getMethodSelect().accept(new SimpleTreeVisitor<Object,Object>(){
#Override
public Object visitMemberSelect(MemberSelectTree tree,Object data){
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,String.format("class: %1$s\nmethod: %2$s",tree.getExpression(),tree.getIdentifier()));
return null;
}
},null);
return null;
}
},null);
}
return true;
}
}
I used that processor to process the below class
package stuff;
import java.util.*;
#MyAnnotation
class MyProgram{
public void run(){
System.out.println("Hello World!");
}
}
and achieved this result:
class: System.out
method: println
I am pretty sure that the method name generated is what you are looking for. I am pretty sure that the "class" is not exactly what you are looking for, but is a pretty good start.
In my example you probably wanted it to print "java.io.PrintStream" for the class. To get that you could use processingEnv.getElementUtils().getTypeElement("java.lang.System") to get a TypeElement representing the system class. Then you can use processingEnv.getElementUtils().getAllMembers() to get every single member of the system class. Iterate through that to find out. Use the asType method to get its type.
The preceding paragraph was a gross simplification. The processor did not know a priori that out is a static member of a class that is part of the implicitly imported java.lang package. So your code will have to try and fail to find the following classes System and java.util.System (because it is in the imports), System.out, java.util.System.out, and java.lang.System.out.
I only dealt with MemberSelect. You will have to deal with other possibilities including MethodInvocation. For example new Object().toString().hashCode() should be class=Object, method=hashCode.
As an alternative to the great answer from #emory, you can consider using the pluggable type-checking annotation processing provided by the Checker Framework. The advantage is it can help you to easily determinate the type of the method invoker. Here is an example processor based on the checker framework (add checker.jar to the classpath when compile).
#SupportedAnnotationTypes("*")
#SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MyTypeProcessor extends AbstractTypeProcessor {
class MyTreePathScanner extends TreePathScanner<Void, Void> {
private final Trees trees;
private final TreePath root;
public MyTreePathScanner(TreePath root) {
this.trees = Trees.instance(processingEnv);
this.root = root;
}
#Override
public Void visitMemberSelect(MemberSelectTree node, Void aVoid) {
ExpressionTree expression = node.getExpression();
TreePath expr = TreePath.getPath(root, expression);
TypeMirror type = trees.getTypeMirror(expr);
Element typeElement = processingEnv.getTypeUtils().asElement(type);
Optional<? extends Element> invoker = typeElement.getEnclosedElements().stream().filter(
e -> e.getSimpleName().equals(node.getIdentifier())).findFirst();
if (invoker.isPresent() && invoker.get().getKind() == ElementKind.METHOD) {
System.out.println("Type: " + typeElement + ", method: " + invoker.get());
}
return super.visitMemberSelect(node, aVoid);
}
}
#Override
public void typeProcess(TypeElement typeElement, TreePath root) {
new MyTreePathScanner(root).scan(root, null);
}
}
Which is processing the following input source.
public class Test {
public void foo() {
}
public static void main(String[] args) {
System.out.println("Hello world!");
Test t = new Test();
t.foo();
}
}
Here is the output:
Type: java.io.PrintStream, method: println()
Type: Test, method: foo()

Intellij IDEA plugin - PersistentStateComponent loadState not called

I am trying to develop a plugin for Intellij IDEA, I am working with SDK 129.451.
The issue I have is that I can't persist the user data like some list items he can input in the plugin and have the data back after the IDE restarts..
I am using PersistentStateComponent to persist the data, the getState() method seems to be called but the loadState() method doesn't.
Here is a sample class that extends PersistentStateComponent:
#State(name = "Test", storages = {#Storage(file = StoragePathMacros.APP_CONFIG+"/other.xml"
)})
public class Test implements PersistentStateComponent<Element> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Element state) {
System.out.println("cstate load");
ceva = (String) state.getContent().get(0);
}
public Element getState() {
System.out.println("cstate retu");
Element configurationsElement = new Element("testtt");
configurationsElement.addContent(ceva);
return configurationsElement;
}
}
Also I added this class in plugin.xml here:
<extensions defaultExtensionNs="com.intellij">
<applicationService serviceImplementation="ro.catalin.prata.testflightuploader.controller.Test"/>
<!-- Add your extensions here -->
<toolWindow id="TF Uploader" secondary="true" icon="/general/add.png" anchor="right"
factoryClass="ro.catalin.prata.testflightuploader.view.TFUploader">
</toolWindow>
</extensions>
And I also have a tool window class:
public class TFUploader implements ToolWindowFactory {
private JButton buttonAction;
private ToolWindow myToolWindow;
final Test test = ServiceManager.getService(Test.class);
public TFUploader() {
// I assume it should print the saved string but it doesn't
System.out.println(test.getCeva());
buttonAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if I click a button I am setting some new value to the string I want to save
test.setCeva(test.getCeva() + "-dddddd+");
}
});
}
Ok so, if I close the app or minimize it, the getState method gets called as I expected.. but when I open the app, the loadState method doesn't get called.. can somebody help me how I can solve this?
I already read this but it doesn't seem to help me to much. Also I want to use PersistentStateComponent as I want to save objects more complex than a simple String.
Thank you in advance!
Ok, I made it! :)
I don't know exactly what the issue was but I changed the Test class to this:
#State(
name = "Test", storages = {
#Storage(
id = "other",
file = "$APP_CONFIG$/testpersist.xml")
})
public class Test implements PersistentStateComponent<Test> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Test state) {
System.out.println("cstate load");
XmlSerializerUtil.copyBean(state, this);
}
public Test getState() {
System.out.println("cstate retu");
return this;
}
}
And in the TFUploader I changed the way I loaded the Test class to this:
final Test test = ServiceManager.getService(Test.class);
I hope it helps others..
I have already commented here but will say again that in my case loadState(MyService state) wasn't called because of lack of getter and setter for stateValue from this example:
class MyService implements PersistentStateComponent<MyService> {
public String stateValue;
public MyService getState() {
return this;
}
public void loadState(MyService state) {
XmlSerializerUtil.copyBean(state, this);
}
}
In my case I was getting a NullPointerException even before loadState was getting called. Similar to your code above I used an Element class as the state class. I had a constructor with some parameters in Element class. This was the problem as the framework could not create an instance of my state class. I tried to add a blank constructor without any parameters. This worked.

Categories