JDeveloper ADF: CreateInsert auto committing? - java

I'm currently starting with ADF Faces technology as well as with JDeveloper. I have a .jspx page where I open a popup in which exists an ADF Form binded with a View Object. Whenever the popup opens it calls a createInsert action, but then some error messages popup as if somewhere a validation is being executed.
Things I've considered or tried so far:
The "SKIP VALIDATION" property of the page is set to TRUE. I don't
know what else to try.
Auto Submit property of each input are set to FALSE.
Consideration
I think the createInsert action is auto submitting but like I said I just started using these technologies a few days ago. So perhaps this "weird behaviour" is being caused by other settings I haven't considered yet.
Here's the code I use when the popup opens (PopUpFecthListener)
public void createInsert(PopupFetchEvent popupFetchEvent) {
try {
System.out.println("Inside function");
ADFUtil.invokeEL("#{bindings.CreateInsertVariable.execute}");
Util.getAppModuleImpl().getFurVariableView1().getCurrentRow().setAttribute("Estado", "I");
System.out.println("Function has been executed");
} catch (Exception e) {
Util.logErrorJava("Error", e.getMessage());
}
}
Here's the method in which I get the AppModuleImpl
public static AppModuleImpl getAppModuleImpl() {
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding vb = context.getApplication().createValueBinding("#{data}");
BindingContext bc = (BindingContext)vb.getValue(context);
DCDataControl dc = bc.findDataControl("AppModuleDataControl");
AppModuleImpl module = (AppModuleImpl)dc.getDataProvider();
return module;
}

I think you should try to use immediate attribute for you input controls.
For best understanding of immediate and validation mechanism read this article

Related

Combobox doesn't react to ".setValue()" nor ".select()"

This is my code:
comboBoxInstance.setInputPrompt("Something...");
comboBoxInstance.setNullSelectionAllowed(false);
Cookie comboCookie = getCookieByName("combo");
comboBoxInstance.select((comboCookie != null) ? comboCookie.getValue() : null);
final TextField textFieldInstance = new TextField("Textfield");
textFieldInstance.setInputPrompt("Something...");
Cookie tfCookie = getCookieByName("tf");
textFieldInstance.setValue((tfCookie != null) ? tfCookie.getValue() : null);
The problem is that the textfield works pretty well with the "Cookie setup". Only the combobox is refusing to work like it should.
The output is like this:
I've tried to use .setValue() instead of .select() but this has pretty much the same effect. I've also made sure that both the Cookie itself and the correct value are provided.
It may help to have a look at the part where the cookie is generated:
Cookie comboCookie = new Cookie("combo", comboBoxInstance.getValue().toString());
cookieProcessing(costcentreCookie); //<- sets maxage and vaadin related stuff (like adding the cookie)
Edit:
A few points to the data flow.
I'm generating a ComboBox with a SimpleJDBCConnectionPool's SQLContainer as the data container (coming from a TableQuery). Here's the initialization (executed in the constructor) in the combobox class:
private void init() throws SQLException {
this.setContainerDataSource(generateContainer());
this.setItemCaptionPropertyId("something");
}
The private method generateContainer() returns the SQLContainer of course.
This happens if I click on a particular button which opens up a dialog. This dialog is the fragment shown in the picture above. The combobox - of course - is part of it.
What one is supposed to do now is setting his data (get an item of the ComboBox) and hit save. The save button executes the routine to store the cookies. It's the code already mentioned above (Cookie comboCookie = new Cookie(...).
Okay, now the user is going to open up the dialog again. It's not important whether he reloads the application or just reopens the dialog (or does something else). It's basically the same in the app.
The dialog opens up and initializes the combobox (and the textfield) once again. However, this time it's supposed to gather the data out of the stored cookies. This is were the issue happens. This works well for the textfields (there are two but I've omitted one for shortening reasons) but not for the combobox, even tough it should've the exact same data as before. Hold in mind that it's the exact same class with the exact same initialization as when we stored the cookies in the first place.
I've the vague presumption, that it has to do something how the code is stacked. Maybe it hasn't finished loading the datacontainer while trying to set the appropriated value which then can't be found.
Edit2:
I've finally managed to reveal something. The ComboBox is indeed empty when the ".select()" is executed. However, this means, that the ComboBox is left untouched (it's only kind of "linked" to the datacontainer) until someone drops down the items. As soon as this happens, the items are there and I can possibly select them.
Is it supposed to work like this? O.o Am I able to fully initialize the combobox before I do something else? Something like:
private void init() throws SQLException {
this.setContainerDataSource(generateContainer());
this.setItemCaptionPropertyId("something");
this.gatherTheItems();
}
Edit3 - Test with ".setImmediate(true)"
I've changed the init to:
private void init() throws SQLException {
this.setContainerDataSource(generateContainer());
this.setItemCaptionPropertyId("SOMETHING");
this.setImmediate(true);
}
This didn't change anything. The combobox is still empty:
Finally! At first I've found a workaround which was like this:
for (Iterator it_IDS = combobox.getItemIds().iterator(); it_IDS.hasNext();) {
Object id = (Object) it_IDS.next();
if(id.toString().equals(cookie.getValue().toString())){
combo2.select(id);
break;
}
}
However, I couldn't believe that this was working since it doesn't change anything at the core problem. So I've investigated, that the RowID is built via a BigDecimal and voilĂ :
if(cookie != null) {
combobox.select(new RowId(new BigDecimal(cookie.getValue())));
}
I'm so happy right now :) Thanks for your patience kukis.
In case you came here because you're experiencing the same issue using a BeanItemContainer as datasource, bear in mind that you must implement both equals()and hashCode() methods on the underlying class for ComboBox's select() or setValue() methods to work.
You have plenty examples on Vaadin Forum on how to implement these methods:
ComboBox select value problem
Select or ComboBox does not Show Selected Property
Combobox select/setValue

