Breaking a while-loop with a stop-command - java

I'm trying to make a Discord-Bot which allows you to ping certain servers. I want to ping a server (which is offline) until it comes back online. So far so good.
Now I want to add a "!stop" command which canceles this process because of whatever reason.
public class cmdping implements Commands{
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
public void action(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
if((args.length == 3)) {
switch (args[2]) {
//Pings the server until it comes back online (won't work while it's online).
case "-t":
try{
int i = 0;
int q = 0;
InetAddress address = InetAddress.getByName(args[0]);
event.getTextChannel().sendMessage("Pinging _" + args[0] + " _(**" + args[1] + "**)_ ....._\n ").queue();
boolean reachable = address.isReachable(2500);
if (reachable) {
event.getTextChannel().sendMessage("Server is online.").queue();
i++;
q++;
} else {
while(!address.isReachable(2500)) {
event.getTextChannel().sendMessage("_"+args[0] + "_ (**"+ args[1] +"**) isn't communicating.").queue();
q++;
}
double outcome = 0;
outcome = i/q*100;
event.getTextChannel().sendMessage(q+" Packages were sent. The server responded to *" + i + ". " +i+"/"+q+" --> **"+outcome+"%**").queue();
i = 0;
q=0;
}
} catch (Exception e){
e.printStackTrace();
}
break;
default:
event.getTextChannel().sendMessage("Wrong arguments.").queue();
break;
}
} else {
event.getTextChannel().sendMessage("Command is not complete.").queue();
}
}
Here is the stopcmd class
public class cmdstop implements Commands {
public boolean called(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
return false;
}
public void action(String[] args, MessageReceivedEvent event) {
// TODO Auto-generated method stub
}
public void executed(boolean safe, MessageReceivedEvent event) {
// TODO Auto-generated method stb
System.out.println("[INFO] Command 'stop' just got used!");
}
public String help() {
// TODO Auto-generated method stub
return null;
} }
What would I have to do to implement the stop command? I've tried out multiple things already which didn't work out for me.
EDIT: CommandListener & CommandHandler
public class commandListener extends ListenerAdapter {
public void onMessageReceived(MessageReceivedEvent event) {
if(event.getMessage().getContentRaw().startsWith(STATIC.PREFIX) && (event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId())) {
commandHandler.handleCommand(CommandParser.parser(event.getMessage().getContentRaw(), event));
}
} }
public class commandHandler {
public static final CommandParser parse = new CommandParser();
public static HashMap<String, Commands> commands = new HashMap<String, Commands>();
public static void handleCommand(CommandParser.commandContainer cmd) {
if(commands.containsKey(cmd.invoke)) {
boolean safe = commands.get(cmd.invoke).called(cmd.args, cmd.event);
if (!safe) {
commands.get(cmd.invoke).action(cmd.args, cmd.event);
commands.get(cmd.invoke).executed(safe, cmd.event);
} else {
commands.get(cmd.invoke).executed(safe, cmd.event);
}
}
}}
Now there is another problem. During the while-loop it doesn't detect any other commands.

Related

Observer with RxJava/Quarkus

I started a Quarkus project, which (in part) shall watch for file changes on a text-file, read the added line(s) and then sends the added line(s) through a websocket connection to a client.
For watching the file changes and reading those I created the following class:
public class McServerService {
private String directory;
private List<String> currentLog;
private Observable<List<String>> observableLog;
private Thread logObserverThread;
public McServerService (String directory) {
this.currentLog = new ArrayList<String>();
this.observableLog = Observable.fromCallable(() -> this.currentLog);
this.directory = directory;
}
public void startWatching () {
this.logObserverThread = new Thread(new LogObserverThreadImpl(this.directory));
this.logObserverThread.start();
}
public void subscribeToLog (Observer<? super List<String>> observer) {
this.observableLog.subscribe(observer);
}
private class LogObserverThreadImpl implements Runnable {
BufferedReader br;
WatchService watchService;
private LogObserverThreadImpl (String directory) {
try {
this.br = new BufferedReader(new java.io.FileReader(directory + "\\" + "latest.log"));
String nextLine;
while ((nextLine = this.br.readLine()) != null) {
McServerService.this.currentLog.add(nextLine);
System.out.println(nextLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Path path = Paths.get(directory);
try {
System.out.println("entered try");
this.watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = this.watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
if (event.context().toString().equals("latest.log")) {
String line = this.br.readLine();
McServerService.this.currentLog.add(line);
System.out.println(line);
}
}
key.reset();
}
System.out.println("after while");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now the websocket would be handled by this class:
#ServerEndpoint("/test")
#ApplicationScoped
public class McServerWebSocket {
Map<String, Session> sessions = new ConcurrentHashMap<>();
McServerService mss = new McServerService("D:\\Spiele\\Minecraft");
#OnOpen
public void onOpen(Session session, #PathParam("name") String name) {
sessions.put(name, session);
}
#OnClose
public void onClose(Session session, #PathParam("name") String name) {
sessions.remove(name);
}
#OnError
public void onError(Session session, #PathParam("name") String name, Throwable throwable) {
sessions.remove(name);
}
#OnMessage
public void onMessage(String message, #PathParam("name") String name) {
Session c_session = sessions.get(name);
c_session.getAsyncRemote().sendObject("insert");
}
private class ConsoleLogObserverImpl implements Observer<List<String>>{
private ConsoleLogObserverImpl () {
}
#Override
public void onSubscribe(#NonNull Disposable d) {
// TODO Auto-generated method stub
System.out.println("subscribed");
}
#Override
public void onNext(#NonNull List<String> t) {
System.out.println(t.toString());
}
#Override
public void onError(#NonNull Throwable e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("finished");
}
}
}
I didnt implement the websocket yet, because my problem lies with observing the changes of
private List<String> currentLog; in the McServerServive class.
Unfortunately I deleted the main method in McServerWebSocket, that I used to test this, but that main method would essentially just create an instance of McServerWebSocket and then call the startWatching() method of its McServerService mss = new McServerService("D:\\Spiele\\Minecraft"); and its
public void subscribeToLog (Observer<? super List<String>> observer) {
this.observableLog.subscribe(observer);
}
method with the inner class:
private class ConsoleLogObserverImpl implements Observer<List<String>>
But the behaviour was not as I would have exspected. The output was:
subscribed
[]
finished
The observable was imediately terminating. Did I do something wrong when creating the Observable or did I completly misunderstand the usage RxJava?
How can I create an Observable class field and an Observer that triggers an action when the Observable is changed with RxJava/some Quarkus extension?

App for external barcode scanner(use USB port)

Update: came up with new error about the provided java class
I have a tutorial for building an app for an external barcode scanner(use USB port) by using Java + provided Jar Library. I'm trying to build the same app by using the Xamarin.Forms and that Jar Library(through BindingsLibrary Project). However, I got an error
"Java.Lang.NoClassDefFoundError: " when I compiled my code. Does anybody have an idea about what I'm doing wrong?
This my java classes:
The USBScanFactory
package com.unistrong.qrcode;
import com.unistrong.pin.GOPOManager;
public class USBQRscanFactory {
private static USBQRscanFactory factory = new USBQRscanFactory();
static boolean mIsScanContinue = false;
private GOPOManager mGopoManager = GOPOManager.getInstance();
private OnScanListener mScanListener;
private QRScanManagerJNI qrScanManagerJNI;
private USBQRscanFactory() {
}
public static USBQRscanFactory createInstance() {
return factory;
}
public void init(OnScanListener onScanListener) {
this.mGopoManager.Pin11_High();
this.qrScanManagerJNI = new QRScanManagerJNI(onScanListener);
this.qrScanManagerJNI.callbackInit();
}
public void enableAddKeyValue(int i) {
QRScanManagerJNI.AddKeyValue(i);
}
public void open() {
this.mGopoManager.Pin11_Low();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
QRScanManagerJNI.OpenDev();
}
public void powerOn() {
this.mGopoManager.Pin11_High();
this.mGopoManager.openPower5V_3V3();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void powerOff() {
this.mGopoManager.Pin11_High();
this.mGopoManager.closePower5V_3V3();
}
public void scan_start() {
QRScanManagerJNI.QRScan();
}
On ScanListener:
package com.unistrong.qrcode;
public interface OnScanListener {
void scanReport(byte[] bArr);
void statusReport(int i);
}
And here is my code on Xamain:
public class OnScanListener : Java.Lang.Object, IOnScanListener
{
H myH = new H();
public void ScanReport(byte[] byteArray)
{
lock (myH)
{
if (null != byteArray && byteArray.Length > 0)
{
myH.SendMessage(myH.ObtainMessage(0, byteArray));
}
}
}
public void StatusReport(int i)
{
lock (myH)
{
myH.SendEmptyMessage(i);
}
}
}
#endregion
public MainPage()
{
usbScan = USBQRscanFactory.CreateInstance();
InitializeComponent();
}
int count = 0;
private void scanBtn_Clicked(object sender, EventArgs e)
{
count++;
//usbScan.Init(OnScanListener);
OnScanListener myOnScanListener = new OnScanListener();
usbScan.PowerOn();
usbScan.Init(myOnScanListener);
Barcode.Text = "";
openScanner(true);
usbScan.Scan_start();
}
//Open Scanner
private void openScanner(bool open)
{
if (open == mWorkingStateFlag) return;
if (open)
{
try
{
Java.Lang.Thread.Sleep(50);
usbScan.Open();
usbScan.EnableAddKeyValue(0);
}
catch (Java.Lang.InterruptedException e)
{
// TODO Auto-generated catch block
e.PrintStackTrace();
}
}
}

Creating Markers and Problems in Eclipse Plugin

I have been doing a fair amount of research but am having a hard time understanding the relation between IProblem and IMarker. I have been able to create problems and add markers but the two do not seem to be connected. Are problems and markers independent? At first I was thinking that if I add problems to ReconcileContext the markers would appear automatically but that does not appear to be the case. Does anyone know if I am doing something wrong?
SecureCompilationParticipant.java:
public class SecureCompilationParticipant extends CompilationParticipant {
public boolean isActive(IJavaProject project) {
return true;
}
#Override
public void reconcile(ReconcileContext context) {
// Call Parent
super.reconcile(context);
// Used in expression loop
int start, end, line;
String fileName;
// Check to see if content has changed
IJavaElementDelta elementDelta = context.getDelta();
IJavaElement element = elementDelta.getElement();
if((elementDelta.getFlags() & IJavaElementDelta.F_CONTENT) != 0) {
System.out.printf("The content of %s has changed%n",
element.getElementName());
try {
CompilationUnit compilation = context.getAST8();
NodeVisitor visitor = new NodeVisitor();
compilation.accept(visitor);
// Iterate through expressions
for (ExpressionStatement expressionStatement : visitor.getExpressionStatements()) {
start = expressionStatement.getStartPosition();
end = start + expressionStatement.getLength();
line = compilation.getLineNumber(start - 1);
fileName = element.getElementName();
System.out.printf("Expression: %s%n", expressionStatement.getExpression().toString());
CategorizedProblem[] problems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> problemList = new ArrayList<CategorizedProblem>();
// Put problems
SecureCodingProblem problem = new SecureCodingProblem(fileName);
problem.setSourceStart(start);
problem.setSourceEnd(end);
problem.setSourceLineNumber(line);
problemList.add(problem);
context.putProblems(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, problemList.toArray(problems));
// Create marker
IResource resource = element.getUnderlyingResource();
IMarker marker = resource.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.MESSAGE, "This is a test marker");
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
marker.setAttribute(IMarker.LINE_NUMBER, line);
marker.setAttribute(IMarker.LOCATION, String.format("Line %d", line));
}
} catch (JavaModelException e) {
// From CompilationUnit compilation = context.getAST8();
e.printStackTrace();
} catch (CoreException e) {
// From IMarker marker = resource.createMarker(IMarker.PROBLEM);
e.printStackTrace();
}
}
}
}
SecureCodingProblem.java:
public class SecureCodingProblem extends CategorizedProblem {
private int m_sourceStart;
private int m_sourceEnd;
private int m_sourceLineNumber;
private char[] m_fileName;
public SecureCodingProblem(String fileName) {
m_fileName = fileName.toCharArray();
}
#Override
public String[] getArguments() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getID() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getMessage() {
// TODO Auto-generated method stub
return "This is a problem";
}
#Override
public char[] getOriginatingFileName() {
// TODO Auto-generated method stub
return m_fileName;
}
#Override
public int getSourceEnd() {
// TODO Auto-generated method stub
return m_sourceEnd;
}
#Override
public int getSourceLineNumber() {
// TODO Auto-generated method stub
return m_sourceLineNumber;
}
#Override
public int getSourceStart() {
// TODO Auto-generated method stub
return m_sourceStart;
}
#Override
public boolean isError() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isWarning() {
// TODO Auto-generated method stub
return true;
}
#Override
public void setSourceEnd(int sourceEnd) {
m_sourceEnd = sourceEnd;
}
#Override
public void setSourceLineNumber(int lineNumber) {
m_sourceLineNumber = lineNumber;
}
#Override
public void setSourceStart(int sourceStart) {
m_sourceStart = sourceStart;
}
#Override
public int getCategoryID() {
// TODO Auto-generated method stub
return CategorizedProblem.CAT_CODE_STYLE;
}
#Override
public String getMarkerType() {
// TODO Auto-generated method stub
return IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER;
}
}
IProblem is specific to the Java Development Tools whereas IMarker can be used for any file in the workspace.
The JavaDoc for IProblem says:
Note: the compiler produces IProblems internally, which are turned
into markers by the JavaBuilder so as to persist problem descriptions.
This explains why there is no API allowing to reach IProblem detected
when compiling. However, the Java problem markers carry equivalent
information to IProblem, in particular their ID (attribute "id") is
set to one of the IDs defined on this interface.

The method getApplication() is undefined for the type (my class)

I am using a global variables "GlobalVariables" in a separated class and I am try to use it in the following code but it is always gives me the error :
The method getApplication() is undefined for the type UploadPicture
I tried the following but still have error:
((GlobalVariables) this.getApplication()).set_FileUploading(false);
The qustion was already asked here but unfortunatlly all the answors didn't work with me and gave me same error! any suggestion please?
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) {
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
return 500;
}
#Override
public void onProgress(long bytes, long total) {
//publishProgress(bytes);
}
}
);
if (mRequest != null) {
mRequest.upload();
((GlobalVariables) UploadPicture.this.getApplication()).set_FileUploading(false);
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
Edit: I am adding now my "VariableGlobales" calss:
public class GlobalVariables extends Application {
private Boolean _IsIOIORunning=false;
private Boolean _FileUploading=false;
public Boolean get_IsIOIORunning()
{
return _IsIOIORunning;
}
public void set_IsIOIORunning(Boolean _IsIOIORunning)
{
this._IsIOIORunning = _IsIOIORunning;
}
public Boolean get_FileUploading()
{
return _FileUploading;
}
public void set_FileUploading(Boolean _FileUploading)
{
this._FileUploading = _FileUploading;
}
It's normal UploadPicture doesn't extend GlobalVariables but it extend AsyncTask.
That it's my "GlobalVariables "
public class AppInfo extends Application {
private static Context context;
private static String user;
public void onCreate(){
super.onCreate();
AppInfo.context = getApplicationContext();
user = null;
}
public static Context getAppContext() {return AppInfo.context;}
public static String getUser() {return user;}
public static void setUser(String user) {AppInfo.user = user;}
}
And I call it everywhere like that:
AppInfo.getUser();
Edit:
GlobalVariables should use static method and variables:
public class GlobalVariables extends Application {
private static Boolean _IsIOIORunning=false;
private static Boolean _FileUploading=false;
public static Boolean get_IsIOIORunning() {
return _IsIOIORunning;
}
public static void set_IsIOIORunning(Boolean _IsIOIORunning) {
GlobalVariables._IsIOIORunning = _IsIOIORunning;
}
public static Boolean get_FileUploading(){
return _FileUploading;
}
public static void set_FileUploading(Boolean _FileUploading){
GlobalVariables._FileUploading = _FileUploading;
}
}

Java getMethod() results in NoSuchMethodException error

I am trying to use reflection to launch the appropriate method when the user inputs a string command. For instance, if the user inputs "go" in the terminal, the go() method of the Player class will be called by the process() method of the Command class.
However, I cannot get my code working and I get a NoSuchMethodException error that I do not know how to fix. The lines at the source of the problem are half-way through the Command class (complete classes reproduced at the bottom):
try {
Method method = pClass.getMethod(commandWord);
method.invoke(player, this);
}
catch (NoSuchMethodException err1) {
System.out.println("No such method");
}
Could anyone please guide me? I thank you in advance.
LC
Command class:
import java.util.ArrayList;
import java.lang.reflect.*;
public class Command
{
private String commandWord;
private String secondWord;
public Command(String firstWord, String secondWord)
{
commandWord = firstWord;
this.secondWord = secondWord;
}
public boolean process(Player player)
{
ArrayList<String> validCommands = new ArrayList<String>();
String methodName;
int index;
Class pClass = player.getClass();
Method[] methods = pClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (Modifier.isPublic(methods[i].getModifiers())) {
validCommands.add(methods[i].getName());
}
}
boolean wantToQuit = false;
if(commandWord == null) {
System.out.println("I don't know what you mean...");
return false;
}
if (commandWord.equals("help")) {
System.out.println("You are lost. You are alone. You wander");
System.out.println("around at the university.");
System.out.println();
System.out.println("Your command words are:");
for(String command: validCommands) {
System.out.print(command + " ");
}
System.out.println();
}
else if (commandWord.equals("quit")) {
wantToQuit = quit();
}
//THIS IS WHERE I GET THE ERROR
try {
Method method = pClass.getMethod(commandWord);
method.invoke(player, this);
}
catch (NoSuchMethodException err1) {
System.out.println("No such method");
}
catch (IllegalAccessException err2) {
System.out.println("Illegal access");
}
catch (InvocationTargetException err3) {
System.out.println("Illegal access");
}
return wantToQuit;
}
[...] //some methods omitted
}
Player class:
public class Player
{
private String name;
private Room currentRoom;
private ArrayList<Item> items;
Player (String name, Room startingRoom)
{
this.name = name;
items = new ArrayList<Item>();
this.currentRoom = startingRoom;
printWelcome();
}
public void engage()
{
[...]
}
public void trade(Command command)
{
[...] }
public void goRoom(Command command)
{
[...] }
public void search(Command command)
{
[...] }
public void takeItem(Command command)
{
[...] }
public void dropItem(Command command)
{
[...] }
public void lock(Command command)
{
[...] }
public void unlock(Command command)
{
[...]
}
}
Try this.
pClass.getMethod(commandWord, Command.class)
Seems to me the problem is that you're looking for methods with no
parameters while these methods all seem to have a parameter of type Command.
For more details see here:
Class.getMethod JavaDoc

Categories