Is it safe to hold on to a mapped TestObject in RFT? - java

Mapped TestObjects are generally accessed through getter methods, e.g.
button().click();
// Other code
button().click();
// ...
button().click();
Is there any reason why I shouldn't retrieve the TestObject once and reuse it? E.g.
GuiTestObject button = button();
button.click();
button.click();
button.click();
Or, stated differently, is there any reason why RFT generates getter methods instead of member variables?
The only potential reason I can think of would be to avoid tying up the application under test's memory, but that doesn't make any sense to me; Java finalizers aren't reliable so I doubt RFT is freeing up any resources when the TestObject is garbage collected. Plus, the fact that I can keep using the same mapped TestObject even if I close and re-open the application suggests RFT is re-finding (and subsequently unregistering) the test object every time I try to use it.
If there's no downside, why does every reference I find access TestObjects through getter methods exclusively? E.g. An Object-Oriented framework for IBM RFT, listings 2 and 3.

I think, first its because
button().click();
is cleaner/simpler code to a user than ..
GuiTestObject button = new GuiTestObject( getMappedTestObject("thebutton"));//This currently resides in the helper file.
button.click();
Second, the button() method can be passed an "Anchor" and a "Flag" also which is again implemented in the Helper class.so again
button(anchorobject,flags).click();
is simpler than having, one more button object
GuiTestObject button1 = new GuiTestObject(getMappedTestObject("thebutton"),anchor,flags);
button1.click();
In case you mean having something like..
GuiTestObject button = button();//where button() still is in helper class
button.click();
button.dosomthingelse();
Then we would need to specify the actual type of object for the button then we have a different TestObject type for Text controls and selects and trees etc.
With this existing approach the user can be completely unaware of existence of different types of TestObjects (GuiTestObject / TextGuiTestObject/SelectGuiSubitemTestObject) etc which is returned by the getter method of an object.
What we are dealing with in the script is a TestObject which resides in the playback process. TestObject is just a specification to find an actual object in the application and create a proxy for it (which resides in the application process) , and this proxy is what gets released once a particular action completes (click() for instance). However the TestObject is still valid , and as you have rightly said RFT would again find the object if you reuse the testobject. TestObject would be taken care of by the Garbage collector as and when required, user can further optimize that code I guess.
Finally to answer your question I am not aware what would be the downside of using the testobject you have. I don't think it will help you in terms of performance also though.
Try timing how much time it saves you if any by using an Object instead of the getter , try it on Java application which is statically enabled.

Related

Make method return unmodifiable object

I want a method that returns an object that is heavy to istantiate like an ObjectMapper, and since it's heavy to istantiate every time an object with new settings is made this value is cached away in a map, the object is meant to be shared among multiple threads so I don't want it to be modified from outside since this can lead to obvious problems.
I could wrap it inside another class and not give access to the methods that modify the settings, but the code would be very long. Is there any simple way to do this?
ObjectMapper here is just an example of the use case, could be a generic object.

Struts2 application scope instances