Selenium Web driver gets blocked after getting a popup from another popup (IE driver)

I'm facing an issue when application I'm testing is opening a second level popup (I mean, a popup that rises another popup). I'm using Selenium for Java, version 2.42.2, with IE Driver.
My code currently manages all other flows and single pop ups windows, but when a second level popup appears my webdriver object gets irresponsive and just stuck in any method that try to get invoked. When this happens, I need to manually close the popup window and then driver method continues the execution of invoked method.
Maybe it worth mentioning, if I call the second popup from the main page (not from another popup) I am able to manage it without problems, so the problem seems to be related with the number of nested windows more than a specific problem for the page.
Take a look on below code:
String url = "/example.jsp"
int counter = 0;
boolean windowDetected = false;
// Waiting until page with given url gets detected
// It tries 10 times before it continues
while (counter++ < 10 && !windowDetected) {
waitForSeconds(1); // Just invokes Thread.sleep method,
System.out.println("before getting handlers, iteration " + counter + " of 10");
Set<String> handlers = driver.getWindowHandles();
System.out.println("after getting handlers, number of handlers: " + handlers.size());
for (String handler : handlers) {
try {
System.out.println("Moving to " + handler);
driver.switchTo().window(handler);
}
catch (NoSuchWindowException e) {
System.out.println("Window not found, it probably redirected to a different window");
break;
}
if (driver.getCurrentUrl().contains(url)) {
windowDetected = true;
waitForPageLoading(); // It just verify current page status to be completed
break;
}
}
}
I am able to position properly the driver in specific window with above code in other application pages, but when having the second level popup it just hangs on line Set handlers = driver.getWindowHandles(); that is the first method called on driver object after popup appeared. Similarly, if I had called another driver method like driver.getPageSource() the same would have happened in that method.
I am not able to change application structure (my scope is only for testing it), so doing changes in web application code is not an option for me now. I have read on different options like trying Robot class, but I think it will be difficult to implement with more complex pages and difficult to maintain.
Any idea of how can I solve this issue? Many thanks in advance.
Best regards,
Alberto.
After taking a look on IEDriverServer changelog, moving to a newer version of this driver solved the issue. Previous was 2.24.2, and now using 2.44. A slightly different behavior but that accomplishes what I wanted

Adding figures using contextual menu - Eclipse GEF

