I'm trying to make a plugin that detects when people chat
"#say " it will broadcast a message with those arguments.
What I need to know is how to get arguments from a string.
Please help.
Main:
package com.gong.say;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin{
String sayMessage = ChatColor.GREEN + "Your message has been said!";
public void onEnable()
{
Bukkit.getLogger().info("[BukkitAPIEnhancer] Plugin started!");
Bukkit.getPluginManager().registerEvents(new ChatListener(this), this);
}
public void onDisable()
{
Bukkit.getLogger().info("[BukkitAPIEnhancer] Plugin disabled!");
}
}
ChatListener:
package com.gong.say;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatListener implements Listener {
Main plugin;
public ChatListener(Main plugin)
{
this.plugin = plugin;
}
#EventHandler
public void onChat(AsyncPlayerChatEvent e)
{
if(e.isAsynchronous())
{
String message = e.getMessage();
if(message.contains("#say"))
{
//String[] args = Arguments after #say
//Bukkit.broadcastMessage(args);
}
}
}
}
You should usually use commands prefixed by /, so, normally you would do /say String[args], and It would be easier to get the arguments, yet if you want it to be prefixed by #, then that's another story. You could do something like this:
if(message.contains("#say")){
String messageToSend = message.replaceAll("#say", "");//get the arguments
if(messageToSend.length <= 0){//make sure there's something after #say
e.getPlayer().sendMessage("Correct usage: #say <arguments>"); //the user didn't put anything after #say
return;
}
else{
e.setCancelled(true);//cancel the event
Bukkit.getServer().broadcastMessage(messageToSend);//send the message that comes after "#say"
//you may want to add a chat color to the message to make it stand out more
}
}
So, here's what your event should look like:
#EventHandler
public void onChat(AsyncPlayerChatEvent e){
if(e.isAsynchronous()){
String message = e.getMessage();
if(message.contains("#say")){
String messageToSend = message.replaceAll("#say", "");//get the arguments
if(messageToSend.length <= 0){//make sure there's something after #say
e.getPlayer().sendMessage("Correct usage: #say <arguments>"); //the user didn't put anything after #say
return;
}
else{
e.setCancelled(true);//cancel the event
Bukkit.getServer().broadcastMessage(messageToSend);//send the message that comes after "#say"
//you may want to add a chat color to the message to make it stand out more
}
}
}
}
#EventHandler
public void onChat2(AsyncPlayerChatEvent e) {
if(e.isAsynchronous()) {
String msg = e.getMessage();
/** Verify if message starts with #say **/
if(msg.startsWith("#say")) {
/** Split message for get the args **/
String[] args = e.getMessage().split(" ");
/** Verify if have something after #say **/
if(args.length > 1) {
/** Cancel message and broadcast **/
e.setCancelled(true);
StringBuilder sb = new StringBuilder();
for(int i = 1; i <args.length; i++) {
sb.append(args[i] + " ");
}
/** Add color to broadcast */
String broadcast = ChatColor.translateAlternateColorCodes('&', sb.toString());
/** Broadcast prefix **/
String prefix = "§c[Broadcast] §r";
/** Broadcast **/
Bukkit.broadcastMessage(prefix + broadcast);
}
}
}
}
Related
How do I access/get the string return values of a public static method that is nested in a public static class?
I want to display the string on a screen.
I've tried using private StringProperty variables to setDataString() the method return values as seen in the code snippet below.
The method named "byteToHex(buffer)" is the one whose return value I'm trying to access.
public static class SerialPortReader implements SerialPortEventListener
{
final public static char COMMA = ',';
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = '\\';
#Override
public void serialEvent(SerialPortEvent event)
{
if(event.isRXCHAR() && event.getEventValue() > 0)
{
try {
byte buffer[] = serialPort.readBytes();
byteToHex(buffer);
TransCeiveSerialData dataString = new TransCeiveSerialData();
dataString.setDataString(byteToHex(buffer));
/*
* wait some milliseconds before sending next data package to avoid data losses
*/
try {
Thread.sleep(100);
}catch(InterruptedException ie)
{
Logger.getLogger(TransCeiveSerialData.class.getName()).log(Level.SEVERE, null, ie);
}
}
catch(SerialPortException spe) {System.out.println("Error in port listener: " + spe);}
}
}
}
public static String byteToHex(byte x[])
{
StringBuffer retString = new StringBuffer();
for(int i = 0; i < x.length; ++i)
{
retString.append(Integer.toHexString(0x0100 + (x[i] & 0x00FF)).substring(1));
}
return retString.toString();
}
Using for exmaple System.out.println("Received data: " + instanceOfClass.getDataString()); in an external class to get the method's return string I get a "null". But I expect to get 31323334353637380d0a.
I've also tried binding the values but without any success.
Do you perhaps have any ideas how I can solve this problem? Your help will be very much appreciated.
Thanks a lot in advance!
AvJoe
When i double-click the right border of a column's header cell - it automatically adjust the width of a column.
How can i do same programmatically?
Finally I found the solution:
TableViewSkin<?> skin = (TableViewSkin<?>) table.getSkin();
TableHeaderRow headerRow = skin.getTableHeaderRow();
NestedTableColumnHeader rootHeader = headerRow.getRootHeader();
for (TableColumnHeader columnHeader : rootHeader.getColumnHeaders()) {
try {
TableColumn<?, ?> column = (TableColumn<?, ?>) columnHeader.getTableColumn();
if (column != null) {
Method method = skin.getClass().getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
method.setAccessible(true);
method.invoke(skin, column, 30);
}
} catch (Throwable e) {
e = e.getCause();
e.printStackTrace(System.err);
}
}
Javafx still crude. Many simple things need to do through deep ass...
(not only internal) API changed from fx8 to fx9:
TableViewSkin (along with all skin implementations) moved into public scope: now it would be okay to subclass and implement whatever additional functionality is needed
tableViewSkin.getTableHeaderRow() and tableHeaderRow.getRootHeader() changed from protected to package-private scope, the only way to legally access any is via lookup
implementation of resizeToFitContent moved from skin to a package-private utility class TableSkinUtils, no way to access at all
TableColumnHeader got a private doColumnAutoSize(TableColumnBase, int) that calls the utility method, provided the column's prefWidth has its default value 80. On the bright side: due to that suboptimal api we can grab an arbitrary header and auto-size any column
In code (note: this handles all visible leaf columns as returned by the TableView, nested or not - if you want to include hidden columns, you'll need to collect them as well)
/**
* Resizes all visible columns to fit its content. Note that this does nothing if a column's
* prefWidth is != 80.
*
* #param table
*/
public static void doAutoSize(TableView<?> table) {
// good enough to find an arbitrary column header
// due to sub-optimal api
TableColumnHeader header = (TableColumnHeader) table.lookup(".column-header");
if (header != null) {
table.getVisibleLeafColumns().stream().forEach(column -> doColumnAutoSize(header, column));
}
}
public static void doColumnAutoSize(TableColumnHeader columnHeader, TableColumn column) {
// use your preferred reflection utility method
FXUtils.invokeGetMethodValue(TableColumnHeader.class, columnHeader, "doColumnAutoSize",
new Class[] {TableColumnBase.class, Integer.TYPE},
new Object[] {column, -1});
}
Using the above excellent answer posted by Александр Киберман, I created a class to handle this and the issue of getSkin() == null:
import com.sun.javafx.scene.control.skin.NestedTableColumnHeader;
import com.sun.javafx.scene.control.skin.TableColumnHeader;
import com.sun.javafx.scene.control.skin.TableHeaderRow;
import com.sun.javafx.scene.control.skin.TableViewSkin;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.lang.reflect.Method;
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
public class TableViewPlus extends TableView
{
private boolean flSkinPropertyListenerAdded = false;
// ---------------------------------------------------------------------------------------------------------------------
public TableViewPlus()
{
super();
this.setEditable(false);
}
// ---------------------------------------------------------------------------------------------------------------------
public TableViewPlus(final ObservableList toItems)
{
super(toItems);
this.setEditable(false);
}
// ---------------------------------------------------------------------------------------------------------------------
public void resizeColumnsToFit()
{
if (this.getSkin() != null)
{
this.resizeColumnsPlatformCheck();
}
else if (!this.flSkinPropertyListenerAdded)
{
this.flSkinPropertyListenerAdded = true;
// From https://stackoverflow.com/questions/38718926/how-to-get-tableheaderrow-from-tableview-nowadays-in-javafx
// Add listener to detect when the skin has been initialized and therefore this.getSkin() != null.
this.skinProperty().addListener((a, b, newSkin) -> this.resizeColumnsPlatformCheck());
}
}
// ---------------------------------------------------------------------------------------------------------------------
private void resizeColumnsPlatformCheck()
{
if (Platform.isFxApplicationThread())
{
this.resizeAllColumnsUsingReflection();
}
else
{
Platform.runLater(this::resizeAllColumnsUsingReflection);
}
}
// ---------------------------------------------------------------------------------------------------------------------
// From https://stackoverflow.com/questions/38090353/javafx-how-automatically-width-of-tableview-column-depending-on-the-content
// Geesh. . . .
private void resizeAllColumnsUsingReflection()
{
final TableViewSkin<?> loSkin = (TableViewSkin<?>) this.getSkin();
// The skin is not applied till after being rendered. Which is happening with the About dialog.
if (loSkin == null)
{
System.err.println("Skin is null");
return;
}
final TableHeaderRow loHeaderRow = loSkin.getTableHeaderRow();
final NestedTableColumnHeader loRootHeader = loHeaderRow.getRootHeader();
for (final TableColumnHeader loColumnHeader : loRootHeader.getColumnHeaders())
{
try
{
final TableColumn<?, ?> loColumn = (TableColumn<?, ?>) loColumnHeader.getTableColumn();
if (loColumn != null)
{
final Method loMethod = loSkin.getClass().getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
loMethod.setAccessible(true);
loMethod.invoke(loSkin, loColumn, 30);
}
}
catch (final Throwable loErr)
{
loErr.printStackTrace(System.err);
}
}
}
// ---------------------------------------------------------------------------------------------------------------------
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
table.skinProperty().addListener((a, b, newSkin) -> {
TableViewSkin<?> skin = (TableViewSkin<?>) table.getSkin();
TableHeaderRow headerRow = skin.getTableHeaderRow();
NestedTableColumnHeader rootHeader = headerRow.getRootHeader();
for (TableColumnHeader columnHeader : rootHeader.getColumnHeaders()) {
try {
TableColumn<?, ?> column = (TableColumn<?, ?>) columnHeader.getTableColumn();
if (column != null) {
Method method = skin.getClass().getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
method.setAccessible(true);
method.invoke(skin, column, 30);
}
} catch (Throwable e) {
e = e.getCause();
e.printStackTrace(System.err);
}
}
});
In order to prevent getSkin() == null;
I have written the following code and keep running into this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at yournamep3.Yournamep3test.main(Yournamep3test.java:23)
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class Yournamep3test {
public static void main(String[] args) {
// Check if target file exists
File targetFile = new File(args[0]);
try {
PrintWriter out = new PrintWriter(targetFile);
out.write("\r\nStringed musical Instrument program");
for (int arrayIndex = 0; arrayIndex < 10; arrayIndex++) {
out.write("\r\n\r\n");
out.write("\r\nCreating new Stringed Musical Instrument object now..............");
Yournamep3 violinInstrument = new Yournamep3();
violinInstrument.setNameOfInstrument("Violin # " + (arrayIndex+1));
out.write("\r\nCreated instrument with name - "
+ violinInstrument.getNameOfInstrument());
int num = violinInstrument.getNumberOfStrings();
out.write("\r\nNumber of strings in instrument is " + num);
out.write("\r\nNames of String are ");
String strings[] = violinInstrument.getStringNames();
for (int counter = 0; counter < num; counter++) {
out.write("\r\n" + strings[counter]);
}
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nTuning now.........");
violinInstrument.setTuned(true);
out.write("\r\nIs the Instrument tuned - "
+ violinInstrument.isTuned());
out.write("\r\nCalling the Instrument play method now..");
violinInstrument.startPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
out.write("\r\nStopping playing of instrument..............");
violinInstrument.stopPlayInstrument();
out.write("\r\nIs the Instrument playing - "
+ violinInstrument.isPlaying());
}
out.close();
} catch (IOException e) {
}
}
}
I think the issue is with line 23. Any advice would be appreciated, thanks.
This is the other part of the code yournamep3
public class Yournamep3 {
//fields to determine if the instrument is isTuned,
private boolean isTuned;
//and if the instrument is currently isPlaying.
private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public Yournamep3() {
this.isTuned = false;
this.isPlaying = false;
}
/**
* #return the name
*/
public String getNameOfInstrument() {
return name;
}
/**
* #param name the name to set
*/
public void setNameOfInstrument(String nameOfInstrument) {
this.name = nameOfInstrument;
}
// Other methods
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean playing) {
this.isPlaying = playing;
}
public boolean isTuned() {
return isTuned;
}
public void setTuned(boolean isTuned) {
this.isTuned = isTuned;
}
public void startPlayInstrument() {
System.out.println("The Instrument is now Playing.");
isPlaying = true;
}
public void stopPlayInstrument() {
System.out.println("The Instrument is not Playing anymore.");
isPlaying = false;
}
public void startTuneInstrument() {
System.out.println("The Instrument is Tuned.");
isTuned = true;
}
public void stopTuneInstrument() {
System.out.println("The Instrument is not Tuned.");
isTuned = false;
}
public int getNumberOfStrings() {
return this.numberOfStrings ;
}
public String[] getStringNames() {
return nameofStringsInInstrument;
}
}
I would look at your getStringNames() method for your violinInstrument. It seems to me that it isn't populating your String array properly, or the getNumberOfStrings() method does not give the right number of strings. If you put the code for that up, I can help a bit more.
Line 23 appears to be
Yournamep3 violinInstrument = new Yournamep3();
If that's the case you should check the constructor for Yournamemp3
Since Line 23 is
File targetFile = new File(args [0]);
It indicates that your args object is empty. ArrayIndexOutOfBoundException is thrown to indicate that an array has been accessed with an illegal index. 0 is an illegal index.
The code will not compile. I changed the JRE to 1.7. The compiler does not highlight the class in Eclipse and the CrawlConfig appears to fail in the compiler. The class should be run from the command line in Linux.
Any ideas?
Compiler Error -
Description Resource Path Location Type
Syntax error on token "crawlStorageFolder", VariableDeclaratorId expected after this token zeocrawler.java /zeowebcrawler/src/main/java/com/example line 95 Java Problem
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
public class Controller {
String crawlStorageFolder = "/data/crawl/root";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.senym.com");
controller.addSeed("http://www.merrows.co.uk");
controller.addSeed("http://www.zeoic.com");
controller.start(MyCrawler.class, numberOfCrawlers);
}
public URLConnection connectURL(String strURL) {
URLConnection conn =null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
int test = 0;
}catch(MalformedURLException e) {
System.out.println("Please input a valid URL");
}catch(IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
public static void updatelongurl()
{
// System.out.println("Short URL: "+ shortURL);
// urlConn = connectURL(shortURL);
// urlConn.getHeaderFields();
// System.out.println("Original URL: "+ urlConn.getURL());
/* connectURL - This function will take a valid url and return a
URL object representing the url address. */
}
public class MyCrawler extends WebCrawler {
private Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+ "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
#Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
#Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
}
}
This is a pretty strange error since the code seems to be clean. Try to start eclipse with the -clean option on command line.
Change
String crawlStorageFolder = "/data/crawl/root";
to
String crawlStorageFolder = "./data/crawl/root";
i.e. add a leading .
public class _Variable
{
public bool MailStat;
public Pop3Client pop3;
public int lastmailCount;
public int currentmailCount;
public Message msg;
public MessagePart msgPart;
public Timer _timer;
}
public List<int> _MailReader()
{
_Variable _var = new _Variable();
try
{
//HttpContext.Current.Session["Pop3Client"]
if (HttpContext.Current.Session["Pop3Client"] == null)
{
_var.pop3 = new Pop3Client();
_var.pop3.Connect("pop.gmail.com", 995, true);
_var.MailStat = _var.pop3.Connected;
_var.pop3.Authenticate("nithin.testing1#gmail.com", "xxxxxxx");
HttpContext.Current.Session["Pop3Client"] = _var.pop3;
}
else
{
_var.pop3 = (Pop3Client)HttpContext.Current.Session["Pop3Client"];
}
if (_var.MailStat)
{
//HttpContext.Current.Application["lastmailCount"] = _var.pop3.GetMessageCount();
_var.currentmailCount = _var.pop3.GetMessageCount();
_var.lastmailCount = _global.lastmailCount;
if (_var.lastmailCount < _var.currentmailCount)
{
_global.lastmailCount = _var.currentmailCount;
int _diff = _var.currentmailCount - _var.lastmailCount;
for (int _loop = _var.currentmailCount; _diff > 0; _diff--)
{
_var.msg = _var.pop3.GetMessage(_loop-(_diff-1));
_var.msgPart = _var.msg.MessagePart.MessageParts[0];
string bodyPart = _var.msgPart.BodyEncoding.GetString(_var.msgPart.Body).ToString().Trim();
int _result;
if (int.TryParse(bodyPart, out _result))
{
_global._vbill.Add(Int32.Parse(bodyPart));
_global._vDate.Add(_var.msg.Headers.DateSent.ToString());
}
}
}
}
_var.pop3.Dispose();
return _global._vbill;
}
catch (Exception ex)
{
return _global._vbill;
}
}
I am using the OpenPop.dll and In the following code pop.getMessageCount is returning zero even there are mails in my account.
_Variable method contains all the variables I used in the code and in _MailReader. I am just reading all my mails from my application and returning into a list but this is the problem count is zero always.
It's a feature of gmail pop3 server. By default, you can receive only unread messages. That means, if you or somebody else already has downloaded certain message once, it will not be possible to receive it by pop3 protocol anymore.
To avoid it, you have to configure your gmail account. Check "Enable POP for all mail (event mail that's already been downloaded)" in "Forwarding and POP/IMAP" section of gmail settings.
Screenshot: http://i.stack.imgur.com/UE7ip.png