How to attach a new BrowserWindowOpener to a button, without destroying the button first? - vaadin

on Vaadin 7 I have the working code :
private void gridAttachmentsClickItemEventAction(ItemClickEvent event) {
// blablabla some code to get the data from the repository
byte[] data = bibocoAttachmentResponseEntity.getBody().getContent();
StreamResource.StreamSource source = convertByteArrayToStreamResource(data);
String filename = "c:\\droppdf\\"
+"temp"+bibocoAttachmentResponseEntity.getBody().getFileName()+LocalDate.now().toString();
StreamResource resource = new StreamResource(source, filename);
resource.setMIMEType("application/pdf");
resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + filename);
BrowserWindowOpener opener = new BrowserWindowOpener(resource);
opener.extend(btnAttachmentPreview);
}
When I click on a grid row, the data is collected from that grid
and code following on it gets the data byte[] from a repository by calling a service.
Afterwards, when the user clicks on btnAttachmentPreview a new browser tab opens
and shows the pdf (that's what's in the data byte[])
This works fine the first time, but when I select a new row in the grid,
the problem is that the second call does not set the listener to the button right.
It show the first data byte[] again in a new tab, not the current data ...
The method is accessed, the correct data[] has been loaded in the array the second time, I checked.
I believe the listener on the btnAttachmentPreview attached due the code
opener.extend(btnAttachmentPreview);
should be binned (empty'ed or nulled) first. But I have no reference to it as for as I can tell.
Problem is that I don't want to destroy the btnAttachmentPreview object.
(The btnAttachmentPreview is a global variable and is set to a layout that I may not change. I know, not nice, but it's a ancient product)
When I close the browser and restart and clicking another row, the right data byte[] is showed.
Anyone a clue ?
Any help appreciated

You can remove an extension using its remove() method, i.e. opener.remove();.
If you cannot easily structure your code to store a reference to the old opener so that you have it available when you want to add a new one, then you can use btnAttachmentPreview.getExtensions() to get a collection of all current extensions and then from that you can find the appropriate extension (if any) and call remove() on it.

Related

FileDownloader and checkbox, download selected items

We've created solution where user has a table with files, each entry has checkbox. He can select as many as he like and then click download button.
We are using such resource, it should allow dynamically download, depending on selected items
private StreamResource createResource(final IndexedContainer container) {
return new StreamResource(new StreamSource() {
#Override
public InputStream getStream() {
for (Object o : container.getItemIds()) {
CheckBox checkbox = (CheckBox) container.getItem(o).getItemProperty(C_CHECK_BOX).getValue();
if (checkbox.getValue()) {
selectedFiles.add(o);
}
}
// do some magic to get stream of selected files
}
}, "download.zip");
}
The problem is that only second and following click on button is giving expected restults.
It's turns out that FileDownoader is getting resource from server and then it is sending current status of component . It is the reason why first click is giving stale result.
Do you have any idea how to overcome this? Is it possible to force: first update component and then download the resource?
Many thanks
Pawel
CheckBox in Vaadin is non-immediate by default, which means that it won't send a request to server when the checkbox is checked (or unchecked) on the browser. Immediate components send queued non-immediate events also to server but it seems that FileDownloader doesn't cause an event that would send non-immediate checkbox values to server.
The only thing you need to do is to set your checkboxes to be immediate when you create those:
checkBox.setImmediate(true);
FileDownloader will not suit your needs. As you can read in the documentation:
Download should be started directly when the user clicks e.g. a Button without going through a server-side click listener to avoid triggering security warnings in some browsers.
That means you cannot dynamically generate download.zip file determined by checkboxes values because that requires a trip to server.
You have at least 2 options. Either create new FileDownloader and generate new Resource download.zip every time user make changes to the checkboxes. Or you can add simple ClickListener to you Button with this line of code:
getUI().getPage().open(resource, "_blank", false);
Related: Vaadin - How to open BrowserWindowOpener from a SINGLE BUTTON
There is also alternative solution to set checkBox.setImmediate(true); . It is possible to send current state of all components, just before click, instead of sending each checkBox change.
This solution is based on this answer: https://stackoverflow.com/a/30643199/1344546
You need to create file downloader button and hide it:
Button hiddenButton = new Button();
hiddenButton.setId(HIDDEN_ID);
hiddenButton.addStyleName("InvisibleButton");
StreamResource zipResource = createResource(container);
FileDownloader fd = new FileDownloader(zipResource);
fd.extend(hiddenButton);
Add css rule to your theme
.InvisibleButton {
display: none;
}
And then create another button, which 1st update state, and then click hidden button.
Button zipDownload = new Button("Download as ZIP file");
zipDownload.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(Button.ClickEvent event) {
Page.getCurrent().getJavaScript()
.execute(String.format("document.getElementById('%s').click();", HIDDEN_ID));
}
});

Behaviour of Table context menu in Vaadin 7.3 unclear

I have a simple use case: in a multi select Table
when the user selects 1 row, a context menu with two actions must be returned (DELETE and DOWNLOAD)
when the user selects more than one row, only the DELETE Action should be in the context menu
This is the code I use:
contactList.setMultiSelect(true);
final Action delete = new Action("Delete", FontAwesome.TIMES);
final Action download = new Action("Download", FontAwesome.DOWNLOAD);
contactList.addActionHandler(new Action.Handler() {
#Override
public Action[] getActions(Object target, Object sender) {
final Table table = (Table)sender;
// if Table is in multi select mode, getValues() returns Set of item id's
if (table.isMultiSelect() && ((Set)table.getValue()).size() > 1) {
return new Action[] {delete};
} else {
return new Action[] {delete, download};
}
}
...
I see that getActions() is called by the Table component every time a row selection is made. It returns the correct Action array. However, in the UI, only one context menu is used, independent of the actions returned.
This topic is not covered in The Book of Vaadin. There is an old question but the solutions is way too complicated and the solution suggested by Joonas is not working (in fact the case i describe here).
Its a well-known issue in Vaadin from version 6. Most people (including me) work-around this by using ContextMenu Addon

Dart web-ui not updated when data received from network

I have the following fragment in a web component:
<div id="mycodes">
<template iterate='code in codeList'>
{{code}}
</template>
</div>
And in a Dart file, codeList is populated when the user clicks on a button:
void onMyButtonClick(Event event) {
HttpRequest.getString('http://getData').then((response) {
mylist = json.parse(response);
for(var code in mylist){
codeList.add(code['c']);
}
}
The problem is that I don't see data on first click. I need to click the button twice to see data.
But if I fill codeList manually (not from network data) as shown below, then I see the data on first click:
void onMyButtonClick(Event event) {
codeList.add("data 1");
codeList.add("data 2");
}
}
I need the template to iterate after the network data is available. It appears that event loop has already done its job of painting a page before the network data becomes available through future object.
Is there a way to refresh the page after model is updated in dart?
The reason your codeList currently populates if you add it with the on-click event is because the current web_ui has 'watchers' which automatically are called when an event happens. You then populate the list synchronously. However one of the downfalls of watchers is exactly your use case, when the data is updated asynchronously then the watchers don't reflect changes in time.
As a result the watchers are being phased out and replaced with observables. Observables allow us to flag a variable to be watched for reassignment and when that happens it will cause the view to change. For example:
#observable int x = 0;
// ...
x = 1;
When the x = 1 is called later in the code it automatically triggers the views to update. This leaves us with one problem however. When you are adding to a list, you are not reassigning the value itself. As such, observables also offer a function to convert a list to an observable list (this also works for maps).
For instance if you changed your declaration of codeList to something like the following, then when you add to the list later it will update accordingly.
var codeList = toObservable([]); // Assuming it starts with an empty list
// or
var codeList = toObservable(_startCodeList); // if you already have a list
Also see the Dart Tutorial: Target 7 for more information on using #observable and toObservable.
For more in-depth information, check out the article on Observables and Data Binding
You need to mark the fields you want WebUi to monitor with the #observable annotation. Otherwise you only get the initial value not any subsequent updates.
You can do this either directly on the object declaration or you can make the entire class as observable and all its fields will then be observed.
For an example see http://www.dartlang.org/docs/tutorials/custom-elements/#using-two-way-data-binding

Editing a BrowserField's History

I have a BrowserField in my app, which works great. It intercept NavigationRequests to links on my website which go to external sites, and brings up a new windows to display those in the regular Browser, which also works great.
The problem I have is that if a user clicks a link to say "www.google.com", my app opens that up in a new browser, but also logs it into the BrowserHistory. So if they click back, away from google, they arrive back at my app, but then if they hit back again, the BrowserHistory would land them on the same page they were on (Because going back from Google doesn't move back in the history) I've tried to find a way to edit the BrowserField's BrowserHistory, but this doesn't seem possible. Short of creating my own class for logging the browsing history, is there anything I can do?
If I didn't do a good job explaining the problem, don't hesitate for clarification.
Thanks
One possible solution to this problem would be to keep track of the last inner URL visited before the current NavigationRequest URL. You could then check to see whether the link clicked is an outside link, as you already do, and if it is call this method:
updateHistory(String url, boolean isRedirect)
with the last URL before the outside link. Using your example this should overwrite "www.google.com" with the last inner URL before the outside link was clicked.
Here is some half pseudocode/half Java to illustrate my solution:
BrowserFieldHistory history = browserField.getHistory():
String lastInnerURL = "";
if navigationRequest is an outside link {
history.updateHistory(lastInnerURL, true);
// Handle loading of outer website
} else {
lastInnerURL = navigationRequest;
// Visit inner navigation request as normal
}
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/browser/field2/BrowserFieldHistory.html#updateHistory(java.lang.String, boolean)
I had a similar but a little bit different issue. Special links in html content like device:smth are used to open barcode scanner, logout etc and I wanted them not to be saved in BrowserFieldHistory. I found in WebWork source code interesting workaround for that. All that you need is throw exception at the end like below:
public void handleNavigationRequest( BrowserFieldRequest request ) throws Exception {
if scheme equals to device {
// perform logout, open barcode scanner, etc
throw new Exception(); // this exception prevent saving history
} else {
// standard behavior
}
}

WatiN: Print Dialog

I have a screen that pops up on load with a print dialog using javascript.
I've just started using WatiN to test my application. This screen is the last step of the test.
What happens is sometimes WatiN closes IE before the dialog appears, sometimes it doesn't and the window hangs around. I have ie.Close() in the test TearDown but it still gets left open if the print dialog is showing.
What I'm trying to avoid is having the orphaned IE window. I want it to close all the time.
I looked up DialogHandlers and wrote this:
var printDialogHandler = new PrintDialogHandler(PrintDialogHandler.ButtonsEnum.Cancel);
ie.DialogWatcher.Add(printDialogHandler);
And placed it before the button click that links to the page, but nothing changed.
The examples I saw had code that would do something like:
someDialogHandler.WaitUntilExists() // I might have this function name wrong...
But PrintDialogHandler has no much member.
I initially wasn't trying to test that this dialog comes up (just that the page loads and checking some values on the page) but I guess it would be more complete to wait and test for the existence of the print dialog.
Not exactly sure about your situation, but we had a problem with a popup window that also displayed a print dialog box when loaded. Our main problem was that we forgot to create a new IE instance and attach it to the popup. Here is the working code:
btnCoverSheetPrint.Click(); //Clicking this button will open a new window and a print dialog
IE iePopup = IE.AttachToIE(Find.ByUrl(new Regex(".+_CoverPage.aspx"))); //Match url ending in "_CoverPage.aspx"
WatiN.Core.DialogHandlers.PrintDialogHandler pdhPopup = new WatiN.Core.DialogHandlers.PrintDialogHandler(WatiN.Core.DialogHandlers.PrintDialogHandler.ButtonsEnum.Cancel);
using (new WatiN.Core.DialogHandlers.UseDialogOnce(iePopup.DialogWatcher, pdhPopup)) //This will use the DialogHandler once and then remove it from the DialogWatcher
{
//At this point the popup window will be open, and the print dialog will be canceled
//Use the iePopup object to manage the new window in here.
}
iePopup.Close(); // Close the popup once we are done.
This worked for me:
private void Print_N_Email(Browser ie)
{
//Print and handle dialog.
ie.Div(Find.ById("ContentMenuLeft")).Link(Find.ByText(new Regex("Print.*"))).Click();//orig
Browser ie2 = Browser.AttachTo(typeof(IE), Find.ByUrl(new Regex(".*Print.*")));
System.Threading.Thread.Sleep(1000);
PrintDialogHandler pdh = new PrintDialogHandler(PrintDialogHandler.ButtonsEnum.Cancel);
new UseDialogOnce(ie2.DialogWatcher, pdh);
ie2.Close();
}
You still might want to check your browser AutoClose property ie.AutoClose

Resources