All,
I am creating a palette less eclipse plugin where am adding figures to the custom editor through the contextual menu, but am not finding a way to do it. Can anyone please guide me as to how to go about adding figures to editor dynamically through context menu i.e. adding actions/commands.
Since Eclipse GEF plugin development finds so less examples to look at, I am adding my solution so others find it useful. This code helps to render a node to the editor.
Source code for Action class to render figures to the editor:
public class AddNodeAction extends EditorPartAction
{
public static final String ADD_NODE = "ADDNODE";
public AddNodeAction(IEditorPart editor) {
super(editor);
setText("Add a Node");
setId(ADD_NODE); // Important to set ID
}
public void run()
{
<ParentModelClass> parent= (<ParentModelClass>)getEditorPart().getAdapter(<ParentModelClass>.class);
if (parent== null)
return;
CommandStack command = (CommandStack)getEditorPart().getAdapter(CommandStack.class);
if (command != null)
{
CompoundCommand totalCmd = new CompoundCommand();
<ChildModelToRenderFigureCommand>cmd = new <ChildModelToRenderFigureCommand>(parent);
cmd.setParent(parent);
<ChildModelClass> newNode = new <ChildModelClass>();
cmd.setNode(newNode);
cmd.setLocation(getLocation()); // Any location you wish to set to
totalCmd.add(cmd);
command.execute(totalCmd);
}
}
#Override
protected boolean calculateEnabled()
{
return true;
}
}
I think you need multiple different things here. Please remember that GEF would like you to have proper MVC pattern, where you have your own model, Figures as View and EditParts as controllers.
From the top of my head I would say that you need at least these things:
CreateCommand
contains all model level modifications that you need to
perform to add your new data to your
data model (undoable and transactional)
CreateAction
makes that CreateCommand instance, initializes it with current selection and executes that command in editdomain
ContextMenuProvider
Provides that CreateAction to context menu
If you happen to be using GMF the canonical mechanism will generate the editparts for you automatically when you make the model modifications inside a command, but if you are not using GMF, you must make sure that your own models and editparts are handling and refreshing the new item adding properly.
EDIT:
Ok, here is some code suggestion with playing around with requests.
public void run() {
// Fetch viewer from editor part (might not work, if not, try some other way)
EditPartViewer viewer = (EditPartViewer) part.getAdapter(EditPartViewer.class);
// get Target EditPart that is under the mouse
EditPart targetEditPart = viewer.findObjectAt(getLocation());
// If nothing under mouse, set root item as target (just playing safe)
if(targetEditPart == null)
targetEditPart = viewer.getContents();
// Make and initialize create request with proper information
CreateRequest createReq = new CreateRequest();
createReq.setLocation(getLocation());
createReq.setFactory(new OwnFactoryImplementation());
// Ask from target editpart command for this request
Command command = targetEditPart.getCommand(createReq);
// If command is ok, and it can be executed, go and execute it on commandstack
if(command != null && command.canExecute()) {
viewer.getEditDomain().getCommandStack().execute(command);
}
}
Now what happens is that editpart will be requested for creation, so the action itself doesn't know how the command works, what makes it objective agaist the command.
So to make things work, you need to install new EditPolicy to your EditPart. EditPolicies can be installed on EditParts createDefaultEditPolicies() function. This EditPolicy must react and return command when there is CreateRequest. This way any child can provide own kind of command for creating children for itself.
Here is a good image how it works (controller is EditPart):
Please ask if I can help you some more. I know that this looks bit more complex, but this makes your own life much more easier, and after you have done that, you actually understand Command-Request Pattern quite well, and it can be reused in many different places.

How can I tell if a JEditorPane/TextPane document or page has finished loading?

I'm trying to load a URL into a JEditorPane or JTextPane but the URL is a dynamically generated PHP page. I then want to process the output from the PHP page in my Java application. The PHP page will always output at least one String that I can use to check that it's generated correctly.
If I try and process the page straight after setting the page using
JEditorPane.setPage(URL);
if( outputTracker.getText().contains("desktop_process") )
it returns a blank HTML page, even if I specify a text/plain content type for the JEditorPane:
System.out.println(outputTracker.getText() );
I assume this is because the PHP page hasn't finished loading as the method below will return the correct output every time.
At the moment I'm setting the page and then starting a Swing Timer and checking every 200ms if the page contains the correctly generated String:
private void getPageBtnActionPerformed(java.awt.event.ActionEvent evt) {
outputTracker.setPage("URL_GOES_HERE?variables=x&y=a");
check_response_timer.start();
}
ActionListener checkAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if( outputTracker.getText().contains("desktop_process") ) {
System.out.println("Checking results...");
check_response_timer.stop();
process_response();
} else {
num_checks++;
System.out.println("Checking results...");
if( num_checks == 10 ) {
check_response_timer.stop();
checkLater = true;
responseLbl.setText("Connection timeout. Please click reconnect to check again.");
num_checks = 0;
}
}
}
};
private Timer check_response_timer = new Timer(200,checkAction);
This works fine.
At current server loads and the current complexity of the PHP pages being loaded the loop stops after the first iteration but it just seems a little inefficient and I don't want to have to keep checking if the page is going to take several seconds to load during heavy server loads or on more complex PHP pages.
I'm wondering if there's a better way to check that the page has finished loading.
I was wondering if I could use the JEditorPane.read(inputStream) method or set the page in a Swing Background Worker thread and then process the output of the PHP page when the worker's done() is called.
And is there a better way of loading the PHP output, reading it straight into a string from the dynamically generated output without the use of an editor pane as the editorpane isn't visible anyway?
Hope this is clear enough.
Thanks.
You can add a PropertyChangeListener to the editor pane:
editorPane.addPropertyChangeListener("page", ...);
However, this will only tell you when the main page is loaded. It won't tell you when images or other related files have finised loading.

