I am taking my first steps with Apache Wicket and ran into the following problem. I have a ListView that displays a "delete" link right next to its entries. When the delete link is clicked, the entity represented by the list item is deleted from the database but the list itself does not get updated until I reload the page manually in the browser.
IModel<List<SampleEntity>> sampleEntityListModel = new LoadableDetachableModel<List<SampleEntity>>() {
#Override
protected List<SampleEntity> load() {
return mSampleEntityBA.findAll();
}
};
mListview = new ListView<SampleEntity>("listview", sampleEntityListModel) {
#Override
protected void populateItem(final ListItem<SampleEntity> item) {
item.add(new Label("listlabel", new PropertyModel<String>(item.getModelObject(),
"text")));
item.add(new Link<SampleEntity>("deleteLink", item.getModel()) {
#Override
public void onClick() {
mSampleEntityBA.delete(item.getModelObject());
}
});
}
};
When onClick called, item.getModelObject() pulls from the sampleEntityListModel which in turn calls mSampleEntityBA.findAll(). The model object of sampleEntityListModel will be cached for the duration on the request cycle (until it is detached - which is usually what you want) and is not aware of the call to delete().
In order to refresh the sampleEntityListModel, add a sampleEntityListModel.detach() call just after the delete (sampleEntityListModel must be made final, but this will not cause any extra state to be serialized). This will cause the model to fetch a fresh set of data when the list view is rendered later in the request cycle.
You probably want an AjaxLink instead of that Link, and then you have to make the list refresh, using the tactics described here, possibly adjusting a bit for the fact that the wiki has Wicket 1.3 code instead of 1.4.
But you might also be better off with a different repeater, such as a RefreshingView or a DataView. There are some examples of assorted repeaters here. While none of them are exactly what you're looking for, looking at that code might help.
looks like the problem is that your mSampleEntityBA.findAll(); is returning incorrect data. hard to help without seeing more code.
on a different note, you should really be using DataView when working with database-backed lists.
You might also want to check out JQGrid from the wiQuery project instead of DataView.
Related
Wicket 6 no longer keeps feedback messages in session. Now they are attached to components, which I think is great move but I approach an issue connected with that. I used to remove all feedback messages that were related to the specific form like this :
Session.get().getFeedbackMessages().clear(new ContainerFeedbackMessageFilter(panelForm));
Unfortunetly right now I can't clear it like this:
panelForm.getFeedbackMessages().clear();
For obvious reasons - they are attached to components inside form.
So is there a way to get those feedback messages by only accesing (in my case) panelForm or my only way to go is to call getFeedbackMessages() on all of my components (panelForm.component1, panelForm.component2 etc)?
use FeedbackCollector as in example:
new FeedbackMessagesModel(this) {
#Override
protected List<FeedbackMessage> collectMessages(Component panel, IFeedbackMessageFilter filter) {
return new FeedbackCollector(YourComponent.this.getParent()) {
#Override
protected boolean shouldRecurseInto(Component component) {
return true; // your citeria here
}
}.setIncludeSession(false).collect(filter);
}
};
Yes. You should use FeedbackCollector. Collect the messages and mark them as rendered.
I have been trying to debug why my DropDownChoice in a simple form with just the DropDown and a Submit Button hasn't been working correctly for hours now.
It has a very weird behaviour. Where the first value selected in the drop down choice is sent successfully to the server after which any other choice select is not updated by the model. ie if I have a List persons, and I select the 2nd person, it submits this successfully. However, on select of another person and trying to submit it again it keeps showing the first selected option.
Snippets of code here:
ChoiceRenderer<Empowerment> empowermentChoiceRenderer = new ChoiceRenderer<>("name", "id");
final DropDownChoice<Empowerment> empowermentDropDownChoice =
new DropDownChoice<>("empowerment", new PropertyModel<Empowerment>(this, "empowerment"), empowermentList, empowermentChoiceRenderer);
empowermentDropDownChoice.setRequired(true);
add(empowermentDropDownChoice);
Only way I am able to get a decent behaviour is if I set the empowerment variable above to null. In this case, on submit the empowerment is reinitialised to null and then a new submit works correctly.
empowerment is just a JPA entity.
I'll be glad to know if this is a known issue. I experienced it in wicket 6.9.1 and wicket 6.12
Finally, found the solution to the problem. Above code is correct, but problem lied in the entity class itself - Empowerment needs to implement Equals and Hashcode correctly.
The DropDownChoice works just fine after this.
Add an OnChangeAjaxBehavior to your DropDownChoice. This will update the model value on every selection change you make on the drop down:
empowermentDropDownChoice .add(new OnChangeAjaxBehavior() {
#Override
protected void onUpdate(AjaxRequestTarget art) {
//just model update
}
});
In a Wicket app, I have a modal dialog that contains a simple form and a button. User enters values (report parameters), and then clicks the button which starts the download of a report file (typically a PDF). (All form values are required, and Wicket's validation mechanism is used to make sure user entered them before the download can start.)
Maybe this is better explained with a picture:
I'm using here a jQuery UI Dialog (instead of Wicket's ModalWindow which felt a lot clumsier and uglier from user's perspective).
Everything is pretty much working, except closing the dialog when/after clicking the download button.
Current version (irrelevant bits omitted):
public class ReportDownloadLink extends Link {
public ReportDownloadLink(String id, ReportDto report) {
super(id);
this.report = report;
}
#Override
public void onClick() {
IResourceStream resourceStream = new AbstractResourceStreamWriter() {
#Override
public void write(OutputStream output) {
try {
reportService.generateReport(output, report);
} catch (ReportGenerationException e) {
// ...
}
}
#Override
public String getContentType() {
// ...
}
};
ResourceStreamRequestTarget target =
new ResourceStreamRequestTarget(resourceStream, report.getFileName());
getRequestCycle().setRequestTarget(target);
}
The dialog is a Wicket Panel (which makes use of ReportDownloadLink above), which we put in a certain div, and then when a report is selected in a list, the dialog is opened from an AjaxLink's onClick() quite simply like this:
target.appendJavascript(String.format("showReportExportDialog('%s')", ... ));
Which calls this JS function:
function showReportExportDialog(dialogTitle) {
$("#reportExportPanelContainer").dialog(
{modal:true, draggable:true, width: 320, height: 330, title: dialogTitle}
);
}
Some options:
Make ReportDownloadLink extend something else than Link, perhaps, and/or find an appropriate method to override which would allow me to execute the tiny bit of JavaScript needed to close the jQuery Dialog.
Investigate jQuery + Wicket libraries (such as jqwicket or wiquery) that supposedly make these two work better together.
Latest thing I tried was overriding method getOnClickScript() in ReportDownloadLink which seemed promising (according to the Javadocs, it returns "Any onClick JavaScript that should be used"):
#Override
protected CharSequence getOnClickScript(CharSequence url) {
return "closeDownloadDialog()";
}
Thing is, this causes onClick() not to be called at all, i.e., the download doesn't start.
Could I perhaps override some more "ajaxy" class from Wicket (than Link) to combine these things: first init the download, then call the JS for closing the dialog?
Any recommendations or experiences from similar cases? Note that I want to keep using the jQuery dialog here, even though it makes things like these more complicated. Using a DownloadLink (see related question) is fine too in case that makes things easier.
NB: if you recommend JQWicket or wiQuery, please provide an example of how to do this.
Maybe you can try to bind the close modal code to the button "click" event using only JQuery, in your modal panel page, add something similar to ${"#mySubmit").click(myCloseModalFunction). It should keep Wicket default's behavior and add modal closing in the mix.
The other way is to override the getOnClickScript(...) method but the javascript has to return true in order for the browser to call the continue link evaluation and load the corresponding href. If you return false, the evaluation stops. I would suggest something like
#Override
protected CharSequence getOnClickScript(CharSequence url) {
return "closeDownloadDialog();return true;";
}
Hope it helps...
See https://cwiki.apache.org/WICKET/ajax-update-and-file-download-in-one-blow.html for inspiration.
I try to reuse an existing WebView by clearing any private data the previous user left behind:
CookieManager.getInstance().removeAllCookie();
webview.clearHistory();
webview.clearFormData();
webview.clearCache(true);
clearHistory seems only to clear the back/forward list, accessible via API, but not the internal list used for coloring links inside the web content.
I even tried the following, suggested by another stackoverflow answer:
deleteDatabase("webview.db");
deleteDatabase("webviewCache.db");
I still have no luck: CSS :visited selectors still work after reloading the page.
An alternative would be to use the API level 11 private browsing feature (new constructor argument), but then I cannot benefit from visited links at all; and can no longer target older versions.
Maybe someone has a solution for this issue? Thanks for your help.
Summary of the answers I got so far:
I tried these two answers, but the first seems to clear HTML5 data storage and the latter seems to be specific to the built-in browser:
WebStorage.getInstance().deleteAllData();
Browser.clearHistory(getContentResolver());
WebChromeClient.getVisitedHistory(ValueCallback<String[]> callback) is only called after the first time I create a new WebView in a recently installed application.
I tried to remove the WebView from view hierachy and create a new one, but unfortunately the visited history seems to be stored for the whole application.
Override WebChromeClient and WebViewClient... Damn that was hidden.
I actually had to dig up a bit to find this out.
WebView webView = (WebView)findViewById(R.id.myWebView);
WebChromeClient myWebChromeClient = new WebChromeClient(){
#Override
public void getVisitedHistory(ValueCallback<String[]> callback) {
// called during webview initialization, original implementation does strictly nothing
// and defaults to the native method WebViewCore.nativeProvideVisitedHistory()
String[] myUserHistory = getVisitedUrlsFromMyOwnDatabase(userId);
callback.onReceiveValue(myUserHistory);
}
};
WebViewClient myWebViewClient = new WebViewClient(){
#Override
public void doUpdateVisitedHistory(WebView view, String url,
boolean isReload) {
// called whenever there is a new link being visited
insertIfNotExistVisitedUrlIntoMyOwnDatabaseForUser(userId);
super(view, url, isReload);
}
}
webView.setWebViewClient(myWebViewClient);
webView.setChromeClient(myWebChromeClient);
webView.getSettings().etc(whatever)...
I think I'm "almost there". Here's the part I managed: what it does so far is remove css history altogether, so we're halfway there. I can't get the browser to recognize the url format I'm providing in "myUserHistory", so in effect the only feature this code does is reset css history altogether, but it's only called once when the WebView is instanciated (or created, didn't check), so for a true multiuser experience you'd need to recreate the webview at each login.
My problem now is that I can't manage to load the urlHistory properly. My Honeycomb Xoom webview seems to ignore my data.
Ah well, I hope it works for you. For me just calling callback.onReceiveValue(new String[]{}); in getVisitedHistory() will be good enough.
EDIT:
I just put twenty more minutes into it because I'm curious. This method is what delegates to the WebChromeClient (mCallbackProxy = WebChromeClient).
protected void populateVisitedLinks() {
ValueCallback callback = new ValueCallback<String[]>() {
public void onReceiveValue(String[] value) {
sendMessage(EventHub.POPULATE_VISITED_LINKS, (Object)value);
}
};
mCallbackProxy.getVisitedHistory(callback);
}
It's protected in WebViewCore, which is a private attribute of WebView with no accessor. The sendMessage delegates to EventHub which is private, and WebViewCore is filled with private native methods, and one of these seems to be the one actually calling the populateVisitedLinks() method during the initialization.
Unless someone at Google adds a public method to WebView to trigger the repopulation, I'm afraid it's practically impossible to achieve your goal. Sorry :(
As a side note, all these native visited history handling really makes me wonder: why do hardware manufacturers care so much about which urls we visited? ;) <<< sarcasm
As an alternate solution, you could try adding your own CSS with the same base colors the default CSS has and switch the CSS by another one (with same color for both "types" of links) when you want to reset the visited links.
A:link{color: "#990000"; text-decoration: none;}
A:visited{color: "#990000"; text-decoration: none;}
A:hover{color: "#ff0000"; text-decoration: none;}
If you can obtain a Browser instance (maybe you can set a WebChromeClient to WebView) you can use its clearHistory() method.
Does WebStorage.clearAllData() have the desired effect? Unfortunately, the documentation on this class is very sparse compared to WebView and doesn't say whether it applies to WebViews.
The exact time you're calling clearHistory() may also have an effect. Clearing it and then navigating to a new page may still keep the first page in history, and you have to call the method after the new page has loaded.
Personally, if privacy is a real issue, I would create a new set of objects from scratch for this new session if possible.
It will take a moment for me to explain this, so please stay with me. I have table NewsFeed that has OneToMany relationship with itself.
#Entity
public class NewsFeed(){
...
#ManyToOne(optional=true, fetch=FetchType.LAZY)
#JoinColumn(name="REPLYTO_ID")
private NewsFeed replyTo;
#OneToMany(mappedBy="replyTo", cascade=CascadeType.ALL)
private List<NewsFeed> replies = new ArrayList<NewsFeed>();
public void addReply(NewsFeed reply){
replies.add(reply);
reply.setReplyTo(this);
}
public void removeReply(NewsFeed reply){
replies.remove(reply);
}
}
So you can think like this. Each feed can have a List of replies which are also type NewsFeed. Now it is very easy for me to delete the original feed and get the updated list back. All I need to do after delete is this.
feeds = scholarEJB.findAllFeed(); //This will query the db and return updated list
But I am having problem when trying to delete replies and getting the updated list back. So here is how I delete the replies. Inside my JSF managed bean I have
//Before invoke this method, I have the value of originalFeed, and deletedFeed set.
//These original feeds are display inside a p:dataTable X, and the replies are
//displayed inside p:dataTable Y which is inside X. So when I click the delete button
//I know which feed I want to delete, and if it is the replies, I will know
//which one is its original post
public void deleteFeed(){
if(this.deletedFeed != null){
scholarEJB.deleteFeeds(this.deletedFeed);
if(this.originalFeed != null){
//Since the originalFeed is not null, this is the `replies`
//that I want to delete
scholarEJB.removeReply(this.originalFeed, this.deletedFeed);
}
feeds = scholarEJB.findAllFeed();
}
}
Then inside my EJB scholarEJB, I have
public void removeReply(NewsFeed feed, NewsFeed reply){
feed = em.merge(feed);
comment.removeReply(reply);
em.persist(comment);
}
public void deleteFeeds(NewsFeed e){
e = em.find(NewsFeed.class, e.getId());
em.remove(e);
em.getEntityManagerFactory().getCache().evict(NewsFeed.class); //Like fdreger suggested
}
When I get out, the entity (the reply) get correctly removed from the database, but inside the feeds List, reference of that reply still there. It only until I log out and log back in that the reply disappear.
What you have written is correct, requerying should work (and in factis how it's usually done), so the problem must be somewhere else. For example if you delete the entity by any means other than the remove method, it may still be in the 2nd level cache. Or maybe the requerying does not happen at all because of some small mistake?
Update: After reading the new version of the original question (with all the new sources and clarification about Eclipselink) I made a little test, and it is - indeed - a second level cache problem. A bit strange, and possibly either a bug or an underspecified corner case. To fix it, evict comments from cache:
// this goes after em.remove(e)
em.getEntityManagerFactory().getCache().evict(Comment.class);
You could also try evicting the parent of the removed entity only (there is an overloaded version of evict).
Uhmpf. Maybe someone with more street cred (BalusC? :-) should change tags on this post. Turned out it has nothinh to do with JSF.
When you delete an object you must remove all reference to that object before deleting it. If you do not, you can get a constraint error, or stale data in your persistence context, or in the 2nd level cache.
When removing the Feed, first remove it from the replies.