Wicket ImageResourceReference ist mounted multiple times everytime the page is reloaded - java

I'm trying to mount an ImageResourceReference on my Page, but the ExternalLink is mounted multiple times (everytime I reload the page, I get a new additional link (same one).
For example when I start the server and load the page for the first time, there's just one ExternalLink, the second time, two links, third time three, etc...
What could be the reason for that?
Here is my code:
WebApp.java:
void init() {
.....
mountResource("/book/number/${number}/images/ray/${name}", new ImageResourceReference());
....
}
ImageResourcesPanel:
public class ImageResourcesPanel extends Panel {
private static final long serialVersionUID = -8723530004274531683L;
private static Logger logger = LoggerFactory.getLogger(ImageResourcesPanel.class
.getName());
/**
* The image names for which dynamic images will be generated
*/
private static List<String> IMAGE_NAMES = new ArrayList<String>();
public ImageResourcesPanel(final String wicketId, final IModel<Device> model) {
super(wicketId, model);
String pathToImage = "images";
IMAGE_NAMES.add(pathToImage);
ListView<String> listView = new ListView<String>("list", IMAGE_NAMES) {
private static final long serialVersionUID = 1L;
#Override
protected void populateItem(ListItem<String> item) {
logger.debug("Executed!");
ResourceReference imagesResourceReference = new ImageResourceReference();
PageParameters imageParameters = new PageParameters();
int number = model.getObject().getNumber();
String imageName = item.getModelObject();
String folder = model.getObject().getLinkToFolder();
imageParameters.set("name", imageName);
imageParameters.set("number", number);
imageParameters.set("folder", folder);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}

Got it!
I just had to make the ListView empty after mounting the image on the page. I just added a line of code after adding the link to the ListView-Item:
`IMAGE_NAMES.remove(pathToImage);`

Related

wicket form clear choice after refresh

I'm currently using three different forms, RadioChoice, DateField and DropDownChoice, in an application where the page reacts based on what the user picks from this form. The problem here is that when I submit the form that is using DateField and DropDownChoice, it does an refresh of the page and the choice from the RadioChoice is remembered but the default choice is shown instead. So my question is if it's either possible to clear the values and set them back to default after a refresh, or make the submit of DateField and DropDownChoice not refresh the page?
//RADIO CHOICE
RadioChoice<String> radioChoice = new RadioChoice<String>("radio", new PropertyModel<String>(this, "selectedRadio"),this.radioChoiceList);
radioChoice.add(new AjaxFormChoiceComponentUpdatingBehavior()
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onUpdate(AjaxRequestTarget target)
{
target.appendJavaScript(changeBaseLayerJS(Page.this.currentMap, Page.this.selectedRadio));
Page.this.currentMap = Page.this.selectedRadio;
}
});
Form<?> radioForm = new Form<Void>("radioForm");
add(radioForm);
radioForm.add(radioChoice);
//DATEFIELD AND DROPDOWNCHOICE
DateField fromDateField = new DateField("fromDateField", new PropertyModel<Date>(
this, "fromDate"));
DateField toDateField = new DateField("toDateField", new PropertyModel<Date>(
this, "toDate"));
DropDownChoice<String> idvNameMenu = new DropDownChoice<String>("idvNameMenu", new PropertyModel<String>(this, "idvTrackName"), individualChoiceList);
Form<?> trackingForm = new Form<Void>("trackingForm"){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit()
{
//do stuff
}
};
Normal (non-Ajax) form submit leads to full page repaint. Ajax form submit will repaint only the components you put into the AjaxRequestTarget.
You can use form.add(new AjaxFormSubmittingBehavior() {...}) to do it with Ajax.
Or you can zero-fy you model objects in onSubmit:
#Override
protected void onSubmit()
{
// do stuff
// save in database
fromDate = null; // or = new Date();
toDate = null;
idvTrackName = "some good default value";
}

Eclipse Preference Pages

I have created a preference page in eclipse the preference page has two fields
server url
store location
If the user open this preferences dialog, change the value of url and apply it the product is restarted and after restart when I check the value in the url field it is changed as expected. When I change the values of both url and directory only one of them is updated depends on which one is changed later.
Here is my init method which initialize the preferences
public class DataStorePreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public static final String SERVER_URL = "prefs_server_url";
public static final String WORKSPACE_DIR = "prefs_workspace_dir";
public static final String KEEP_LOCKS = "prefs_keep_locks";
//public static final String RELEASE = "prefs_release";
public DataStorePreferencePage() {
super(GRID);
}
#Override
public void init(IWorkbench workbench) {
setPreferenceStore(Activator.getDefault().getPreferenceStore());
getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
String property = event.getProperty();
System.setProperty("datastoreserver_url", property);
if (property.equals(DataStorePreferencePage.WORKSPACE_DIR) ||
property.equals(DataStorePreferencePage.SERVER_URL)) {
if(MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Information", "New settings will be applied after a restart.\nRestart now?"))
PlatformUI.getWorkbench().restart();
}
}
});
}
#Override
protected void createFieldEditors() {
StringFieldEditor urlEditor = new StringFieldEditor(SERVER_URL, "DataStore Server URL", getFieldEditorParent());
StringFieldEditor workspaceDirEditor = new DirectoryFieldEditor(WORKSPACE_DIR, "Workspace directory:", getFieldEditorParent());
BooleanFieldEditor keepLocksEditor = new BooleanFieldEditor(KEEP_LOCKS, "Keep locks (default setting):", getFieldEditorParent());
//BooleanFieldEditor releaseEditor = new BooleanFieldEditor(RELEASE, "Release (default setting):", getFieldEditorParent());
addField(workspaceDirEditor);
addField(urlEditor);
addField(keepLocksEditor);
//addField(releaseEditor);
}
#Override
public boolean performOk() {
return super.performOk();
}
}
Question:
Where is the new value stored? From where eclipse get this changed value in any .ini file?
How can I change both the properties at the same time?
Thanks
Wait until performOk or performApply is called before checking for restart.
The preference values are stored in the preference store. You can get them with:
IPreferenceStore store = getPreferenceStore();
String dir = store.getString(WORKSPACE_DIR);
String url = store.getString(SERVER_URL);

Passing PageParameters From WicketPanel

How could I use PageParameters on a Wicketpanel?
I'm willing to load images from filesystem on a WicketPanel, and I found a tutorial for that, but they are using a Page, and in my case, I want to mount the images on a Panel. What should I change in this class or do I HAVE to implement a PageClass for this usecase?
http://wicketinaction.com/2011/07/wicket-1-5-mounting-resources/
https://github.com/martin-g/blogs/blob/master/request-mappers/src/main/java/com/wicketinaction/requestmappers/resources/images/ImageResourcesPage.java
public class ImageResourcesPage extends WebPage {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPage(final PageParameters parameters) {
super(parameters);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}
Thanks
The example code shown does not actually use the pageParameters from the WebPage in the image handling at all, but has an additional PageParameters imageParameters field for the images. There's no reason you can't do the same in a Panel.
Something along the lines of
public class ImageResourcesPanel extends Panel {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPanel(final String wicketId) {
super(wicketId);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}
should work just as well as the page version shown.
I'm not sure final fields for imageParameters and imageResourceReference are appropriate though. I would probably just make them local variables within the populateItem(ListItem<String> item) method.
Update based on comments:
It appears this example produces links to images and what you want is embedded images. A better starting point for that might be the images example in the wicket-library examples page. The
ImageResourceReference code from this example might however still be useful in conjunction with the other example.
Can't you just hand over the page parametersfrom the Panel/Page you embed it in?
Alternatively you can use
RequestCycle.get().getPageParameters()
but I think handing it over from the embedding component would be cleaner.
Got it! I Had just to add the IModel as argument in the ImageResourcePanel-Constructor.
`public class ImageResourcesPanel extends Panel {
/**
* The image names for which dynamic images will be generated
*/
private static final String[] IMAGE_NAMES = new String[] {"one", "two", "three"};
public ImageResourcesPanel(final String wicketId, IModel<Book> book) {
super(wicketId, book);
int refNumber = book.getModelObject().getRefNumber();
ListView<String> listView = new ListView<String>("list", Arrays.asList(IMAGE_NAMES)) {
#Override
protected void populateItem(ListItem<String> item) {
String imageName = item.getModelObject();
imageParameters.set("name", imageName);
imageParameters.set("ref_number", refNumber);
final ResourceReference imagesResourceReference = new ImageResourceReference();
final PageParameters imageParameters = new PageParameters();
// generates nice looking url (the mounted one) to the current image
CharSequence urlForWordAsImage = getRequestCycle().urlFor(imagesResourceReference, imageParameters);
ExternalLink link = new ExternalLink("link", urlForWordAsImage.toString());
link.setBody(Model.of(imageName));
item.add(link);
}
};
add(listView);
}
}`

How to get images to display it in Wicket?

I am stuck with images. I need to upload an image and then display it on my page.
What I am doing now is uploading file like this:
private Picture picture; *// picture model*
private FileUploadField fileUpload;
public PictureUploader() {
Form<?> form = new Form<Void>("uploadForm") {
/**
*
*/
private static final long serialVersionUID = -694488846250739923L;
protected void onSubmit() {
FileUpload uploadedFile = fileUpload.getFileUpload();
File newFile = new File(uploadedFile.getClientFileName());
picture.setImage(newFile);
PageParameters pageParameter = new PageParameters();
pageParameter.put("file", picture.getImage());
setResponsePage(DataPage.class,pageParameter);
}
};
add(form);
form.setMultiPart(true);
form.add(setFileUpload(new FileUploadField("fileUpload")));
}
Then I submit it and go to DataPage ( I show only the constructor):
public DataPage(final PageParameters parameters) {
File file;
if (parameters.containsKey("file")) {
// WHAT TO DO HERE? SINCE GET() FROM PAGEPARAMETERS DOES NOT WORK FOR IT!
}
final Label result = new Label("result", ?????);
add(result);
}
Who knows how to make it, please, help me figure it out.

How to print pdf file with wicket and javascript

my wicket apliaction created some pdf file. now I want to add button to print it somethink like this: http://javascript.about.com/library/blprint.htm how I can do it ?
it looks you mix two things together. Your example is a javascript. It is not a PDF, it is just printing your document. It is equal as browser menu File -> Print, but the event is invoked from a javascript that handles button action. You can use the same button as in that example and add #print CSS to your web page to make your document nicely printable.
Also there is another way. If you want to print a PDF document from your application and you generate the PDF from Java code, look the following example for Wicket 1.6:
add(new Link<Void>("myPdfLink") {
private static final long serialVersionUID = 1L;
#Override
public void onClick() {
byte[] data = ... // TODO your data
final ByteArrayInputStream stream = new ByteArrayInputStream(data);
IResourceStream resourceStream = new AbstractResourceStream() {
private static final long serialVersionUID = 1L;
#Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
return stream;
}
#Override
public void close() throws IOException {
stream.close();
}
#Override
public String getContentType() {
return "application/pdf";
}
};
getRequestCycle().scheduleRequestHandlerAfterCurrent(
new ResourceStreamRequestHandler(resourceStream)
.setFileName("my-pdf-to-download.pdf")
.setContentDisposition(ContentDisposition.ATTACHMENT)
.setCacheDuration(Duration.ONE_SECOND)
);
}
});

Categories

Resources