What's the best way to get a return value out of an asyncExec in Eclipse? - eclipse

I am writing Eclipse plugins, and frequently have a situation where a running Job needs to pause for a short while, run something asynchronously on the UI thread, and resume.
So my code usually looks something like:
Display display = Display.getDefault();
display.syncExec(new Runnable() {
public void run() {
// Do some calculation
// How do I return a value from here?
}
});
// I want to be able to use the calculation result here!
One way to do it is to have the entire Job class have some field. Another is to use a customized class (rather than anonymous for this and use its resulting data field, etc.
What's the best and most elegant approach?

I think the Container above is the "right" choice. It could be also be genericized for type safety. The quick choice in this kind of situation is the final array idiom. The trick is that a any local variables referenced from the Runnable must be final, and thus can't be modified. So instead, you use a single element array, where the array is final, but the element of the array can be modified:
final Object[] result = new Object[1];
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
result[0] = "foo";
}
}
System.out.println(result[0]);
Again, this is the "quick" solution for those cases where you have an anonymous class and you want to give it a place to stick a result without defining a specific Container class.
UPDATE
After I thought about this a bit, I realized this works fine for listener and visitor type usage where the callback is in the same thread. In this case, however, the Runnable executes in a different thread so you're not guaranteed to actually see the result after syncExec returns. The correct solution is to use an AtomicReference:
final AtomicReference<Object> result = new AtomicReference<Object>();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
result.set("foo");
}
}
System.out.println(result.get());
Changes to the value of AtomicReference are guaranteed to be visible by all threads, just as if it were declared volatile. This is described in detail here.

You probably shouldn't be assuming that the async Runnable will have finished by the time the asyncExec call returns.
In which case, you're looking at pushing the result out into listeners/callbacks (possibly Command pattern), or if you do want to have the result available at a later in the same method, using something like a java.util.concurrent.Future.

Well, if it's sync you can just have a value holder of some kind external to the run() method.
The classic is:
final Container container = new Container();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
container.setValue("foo");
}
}
System.out.println(container.getValue());
Where container is just:
public class Container {
private Object value;
public Object getValue() {
return value;
}
public void setValue(Object o) {
value = o;
}
}
This is of course hilarious and dodgy (even more dodgy is creating a new List and then setting and getting the 1st element) but the syncExec method blocks so nothing bad comes of it.
Except when someone comes back later and makes it asyncExec()..

Related

Wicket: AjaxRequestTarget vs onModelChanged

I'm working on a code in a wicket project, where the original devs used the onModelChanged() method quite a lot in Ajax request handling methods. I, for one, however am not a strong believer of this implementation.
In fact, I can't think of any examples, where calling the target.add(...) is inferior to calling the onModelChanged method.
Am I missing some key concepts here?
Example:
public MyComponent extends Panel {
public MyComponent(String id, Component... componentsToRefresh) {
add(new AjaxLink<Void>("someId") {
#Override
public void onClick(AjaxRequestTarget target) {
// some logic with model change
for(Component c: componentsToRefresh) {
c.modelChanged();
}
target.add(componentsToRefresh);
}
};
}
}
Now, there are a couple of things I don't agree with, the very first is the componentsToRefresh parameter, the second is (as the question suggests), the fact that we called c.modelChanged() on all components in that array. My guess would be that it is completely un necessary and instead of a parameter in the constructor, one should just write an empty function in MyComponent and override it, and put the necessary components in there when needed.
I would suggest to use Wicket Event system instead. That is, whenever the AjaxLink is clicked you will broadcast an event:
send(getPage(), Broadcast.BREATH, new MyEventPayload(target));
This will broadcast the event to the current Page and all its components.
Then in any of your components you can listen for events:
#Override
public void onEvent(IEvent event) {
Object payload = event.getPayload();
if (payload instanceof MyEventPayload) {
((MyEventPayload) payload).getTarget().add(this); // or any of my sub-components
event.stop(); // optionally you can stop the broadcasting
}
}
This way you do not couple unrelated components in your application.
See Wicket Guide for more information.

Bukkit How to change an int in the config file then be able to change it again without reloading (Custom config file class.))