I've inherited a Struts2 project which needs some functionality addition. When I ran into de code to guess how the previous guy did things, I found out that if he wants a class to instantiate only once when the Tomcat server starts (because it has to read heavy loads of data from disk, but only once to get its config, for instance), he did this in the following way:
public class ExampleClass {
public ExampleClass(){//Read files and stuff to initialize}
public Object method(Object[] args){//The job to do}
}
And then, in the struts action which uses it he instantiates it this way:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass()
public String execute() {
//Do stuff every time the action is called
Object result = example.method(args);
// Do stuff with results
}
}
I know from servlet times that this does the trick, however, I feel like the guy who handled this before was as inexperienced in Struts2 as I am, so here comes my question:
Is this the proper way to do so according to style recommendations and best practices? Does struts2 provide a more controlled way to do so?
I found some answers related to simple parameters here, but I'm not sure if this is the proper way for objects like those? What would happen if ExampleClass instance is really heavy? I don't want them to be copied around:
How to set a value in application scope in struts2?
Some background about ExampleClass: When the constructor is called, it reads large sets of files and extracts it's configurations from them, creating complex internal representations.
When method() is called, it analyzes it's parameters using the rules, and outputs results to the user. This process usually takes seconds, and doesn't modify the previously initialized rule values.
This is running in Tomcat 7, however, I'm planning to upgrade to Tomcat 8.5 when everything is in place. I'd like to know if there are known issues about this regarding to this setup aswell (there are no other incompatibilities in the code).
BTW: He's not checking if ExampleClass is broken or anything like that, this definetly looks like a recipe to disaster xD. In fact, If I remove the source files, it is still trying to execute the method()... Poor soul...
Ideally, I need a way to instantiate all my application-level objects on start-up (they're the application itself, the rest is just a mere interface) in a way that if they fail Struts2 will tell Tomcat not to start that war, with the corresponding error logging and so on.
If Struts2 doesn't support this, which is the commonly accepted work-around? Maybe some Interceptor to check the object status and return to a error page if it hasn't been correctly instantiated? Execute a partial stop of tomcat from within?
All the objects of this project are thread safe (the only write operation inside them is performed on initialization), but I'd like to know best practices for Struts2 when objects are not so simple. What happens if a user can actually break one? (I know I should by any means avoid that, and I do, but mistakes happen, so I need a secure way to get through them, and get properly alerted, and of course I need a way to reinstantiate it safelly or to stop the whole service).
Right now, I can manually execute something like:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass();
private boolean otherIsBuildingExample = false;
public String execute() {
if(otherIsBuildingExample) return '500 error';
if(example==null || example.isBroken()){
otherIsBuildingExample = true;
example = new ExampleClass();
otherIsBuildingExample = false;
}
Object result = example.method(args);
// Do stuff with results
}
}
Indeed, this would be cleaner with Interceptors, or so, however, this sounds like a pain in the *** for concurrency, specially taking into consideration thay example takes several seconds to start, and that more requests can come, so more concerns to take into consideration, like: what if two people call if(otherIsBuildingExample) and the second one gets the value before the first one performs otherIsBuildingExample=true? Nothing good... If the class is simple enough, both will instantiate and the slower one will prevail, but if one instantiation blocks the other's resources... well, more problems.
The only clean solution I can think of is to make ExampleClass robust enough so you can repare it using its own methods (not reinstantiating) and make those thread safe in the common way (if 10 people try to repair it, only one will proceed, while the others are just waiting for the first to end to continue, for instance).
Or maybe everytime you call execute() you get a copy of example, so no worries at all about this?
I'm digging into struts documentation
Thanks in advance.

Java : reference one form from another form to append values

In my application I have a main form which has buttons to process other actions, for example my main form displays a list of all entities in my system, and a user is then able to select and then Add or Edit those entities in the application.
When a user presses "Add" a new JFrame is opened, allowing them to add to the system. This is all fine, however I am having a small problem which is affecting some functionality.
I wrote a CommandTracker which allows me to undo and redo operations, the library works fine however I am struggling to reference the CommandTracker object on my main form from other forms. (hopefully code shall convey my question better)
Main Form Declarations:
protected CommandTracker;
// This is instantiated in my constructor, trying to show less code to keep simple.
objCommandTracker = new CommandTracker();
This instantiates my new Command Tracker object within my main form, I would then like to reference this object from my subform so that I can append the next command fired in my sub form.
So far I have tried to resolve this by providing a reference to my main form within my subforms .java file
protected static MainMenu main_menu = null;
I then tried to access the command tracker as follows
// Run AddRequestCommand, through the command tracker
mainMenu.objCommandTracker.executeCommand(addCommand);
However, this results in a null pointer Exception being thrown, I assume this is because mainMenu has a null reference in its declaration. How do I go about passing the current active MainMenu instance to my subform?
Use of statics is never the way to solve something like this. The solution is to pass valid references where needed and to call appropriate methods on these references.
So in other words, if one class needs reference to another, then pass the reference in via a parameter, either a constructor parameter or a setter method parameter, use it to set a field, and then you are free to call methods on that reference in that class.
As an aside: at some other time we'll need to discuss the problems with shooting multiple JFrames at the user, and at your atypical use of the term "form" as if it had a standard meaning in the Swing library -- it doesn't, and so you'll want to use other clearer terms.

JPanel with anonymous EventListener - why doesn't GC destroy listener?

I have been perusing the open source code of JMapViewer. If anyone else wishes to look at it, check the SVN.
In a nutshell, the main class is JMapViewer, which is an extension of a JPanel. There is another very important class called DefaultMapController which acts as a MouseListener for the main class.
The first weird thing I noticed is that the viewer has no references to the controller. The JMapViewer constructor instantiates an anonymous instance of the DefaultMapController, like this:
public JMapViewer() {
// other stuff
new DefaultMapController(this);
}
This seems to me to be a poor design choice, since the controller has tons of methods (options, toggles, etc - example shown below), which now can not be accessed at all, so what good are they?
public void setMovementMouseButton(int movementMouseButton) {
// changes which mouse button is used to move the map
}
The controller does have a reference to the viewer as shown in the first snippet above, which is how it is able to exercise control.
However, then I thought of something even weirder! If this anonymous instance of the listener has no references, why is it allowed to even survive? Shouldn't the GC destroy it quickly? Or is GC smart enough to know that a listener class which references a live JComponent must also stay alive to work properly, even if it has no name for some strange reason?
So, two real questions:
why does GC not destroy object?
is this indeed a poor design choice, or is there some way I'm unaware of to access the controller from the class which instantiates the viewer?
I want to contribute to this open source library, and my first idea for a change is to change the JMapViewer class to have a field referencing its controller, and to change the constructor to assign the currently anonymous controller to this new field. But, I want to make sure I'm not ignorantly missing something. I have searched the entire codebase for the text DefaultMapController, and it only occurs in its own class definitions, and in the anonymous instantiations in the JMapViewer constructors.
EDIT:
It does indeed appear that there is a way to access the anonymous listeners, by using the java.awt.Component method getMouseListeners(). So technically in my application I could search this collection for instances of DefaultMapController, and use that to access the methods I need to use to change the controller options.
To play devil's advocate though, if I go with original idea and give the map a reference of its controller, now I have a sort of circular reference (map knows of controller and controller knows of map). Is this a bad idea?
The abstract parent, JMapController, holds a reference to the JMapViewer passed there by the DefaultMapController constructor:
public DefaultMapController(JMapViewer map) {
super(map);
}
Addendum: The map reference held by the controller is used to (selectively) add up to three controller references to the map's EventListenerList, discussed here. Any one of these would preclude GC. At least one salutary design benefit is that a concrete JMapController need only implement available interfaces.
As suggested in this MVC outline, it would be unusual to give the view a reference to the controller. In contrast, there's nothing wrong with letting the controller register as a listener to the view, as suggested here.
Note that only the no-argument JMapViewer constructor installs a DefaultMapController. You can use the alternate constructor, as noted in comments at line 57-59 in revision 29113 of Demo.java. A complete example is examined here.
1) Everything you know is that, if and when the VM deems it to be appropriate, it will collect some or all of the dead objects. The GC is not required to do anything.
2) The best thing is to ask to the maintainer of the library. Anyway, as a general rule, I would not bother to change anything unless there's a good reason to, e.g. if it sensibly improves readability, and would rather focus myself on real problems.
3) Not sure if that's the case, but, when you serialize a JComponent, you also serialize all of its fields. And you do not want to serialize a lot of unused stuff.

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources