I have a problem as follows:
I've written a simple minimalistic Application that utilizes the SWT for the GUI.
In a specific tab, where it displays a table that get's filled with Informition via a REST Api Call. Additionaly, i have another method to export this table into a CSV-file.
This works absolutely fine. Now I need some kind of autoupdate/-export for which I implemented a Swing-Worker like this:
protected class AutoExportWorker extends SwingWorker<Integer, String> {
#Override
public Integer doInBackground() throws Exception {
System.out.println("Worker Start!");
while (true) {
System.out.println("In Loop");
//updateTable();
//exportToCSV();
for (int i = 0; i<interval;i++) {
System.out.println(interval - i);
Thread.sleep(1000);
}
}
}
The Class is a subclass of the Composite which views the table and holds the methods "updateTable()" and "exportsToCSV()". Now I'm aware that this Worker doesn't do much when I call these Methods but I can't figure out, how to do this correctly. Do you have any hints for me?
Best regards!
If you are using Eclipse RCP, you should use Jobs API. In plain SWT, there is no built-in solution. You need to use Display.asyncExec to update the table.
Related
System to System
Currently I'm developing CharacterSystem, GunSystem, BulletSystem using ashley framework. My problem is I dont know if this is the proper way of talking system to other system.
My CharacterSystem method onProcessEntity when the character attack is triggered I used getEngine().getSystem(GunSystem.class).trigger(true) and inside the GunSystem I have a method the Generate entity of a Bullet. While the BulletSystem handles the freeing of bodies, when outside the camera.
sub-question What is the proper way of creating Bullet class with ECS framework?
I use the Ashley ECS quite a lot for games and in a recent project (https://github.com/basimkhajwal/LSD) I ran into a similar situation. My method probably isn't standard and it may have issues which would occur in a different project setup but using an event queue has been a good solution for me.
In essence, you have an enum (in my case GameEvent) which handles all the different events needing to be passed around like PLAYER_DIED, LAUNCH_PLAYER and so on. I used Ashley's signals interface to create a simple queued store of events that a system can poll on each tick. As follows:
public class EventQueue implements Listener<GameEvent> {
private PriorityQueue<GameEvent> eventQueue;
public EventQueue() {
eventQueue = new PriorityQueue<GameEvent>();
}
public GameEvent[] getEvents() {
GameEvent[] events = eventQueue.toArray(new GameEvent[0]);
eventQueue.clear();
return events;
}
public GameEvent poll() {
return eventQueue.poll();
}
#Override
public void receive(Signal<GameEvent> signal, GameEvent event) {
eventQueue.add(event);
}
}
Next, in my GameWorld class, the one which loads the Ashley Engine and populates it with systems, I have a single Signal<GameEvent> which is the main backbone for my event queue. Here, like Listener<T>, Signal<T> is already part of Ashley.
Some systems then need to be able to fire into this signal / receive events from it so they take this Signal class in the constructor. The EntitySystem can then bind a listener or fire events which would then be passed on to other listeners. E.g. my LaserSystem class (simplified):
public class LaserSystem extends IteratingSystem implements Disposable, ContactListener {
...
private Signal<GameEvent> gameEventSignal;
private EventQueue eventQueue;
public LaserSystem(Signal<GameEvent> gameEventSignal) {
super(Family.all(LaserComponent.class).get(), Constants.SYSTEM_PRIORITIES.LASER);
this.gameEventSignal = gameEventSignal;
eventQueue = new EventQueue();
gameEventSignal.add(eventQueue);
}
...
#Override
public void beginContact(Contact contact) {
....
LaserComponent laserComponent = laserMapper.get(laser);
laserComponent.updateLaser = true;
if (other.getComponent(PlayerComponent.class) != null) {
gameEventSignal.dispatch(GameEvent.LASER_COLLISION);
}
}
}
Hopefully this makes sense, also feel free to read my project code for more example usage.
I never used Ashley as ECS but usually Systems should not communicate with each other.
Reason: When Systems would communicate they would not be independent of each other. Independent Systems allow you to freely add and remove them without having to worry the code breaks. The game logic probably breaks of course when a important Systems are missing.
Have a Factory (class) which does create the bullet entity. Then use the Factory in each System which can built new bullet entity.
Newbie at netbeans-platform.
How can I save my state from one execution to the next.
The netbeans platform elegantly remembers the state and position of all my windows. How can I add to that state some of my own data? Very much like Netbeans saves what projects are open and reopens them when it starts up, along with their state.
Ass suggested here I added the following to my TopComponent but it doesn't work. getPersistenceType is called but neither writeExternal n'or readExternal are called.
#Override
public int getPersistenceType() {
return TopComponent.PERSISTENCE_ALWAYS;
}
#Override
public void writeExternal(ObjectOutput oo) throws IOException {
super.writeExternal(oo);
}
#Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException {
super.readExternal(oi);
}
Comments here suggest tapping into readProperties and writeProperties but that doesn't feel right to me. I am not wanting to store Properties, I want to store State.
Some years ago I blogged about this, using the Session Storage feature of the Swing Application Framework in a NetBeans Platform application:
http://puces-blog.blogspot.ch/2009/04/netbeans-platform-meets-swing.html
The following 3 classes should provide the integration into the NetBeans Platform:
ModuleApplicationContext.java
ModuleLocalStorage.java
Modules.java
The referenced XProperties and JXTable you only need if you want support for SwingX classes such as JXTable.
To use this feature in your own module you need to initialize the context in your ModuleInstall class:
public class Installer extends ModuleInstall {
private static ModuleApplicationContext applicationContext;
#Override
public void restored() {
applicationContext = new ModuleApplicationContext(Modules.getModuleInfo(
Installer.class));
}
public static ModuleApplicationContext getApplicationContext() {
return applicationContext;
}
}
For a given contentPane you can then store the GUI session state using:
Installer.getApplicationContext().getSessionStorage().save(
getContentPanel(), SESSION_STORAGE_XML);
and restore the state using:
Installer.getApplicationContext().getSessionStorage().
restore(getContentPanel(), SESSION_STORAGE_XML);
Note: you need to set the component names of the relevant components
You can find the complete sample here: http://sourceforge.net/p/puces-samples/code/HEAD/tree/tags/sessionstate-1.0/
Also note however that development of the Swing Application Framework (JSR-296) has been withdrawn.
There is a fork called Better Swing Application Framework, but I haven't used it yet.
I also had some problems with this but finally I could fix it.
Annotate Your topcomponent class with #TopComponent.Description and set the right persistence type inside the annotation.
Your topcomponent class has to be serializable so,
every fields inside the topcompent have to be serializable or transient.
You can implement Your custom serialization with readExtern/writeExternal but it is not necessary, You can remove them.
If it still does not work check the log after You closed Your netbeans app and You will see why the platform could not serialize Your topComponent.
I am trying to initiate complex operation from a wizard.
It includes showing some view and then initiating of this view, which is long.
First way I was just calling view creation code from wizard's performFinish()
But this was not beautiful, since wizard was hanging on pressing Finish button. User would not see that execution began.
Other way I was trying to call Eclipse command from performFinish() and wrote handler to handle this command. I was thinking this will add some asynchronicity.
Unfortunately, I found no way to pass complex objects to a command. Method org.eclipse.core.commands.Command.executeWithChecks(ExecutionEvent) accepts ExecutionEvent, which allows to pass map of parameters, but values should all be of String type. ExecutionEvent is final and I am unable to add by own properties to it.
So what is the proper way to call complex operation from a wizard in Eclipse RCP?
UPDATE
If I am trying to use Job, I am getting org.eclipse.swt.SWTException: Invalid thread access
UPDATE 2
The same is with IRunnableWithProgress.
Probably I need put view initialization into another thread...
As an alternative to using a Job you can also get the wizard to display a progress bar at the bottom of the wizard while your code is running. To do this call
setNeedsProgressMonitor(true);
in the constructor of your Wizard.
In the performFinish use:
getContainer().run(true, true, new WorkClass());
where WorkClass is a class you define which implements IRunnableWithProgress:
class WorkClass implements IRunnableWithProgress
{
#Override
public void run(final IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException
{
// Your work here updating the progress monitor
}
}
Using this code your wizard will remain open showing a progress bar until the work is done. Using a Job the wizard will close and progress will be show in the status line or a pop-up dialog.
In both cases you need to use Display.asycnExec or Display.syncExec to update the UI:
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
// Work which updates the UI
}
});
If you have a long-running or complex task to execute at the end of the wizard then it's best to just use the wizard to gather and validate information. On performFinish() you can then use the Eclipse Jobs API to asynchronously execute the task.
Job job = new Job("name") {
#Override
protected IStatus run(IProgressMonitor monitor) {
// TODO Complex task
return Status.OK_STATUS;
}
};
job.schedule();
If you feed progress information back to the IProgressMonitor then the status of the job will be visible in the Eclipse Progress view.
To pass in information from the wizard you can either extend Job with your own class or just have the job code access fields or final variables in the wizard class.
I use JDK ScheduledThreadPoolExecutor to do schdule job. I give simple code as below.
class Job implements Callable<Void>{
public Long id;
#Override
public Void call() throws Exception {
if (!isOk(id)) {
return null;
}
_context.exe(id);
return null;
}
void setId(Long id) {
this.id = id;
}
}
Every time i add this job to schedule service:
public void schedule() {
Job job = new Job();
job.setId(1L);;
_scheduledExecutor.schedule(job, 1000, TimeUnit.MILLISECONDS) ;
}
this job will delay call context's exe method.
My Question: I want assert _context's exe method called or not? How can I do this?
What I do currently, I try to add log in call() method and verify UT by my eyes.
PS: For this UT, I also try to mock _context's exe method, but job run in other thread, So I cannot assert it in currently thread. anyone have idea to help me write assert for this case?
Currently I do below way, but I still think there better solution for this, Just I don't known.
_context is instance of Context, I extend from this class.
public class UTContext extends Context {
public UTTestCase utTestCase ;
#Override
public void exe(Long id) {
utTestCase.setIsCall(true);
}
public void setUtTestCase(UTTestCase utTestCase) {
this.utTestCase = utTestCase;
}
}
Then I will assert isCall var in UT.
Is any one have good idea for this , pls give me answer. Thank you very much.
You are testing a piece of the middle of the call hierarchy, namely the thread creator/dispatcher code. That means you have to drive the code from the top and test either from the top or the bottom. There are several patterns for how you do that.
Either you instrument the bottom (exe(id)) or you measure from the top. With the scheduling delay, measuring from the top becomes very difficult.
Does exe() have side effects? Is that side effect testable from your test code? Can you infer the operation of one invocation of exe()? Can you infer the invocation of more than one? If the answer to any of these is "no", then you will have to go further.
#RamonBoza has provided a good solution.
You could also create a testable version of class Job, thus:
class JobUT extends Job {
#Override
public Void call() throws Exception {
Void result = super.call();
// Report error if wrong return result
}
}
(I know there are problems with the above code as Void is not being handled properly. I'm not in a position to refactor your code.)
You may also achieve the same objective using Aspect Oriented Programming, where you intercept the call after it has completed and perform the same testing.
For asserting on multithreading I usually create 'N' threads, and assign a different value to set for each thread.
Then join them all and at the end just check if the data of each thread is ¿stored? for example.
Imagine, you create 1000 threads that stores an integer to a database, so after those 1000 threads has finished you have to check if in the database all the data is stored.
A more hard kind of test is for integration test and shall be perform with different scenarios and middleware (OpenNebula, Amazon cloud, etc).
After server day, I know how to verify it now. I attached other question for reference:
Assert times of expectLastCall
Service service = EasyMock.createMock(Service.class);
service.applyInitialDump(entities);
EasyMock.expectLastCall().times(100);
processor.processInitialDump(entities)
EasyMock.verify(service);
I am trying to write a GUI application using NetBeans, and I am getting increasingly tired of it..
I constructed a "Java Desktop Application" using NetBeans. It creates the main form as a org.jdesktop.application.FrameView descendent. I would like to know what is the proper way to add some code that is executed when the form is closed.
My current attempt so far is to add a WindowAdapter object using getFrame().addWindowListener in the constructor, which doesn't work. Because you can't call getFrame while the frame is not constructed yet. And I can't see it as an event somewhere i the GUI builder.
Java Desktop Application which is available in NetBeans IDE 6.9.1 is only for historical purposes and is not recommended for use in projects. The NetBeans IDE 6.9.1 also shows this warning when we try to create a new project using Java Desktop Application option.
Given that let me answer your question assuming you are still using the Swing Application Framework and you want to add a windowClosing listener to the Main Window.
When you create a Java Desktop Application you get three classes (assuming you typed DesktopApplication1 as the name of your application):
DesktopApplication1.java
DesktopApplication1AboutBox.java
DesktopApplication1View.java
To add the window closing listener, write the code in configureWindow method of the class DesktopApplication1 as follows:
#Override protected void configureWindow(java.awt.Window root) {
root.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
// write your code here
System.out.println("Window Closing");
}
});
}
with regards
Tushar Joshi, Nagpur
This is just an addition to Tushar's answer.
If you want to provide a confirmation dialog on the window closing, then you must change the default exit behavior by adding an ExitListener into the startup method and making the canExit method return false:
#Override
protected void startup() {
addExitListener(new ExitListener() {
public boolean canExit(EventObject event) {
return false;
}
public void willExit(EventObject event) {
}
});
show(new DesktopApplication1View(this));
}