Okay so I am making a custom feature for my OP-Prison server, one of the things that I need to do is get an integer from the players.yml file, check if it is >= one, if it is take away one, save it and then if it is still above one then they can repeat the action untill it's 0.
The issue comes with the fact that I have to restart the server for the file to change, and even when I do, it will only go down by one integer at a time, before having to reload it again.
GUI Creation code:
Main main = Main.getPlugin(Main.class);
#SuppressWarnings("unused")
private FileControl fc;
#SuppressWarnings("unused")
private FileControl playerfc;
public static String inventoryname = Utils.chat(Main.pl.getFileControl().getConfig().getString("Backpacks.White.InventoryName"));
public List<Player> WhiteOpened = new ArrayList<>();
public static Inventory whiteBackpack(Player player) {
Inventory whiteBackpack = Bukkit.createInventory(null, 27, (inventoryname));
UUID uuid = player.getUniqueId();
whiteBackpack.setItem(10,
new ItemCreator(Material.INK_SACK).setData(8)
.setDisplayname(Utils.chat("&fCommon Packages &8ยป &f&l" + Main.pl.getPlayerFile().getConfig().getInt("Users." + uuid + ".Packages.Common")))
.getItem());
return whiteBackpack;
}
Code for updating the config + item when the Commonpackage is clicked:
#EventHandler
public void whiteBackpackInteract(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
UUID uuid = player.getUniqueId();
ItemStack clicked = event.getCurrentItem();
String title = event.getInventory().getName();
if (title.equals(inventoryname)) {
// Making it so that the item cannot be moved
event.setCancelled(true);
if (clicked != null) {
if (event.getSlot() == 10) {
// Getting the user's common packages section in the config and checking if it is greater than or equal to 1.
if (Main.pl.getPlayerFile().getConfig().getInt("Users." + uuid + ".Packages.Common") >= 1) {
// Saving the user's common package section to 'currentCommon'
Integer currentCommon = Main.pl.getPlayerFile().getConfig().getInt("Users." + uuid + ".Packages.Common");
// Taking away one from 'currentCommon' and saving it to 'newCommon'
Integer newCommon = currentCommon - 1;
// Getting the 'players.yml' file
File file = new File(main.getDataFolder(), "players.yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
// Checking if the current common keys is greater than or equal to 1
if (currentCommon >= 1) {
try {
//Now, Here's where the error lies.
//Gets the player's common package count and sets it to the 'newCommon' count
config.set("Users." + uuid + ".Packages.Common", newCommon);
//Saves the players.yml file
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
// Updates the inventory they're currently in (Atleast it's meant to...)
player.updateInventory();
// Sends them a message (This is just for testing purposes, making sure it's working.)
player.sendMessage(Utils.chat("&8(&9Vexil&8) &fCommon Package"));
}
}
}
}
}
}
If there is any other code that you need, just ask I'll happily provide it for you.
Right now, you need to restart the server for it to save the data to the file. This should not happen, since you are calling the method config.save(file). The following is simply speculation, but it's the only cause that I think can easily explain what is going on.
In the object that is returned by getPlayerFile().getConfig(), there is likely a variable that stores a FileConfiguration object. That variable houses all the data from the players.yml file. In your whiteBackpackInteract() method, you load the data all over again. You then continue on to write to this NEW FileConfiguration variable, rather than the one that is stored in getPlayerfile().getConfig(). Since you then proceed to save to the file directly, the variables stored in the getPlayerfile().getConfig() is never told that you changed some values around. To fix this, you need to change the following:
config.set("Users." + uuid + ".Packages.Common", newCommon);
config.save(file);
to this:
Main.pl.getPlayerFile().getConfig().set("Users." + uuid + ".Packages.Common", newCommon);
Main.pl.getPlayerFile().getConfig().save(file);
and then delete this line of code:
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
This should solve your problem entirely. If it does not, I would recommend not using your friend's custom config API and instead just use the ones that are built in. Using third party code that you don't properly understand can very often lead to problems such as this.
The following are not the bugs, but are suggestions to help improve your code:
You should be sure to put your comments ABOVE or to the RIGHT over the code they describe. People read from top to bottom, so the comments (before I made the suggested edit to your post) were all below the code they describe.
Typically, you want to try to make sure that if code doesn't need to be run, it isn't. Since the int newCommon is not used until inside that if statement, you should move it in there.
You are using Main.getPlugin();
Now while that doesn't seem like such a bad thing, your getting an unassigned variable, I have no idea how it is working but you're assigning Main to Main. There are 2 proper ways to actually get the main class.
The first, and generally best way, is to use dependency injection.
So basically,
public class Main extends JavaPlugin {
#Override
public void onEnable() {
BackpackListener listener new Backpacklistener(this);
getServer().getPluginManager().registerEvents(listener, this);
}
}
public class BackpackListener implements Listener {
private Main instance;
private BackpackUtil util;
public BackpackListener(Main instance) {
this.instance = instance;
util = new BackpackUtil();
}
#EventHandler
public void onClick(InventoryClickEvent event) {
//code
util.whiteBackpack(instance);
}
public class BackpackUtil {
public Inventory whiteBackpack(Main instance) {
FileConfiguration config = instance.getConfig();
//Do things
instance.saveConfig();
}
}
The next way you can do it is less optimal, and frowned upon, but still an easier option.
public class Main() {
public static Main instance;
#Override
public void onEnable() {
instance = this;
}
}
public class ConfigHelper() {
Main instance = Main.instance;
FileConfiguration config = instance.getConfig();
//Do things
instance.saveConfig();
}
It's good to get out of the habit of using the second method (It's called a singleton), because normally the main class will change, or have multiple instances, etc... but with Spigot there can only be one main instance and one thread.

Target a Object Variable in a different Class

So, without posting my entire project in here, I will sum it up as best I can:
class Program
{
static void Main(string[] args)
{
Thing one = new Thing();
one.addTimer(10);
one.addTimer(4);
one.addTimer(2);
one.addTimer(8);
}
}
class Counter
{
private int Seconds;
private int TimerNum;
public Counter(int SecondsX)
{
Seconds = (SecondsX * 1000);
}
public void TimerCall(){
Thread.sleep(Seconds);
CounterCallBack();
}
public void CounterCallBack()
{
Console.WriteLine("Timer " + TimerNum + " Done");
//Then the time is up the call back is executed
//The issue I am having is how do I trigger the next timer for the list timers to go from hear automatically. It would send back TimerNum to Thing.Continue
}
}
class Thing
{
List<int> timers = new List<int>();
public Thing()
{
}
public void addTimer(new Timer(int SecondsToAdd))
{
timers.Add(SecondsToAdd);
}
public void StartTimers(){
timers[0].TimerCall();
}
public void Continue(int LastRun){
if(timers.count()-1>= LastRun){
timers[LastRun].TimerCall();
}
}
}
So I need to access the Continue method from counter to kick off the next timer.
Or I need to find a way to do the same thing.
However, the user needs to be able to edit, add, and remove timers (Which happens from the Program class)
Remember that in my program (this is a simplified version) Counter is a timer Call and CallBack that runs asynchronously.
Is it even possible to do? Or do I need to scrap this approach and start from square one?
Also, I know this is rough, but this a project is for charity and I plan to clean it up once I get this prototype working. Also I am 16. So please, any help you can give would be well appreciated.
Okay It's a dirty answer but I am going to Use a dictionary to store the Object variables, and have an assessor method that is passed the ID of Correct set of timers, and the Index of the next timer to run. That then calls the next timer, and so on and so fort.
Dirty but functional for a Prototype.

How do I simplify these NUNit tests?

These three tests are identical, except that they use a different static function to create a StartInfo instance. I have this pattern coming up all trough my testcode, and would love
to be be able to simplify this using [TestCase], or any other way that reduces boilerplate code. To the best of my knowledge I'm not allowed to use a delegate as a [TestCase] argument, and I'm hoping people here have creative ideas on how to make the code below more terse.
[Test]
public void ResponseHeadersWorkinPlatform1()
{
DoResponseHeadersWorkTest(Platform1StartInfo.CreateOneRunning);
}
[Test]
public void ResponseHeadersWorkinPlatform2()
{
DoResponseHeadersWorkTest(Platform2StartInfo.CreateOneRunning);
}
[Test]
public void ResponseHeadersWorkinPlatform3()
{
DoResponseHeadersWorkTest(Platform3StartInfo.CreateOneRunning);
}
void DoResponseHeadersWorkTest(Func<ScriptResource,StartInfo> startInfoCreator)
{
ScriptResource sr = ScriptResource.Default;
var process = startInfoCreator(sr).Start();
//assert some things here
}
Firstly, I don't think the original is too bad. It's only messy if your assertions are different from test case to test case.
Anyway, you can use a test case, but it can't be done via a standard [TestCase] attribute due to using more complicated types. Instead, you need to use a public IEnumerable<> as the data provider and then tag your test method with a [TestCaseSource] attribute.
Try something like:
public IEnumerable<Func<ScriptResource, StartInfo>> TestCases
{
get
{
yield return Platform1StartInfo.CreateOneRunning;
yield return Platform2StartInfo.CreateOneRunning;
yield return Platform3StartInfo.CreateOneRunning;
}
}
[TestCaseSource("TestCases")]
public void MyDataDrivenTest(Func<ScriptResource, StartInfo> startInfoCreator)
{
ScriptResource sr = ScriptResource.Default;
var process = startInfoCreator(sr);
// do asserts
}
}
This is a more concise version of the standard pattern of yielding TestCaseData instances containing the parameters. If you yield instances of TestCaseData you can add more information and behaviours to each test (like expected exceptions, descriptions and so forth), but it is slightly more verbose.
Part of the reason I really like this stuff is that you can make one method for your 'act' and one method for your 'assert', then mix and match them independently. E.g. my friend was doing something yesterday where he used two Actions to say ("when method Blah is called, this method on the ViewModel should be triggered"). Very terse and effective!
It looks good. Are you looking to add a factory maybe ? Or you could add these methods to a Action List(in test setup) and call first action delegate, second action delegate and third action delegate.

Fundamental GWT asynchronous call misunderstanding

I seem to be suffering from some fundamental misunderstanding of the way that GWT async calls work and/or how widgets are updated upon receipt of a callback.
I've created the two interfaces as well as the implementation and they seem to be communicating with one another. I make this claim based on reasonable looking data observed while stepping through with the eclipse debugger: the result variable in the onSuccess method below contains what I expect it to and the grid that I am attempting to populate ends up being filled with the data from results upon exit from the loop. However when the onSuccess call returns, no grid is displayed in my GUI as per the uhpScrollPanel.setWidget(uhpGrid) call, and no exceptions of any sort are thrown.
I must be be overlooking something obvious, has anyone got any ideas about where to look?
final ScrollPanel uhpScrollPanel = new ScrollPanel();
uhpVert.add(uhpScrollPanel);
uhpScrollPanel.setSize("100%", "100%");
//build and populate grid
UpdateHistoryServiceAsync uhpService = UpdateHistoryService.Util.getInstance();
uhpService.getUpdateHistory(new AsyncCallback<List<UpdateHistoryEntryBean>>() {
public void onFailure(Throwable caught) {
System.out.println("OnFailure");
caught.printStackTrace();
final Label uhpErrorLabel = new Label("Server Unable to Grab History...");
uhpScrollPanel.setWidget(uhpErrorLabel);
uhpErrorLabel.setSize("100%", "100%");
}
public void onSuccess(List<UpdateHistoryEntryBean> result) {
int length = result.size();
final Grid uhpGrid = new Grid();
uhpScrollPanel.setWidget(uhpGrid);
uhpGrid.setBorderWidth(1);
uhpGrid.setSize("100%", "100%");
uhpGrid.resize(length, 3);
int i = 0;
for (UpdateHistoryEntryBean entry : result) {
uhpGrid.setText(i, 0, String.valueOf(entry.getSourceId()));
uhpGrid.setText(i, 1, entry.getTitle());
uhpGrid.setText(i, 2, entry.getBody());
i++;
}
}
});
Your onSuccess() method is not defined correctly, as a parameter it receives an Object, and you must downcast it afterwards.
Meaning, the signature should be:
public void onSuccess(Object result)
After that, you can explicitly downcast the object you know you got back like so:
List<UpdateHistoryEntryBean> resultList = (List<UpdateHistoryEntryBean>) result;
Well it turns out that the quick fix is to add the grid to a VerticalPanel rather than a ScrollPanel. The question now becomes - why should that matter, and how do we get around this dilemma?