How do you get selenium to recognize that a page loaded?

In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.):
Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com");
browser.start();
browser.open("http://www.google.com/webhp?hl=en");
browser.type("q", "hello world");
When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made.
How do you get selenium to recognize that the page has loaded when this error occurs?
I faced this problem quite recently.
All JS-based solutions didn't quite fit ICEFaces 2.x + Selenium 2.x/Webdriver combination I have.
What I did and what worked for me is the following:
In the corner of the screen, there's connection activity indicator.
<ice:outputConnectionStatus id="connectStat"
showPopupOnDisconnect="true"/>
In my Java unit test, I wait until its 'idle' image comes back again:
private void waitForAjax() throws InterruptedException {
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try {
if ("visibility: visible;".equals(
selenium.getAttribute("top_right_form:connectStat:connection-idle#style"))) {
break;
}
} catch (Exception e) {
}
Thread.sleep(1000);
}
}
You can disable rendering of this indicator in production build, if showing it at the page is unnecessary, or use empty 1x1 gifs as its images.
Works 100% (with popups, pushed messages etc.) and relieves you from the hell of specifying waitForElement(...) for each element separately.
Hope this helps someone.
Maybe this will help you....
Consider the following method is in page called Functions.java
public static void waitForPageLoaded(WebDriver driver) {
ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver,30);
try {
wait.until(expectation);
} catch(Throwable error) {
Assert.assertFalse(true, "Timeout waiting for Page Load Request to complete.");
}
}
And you can call this method into your function. Since it is a static method, you can directly call with the class name.
public class Test(){
WebDriver driver;
#Test
public void testing(){
driver = new FirefoxDriver();
driver.get("http://www.gmail.com");
Functions.waitForPageLoaded(driver);
}
}
When I do Selenium testing, I wait to see if a certain element is visible (waitForVisible), then I do my action. I usually try to use an element after the one I'm typing in.
Using 'openAndWait' in place of 'open' will do the trick.
From the website:
Many Actions can be called with the "AndWait" suffix, e.g. "clickAndWait". This suffix tells Selenium that the action will cause the browser to make a call to the server, and that Selenium should wait for a new page to load.
Enabling the 'multiWindow' feature solved the issue, though I am not clear why.
SeleniumServer(int port, boolean slowResources, boolean multiWindow)
SeleniumServer server = new SeleniumServer(4444, false, true);
Any clarification would be helpful.
I've run into similar issues when using Selenium to test an application with iFrames. Basically, it seemed that once the primary page (the page containing the iframes) was loaded, Selenium was unable to determine when the iframe content had finished loading.
From looking at the source for the link you're trying to load, it looks like there's some Javascript that's creating additional page elements once the page has loaded. I can't be sure, but it's possible that this is what's causing the problem since it seems similar to the situation that I've encountered above.
Do you get the same sort of errors loading a static page? (ie, something with straight html)
If you're unable to get a better answer, try the selenium forums, they're usually quite active and the Selenium devs do respond to good questions.
http://clearspace.openqa.org/community/selenium_remote_control
Also, if you haven't already tried it, add a call to browser.WaitForPageToLoad("15000") after the call to open. I've found that doing this after every page transition makes my tests a little more solid, even though it shouldn't technically be required. (When Selenium detects that the page actually has loaded, it continues, so the actual timeout variable isn't really a concern..
Not a perfect solution, but I am using this method
$t1 = time(); // current timestamp
$this->selenium->waitForPageToLoad(30);
$t2 = time();
if ($t2 - $t1 >= 28) {
// page was not loaded
}
So, it is kind of checking if the page was not loaded during the specified time, so it is not loaded.
another idea is to modify AJAX API (to add some text after AJAX actions).
After ajax action was finished, before return, set invisible field to TRUE, selenium will find it and read as green-light
in html:
<input type='hidden' id="greenlight">
in selenium
if(driver.findElement(By.id("greenlight")).getAttr("value").equals("TRUE")){
// do something after page loading
}
If you page has no AJAX, try to seek footer of page (I also use Junit fail(""), you may use System.err.println() instead):
element.click();
int timeout =120;
// one loop = 0.5 sec, co it will be one minute
WebElement myFooter = null;
for(int i=0; i<timeout; i++){
myFooter = driver.findElement(By.id("footer"));
if(myFooter!= null){
break;
}
else{
timeout--;
}
}
if(timeout==0 && myFooter == null){
fail("ERROR! PAGE TIMEOUT");
}

Categories

Resources