Problems when using robocode with JESS - eclipse

I'm attempting to use JESS in order to utilise a rule-based system for making a robot. I've got both robocode and the JESS .jar imported into Eclipse. Here's my code -
public class myRobot extends Robot {
Rete r = new Rete();
public void run() {
try {
String reset = "(reset)";
r.executeCommand(reset);
String enemyInfo = "(deftemplate enemyInfo (slot present) (slot energy) (slot name))";
r.executeCommand(enemyInfo);
while (true) {
String command = "(assert (enemyInfo (present no) (energy -1) (name none)))";
r.executeCommand(command);
}
} catch (JessException ex) {
System.err.println(ex);
}
}
public void onScannedRobot(ScannedRobotEvent e) {
try {
String command = "(assert (enemyInfo (present yes) (energy " + e.getEnergy() + ") (name " + e.getName() + ")))";
r.executeCommand(command);
} catch (JessException ex) {
System.err.println(ex);
}
}
}
I haven't added in any rules yet because I just wanted to check that robocode and JESS run properly together. When I fire this up, the robocode application opens up. But when I try adding this robot in a battle and starting it, the application just freezes up completely.
I can't access the robot's console to see what's wrong since it hangs just immediately after I try and start a battle. Since all my System.out.println() debugging statements are printed to the robot's console as opposed to the main one, I can't even figure out what's wrong. Any suggestions to get this to work?

The problem is, that the robocode application does not know the JESS library. You will need to include it in the jar of your exported robot.
How to include librarys to jars

Related

Java WatchService code works in Eclipse but same code fails in Tomcat in Docker

In Eclipse, a unit test fires up this code and when the watched file is altered, outputs the new text.
In Tomcat, it hangs where shown.
I've grovelled around online for quite some time trying to find anyone with a similar problem, but nothing showed up.
This is vanilla watcher code, and because it works fine in Eclipse, there must be a Tomcat-specific issue, but what?
The file is accessible to the code in Tomcat. It's not a permissions problem.
public class Foo extends Thread {
File watchedFile = <the watched file>;
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = watchedFile.getParentFile().toPath();
dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
#Override
public void run() {
while (true) {
WatchKey key;
try {
key = watcher().take(); <<< HANGS HERE IN TOMCAT, DOESN'T HANG HERE IN ECLIPSE.
} catch (InterruptedException | ClosedWatchServiceException e) {
break;
}
try {
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
WatchEvent<Path> pathEvent = (WatchEvent<Path>)event;
if (pathEvent.context().toString().equals(watchedFile.getName()) {
// Do something.
}
}
}
} catch (Exception e) {
throw new RuntimeException("Trouble: " + e.getMessage(), e);
}
if (!key.reset()) {
break;
}
}
}
}
UPDATE: . The problem was that I was writing to the file from outside Docker, so the change event wasn’t seen.
It’s similar to Java WatchService not generating events while watching mapped drives.

Eclipse plugin - getting the IStackframe object from a selection in DebugView

So, this is the problem I am stuck at for a few weeks.
I am developing an Eclipse plugin which fills in a View with custom values depending on a particular StackFrame selection in the Debug View.
In particular, I want to listen to the stackframe selected and would like to get the underlying IStackFrame object.
However, I have tried more than a dozen things and all of them have failed. So I tried adding DebugContextListener to get the DebugContextEvent and finally the selection. However, the main issue is that ISelection doesn't return the underlying IStackFrame object. It instead returns an object of type AbstractDMVMNode.DMVMContext. I tried getting an adapter but that didn't work out too. I posted this question sometime back also:
Eclipse Plugin Dev- Extracting IStackFrame object from selection in Debug View
Since then, I have tried out many different approaches. I tried adding IDebugEventSetListener (but this failed as it cannot identify stack frame selection in the debug view).
I tried adding an object contribution action but this too was pointless as it ultimately returned me an ISelection which is useless as it only returns me an object of class AbstractDMVMNode.DMVMContext and not IStackframe.
Moreover, I checked out the implementation of the VariablesView source code itself in the org.eclipse.debug.ui plugin. It looks like a few versions back (VariablesView source code in version 3.2), the underlying logic was to use the ISelection and get the IStackFrame. All the other resources on the internet also advocate the same. However, now, this scheme no longer works as ISelection doesn't return you an IStackFrame. Also, the source code for the latest eclipse Debug plugin (which doesn't use this scheme) was not very intuitive for me.
Can anyone tell how I should proceed ? Is hacking the latest Eclipse source code for VariablesView my only option ? This doesn't look like a good design practice and I believe there should be a much more elegant way of doing this.
PS: I have tried all the techniques and all of them return an ISelection. So, if your approach too return the same thing, then it is most likely incorrect.
Edit (Code snippet for trying to adapt the ISelection):
// Following is the listener implemnetation
IDebugContextListener flistener = new IDebugContextListener() {
#Override
public void debugContextChanged(DebugContextEvent event) {
if ((event.getFlags() & DebugContextEvent.ACTIVATED) > 0) {
contextActivated(event.getContext());
}
};
};
// Few things I tried in the contextActivated Method
//Attempt 1 (Getting the Adapter):
private void contextActivated(ISelection context) {
if (context instanceof StructuredSelection) {
Object data = ((StructuredSelection) context).getFirstElement();
if( data instanceof IAdaptable){
System.out.println("check1");
IStackFrame model = (IStackFrame)((IAdaptable)data).getAdapter(IStackFrame.class);
if(model != null){
System.out.println("success" + model.getName());
}
}
}
}
// Attemp2 (Directly getting it from ISelection):
private void contextActivated(ISelection context) {
if (context instanceof StructuredSelection) {
System.out.println("a");
Object data = ((StructuredSelection) context).getFirstElement();
if (data instanceof IStackFrame) {
System.out.println("yes");
} else {
System.out.println("no" + data.getClass().getName());
}
}
// This always execute the else and it prints: org.eclipse.cdt.dsf.ui.viewmodel.datamodel.AbstractDMVMNode.DMVMContext
}
// Attemp3 (Trying to obtain it from the viewer (similiar to object action binding in some ways):
private void contextActivated(ISelection context) {
VariablesView variablesView = (VariablesView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(IDebugUIConstants.ID_VARIABLE_VIEW);
if (variablesView != null) {
Object input = ((TreeViewer) variablesView.getViewer()).getInput();
if(input != null) System.out.println(input.getClass().getName());
if (input instanceof IStackFrame) {
System.out.println("success");
} else if (input instanceof IThread) {
System.out.println("success");
try {
IStackFrame[] stackFrames = ((IThread) input).getStackFrames();
for (IStackFrame iStackFrame : stackFrames) {
printVariables(iStackFrame);
}
} catch (DebugException e) {
e.printStackTrace();
}
}
}
}
While I am building this view to work with both JDT & CDT, I am testing it out on the C project. So, this might be the reason why I always get the returned object type as AbstractDMVMNode.DMVMContext. Should my implementation be different to handle both these cases ? I believe I should be building a generic view. Also, if AbstractDMVMNode.DMVMContext is CDT specific, I should I go about implementing it for the CDT case?

Random "404 Not Found" error on PasrseObject SaveAsynch (on Unity/Win)

I started using Parse on Unity for a windows desktop game.
I save very simple objects in a very simple way.
Unfortunately, 10% of the time, i randomly get a 404 error on the SaveAsynch method :-(
This happen on different kind of ParseObject.
I also isolated the run context to avoid any external interference.
I checked the object id when this error happen and everything looks ok.
The strange thing is that 90% of the time, i save these objects without an error (during the same application run).
Did someone already got this problem ?
Just in case, here is my code (but there is nothing special i think):
{
encodedContent = Convert.ToBase64String(ZipHelper.CompressString(jsonDocument));
mLoadedParseObject[key]["encodedContent "] = encodedContent ;
mLoadedParseObject[key].SaveAsync().ContinueWith(OnTaskEnd);
}
....
void OnTaskEnd(Task task)
{
if (task.IsFaulted || task.IsCanceled)
OnTaskError(task); // print error ....
else
mState = States.SUCEEDED;
}
private void DoTest()
{
StartCoroutine(DoTestAsync());
}
private IEnumerator DoTestAsync()
{
yield return 1;
Terminal.Log("Starting 404 Test");
var obj = new ParseObject("Test1");
obj["encodedContent"] = "Hello World";
Terminal.Log("Saving");
obj.SaveAsync().ContinueWith(OnTaskEnd);
}
private void OnTaskEnd(Task task)
{
if (task.IsFaulted || task.IsCanceled)
Terminal.LogError(task.Exception.Message);
else
Terminal.LogSuccess("Thank You !");
}
Was not able to replicate. I got a Thank You. Could you try updating your Parse SDK.
EDIT
404 could be due to a bad username / password match. The exception messages are not the best.

opennlp with netbeans is not giving output

How to use opennlp with netbeans. I made a small program as given in apache document but it is not working. I have set path to the opennlp bin as stated in the apache document but still i m not geting an output. it is not able to find .bin and hence SentenceModel model.
package sp;
public class Sp {
public static void main(String[] args) throws FileNotFoundException {
InputStream modelIn ;
modelIn = new FileInputStream("en-token.bin");
try {
SentenceModel model = new SentenceModel(modelIn);
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
}
}
}
The current working directory when you run in Netbeans is the base project directory (the one with build.xml in it). Place your .bin file there, and you should be able to open the file like that.

How to run ant from an Eclipse plugin, send output to an Eclipse console, and capture the build result (success/failure)?

From within an Eclipse plugin, I'd like to run an Ant build script. I also want to display the Ant output to the user, by displaying it in an Eclipse console. Finally, I also want to wait for the Ant build to be finished, and capture the result: did the build succeed or fail?
I found three ways to run an Ant script from eclipse:
Instantiate an org.eclipse.ant.core.AntRunner, call some setters and call run() or run(IProgressMonitor). The result is either normal termination (indicating success), or a CoreException with an IStatus containing a BuildException (indicating failure), or else something else went wrong. However, I don't see the Ant output anywhere.
Instantiate an org.eclipse.ant.core.AntRunner and call run(Object), passing a String[] containing the command line arguments. The result is either normal termination (indication success), or an InvocationTargetException (indicating failure), or else something else went wrong. The Ant output is sent to Eclipse's stdout, it seems; it is not visible in Eclipse itself.
Call DebugPlugin.getDefault().getLaunchManager(), then on that call getLaunchConfigurationType(IAntLaunchConfigurationConstants.ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE), then on that set attribute "org.eclipse.ui.externaltools.ATTR_LOCATION" to the build file name (and attribute DebugPlugin.ATTR_CAPTURE_OUTPUT to true) and finally call launch(). The Ant output is shown in an Eclipse console, but I have no idea how to capture the build result (success/failure) in my code. Or how to wait for termination of the launch, even.
Is there any way to have both console output and capture the result?
Edit 05/16/2016 #Lii alerted me to the fact that any output between the ILaunchConfigurationWorkingCopy#launch call and when the IStreamListener is appended will be lost. He made a contribution to this answer here.
Original Answer
I realize this is an old post, but I was able to do exactly what you want in one of my plugins. If it doesn't help you at this point, maybe it will help someone else. I originally did this in 3.2, but it has been updated for 3.6 API changes...
// show the console
final IWorkbenchPage activePage = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage();
activePage.showView(IConsoleConstants.ID_CONSOLE_VIEW);
// let launch manager handle ant script so output is directed to Console view
final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType type = manager.getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);
final ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, [*** GIVE YOUR LAUNCHER A NAME ***]);
workingCopy.setAttribute(ILaunchManager.ATTR_PRIVATE, true);
workingCopy.setAttribute(IExternalToolConstants.ATTR_LOCATION, [*** PATH TO ANT SCRIPT HERE ***]);
final ILaunch launch = workingCopy.launch(ILaunchManager.RUN_MODE, null);
// make sure the build doesnt fail
final boolean[] buildSucceeded = new boolean[] { true };
((AntProcess) launch.getProcesses()[0]).getStreamsProxy()
.getErrorStreamMonitor()
.addListener(new IStreamListener() {
#Override
public void streamAppended(String text, IStreamMonitor monitor) {
if (text.indexOf("BUILD FAILED") > -1) {
buildSucceeded[0] = false;
}
}
});
// wait for the launch (ant build) to complete
manager.addLaunchListener(new ILaunchesListener2() {
public void launchesTerminated(ILaunch[] launches) {
boolean patchSuccess = false;
try {
if (!buildSucceeded[0]) {
throw new Exception("Build FAILED!");
}
for (int i = 0; i < launches.length; i++) {
if (launches[i].equals(launch)
&& buildSucceeded[0]
&& !((IProgressMonitor) launches[i].getProcesses()[0]).isCanceled()) {
[*** DO YOUR THING... ***]
break;
}
}
} catch (Exception e) {
[*** DO YOUR THING... ***]
} finally {
// get rid of this listener
manager.removeLaunchListener(this);
[*** DO YOUR THING... ***]
}
}
public void launchesAdded(ILaunch[] launches) {
}
public void launchesChanged(ILaunch[] launches) {
}
public void launchesRemoved(ILaunch[] launches) {
}
});
I'd like to add one thing to happytime harry's answer.
Sometimes the first writes to the stream happens before the stream listener is added. Then streamAppended on the listener is never called for those writes so output is lost.
See for example this bug. I think happytime harry's solution might have this problem. I myself registered my stream listener in ILaunchListener.launchChanged and this happened 4/5 times.
If one wants to be sure to get all the output from a stream then the IStreamMonitor.getContents method can be used to fetch the output that happened before the listener got added.
The following is an attempt on a utility method that handles this. It is based on the code in ProcessConsole.
/**
* Adds listener to monitor, and calls listener with any content monitor already has.
* NOTE: This methods synchronises on monitor while listener is called. Listener may
* not wait on any thread that waits for monitors monitor, what would result in dead-lock.
*/
public static void addAndNotifyStreamListener(IStreamMonitor monitor, IStreamListener listener) {
// Synchronise on monitor to prevent writes to stream while we are adding listener.
// It's weird to synchronise on monitor because that's a shared object, but that's
// what ProcessConsole does.
synchronized (monitor) {
String contents = monitor.getContents();
if (!contents.isEmpty()) {
// Call to unknown code while synchronising on monitor. This is dead-lock prone!
// Listener must not wait for other threads that are waiting in line to
// synchronise on monitor.
listener.streamAppended(contents, monitor);
}
monitor.addListener(listener);
}
}
PS: There is some weird stuff going on in ProcessConsole.java. Why is the content buffering switched of from the ProcessConsole.StreamListener constructor?! If the ProcessConsole.StreamListener runs before this one maybe this solution doesn't work.