How to get images to display it in Wicket? - java

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.

Related

Error message displayed by FeedbackPanel does not clear on valid input submission in Wicket

I have a form where their is a dropdown and checkbox . When i dont provide any input i receive the error message set through the Feedback Panel as below code
private Form<ReportCriteria> createCriteriaPanel(String id, IModel<ReportCriteria> model) {
SelectionForm form = new SelectionForm(id, model);
ReportCriteria criteria = (ReportCriteria) getDefaultModelObject();
.......
FeedbackPanel fb = new FeedbackPanel("feedback");
fb.setOutputMarkupId(true);
form.add(fb);
DropDownChoice<Project> billableProjectsList = new DropDownChoice<>(
"projectsList",
......
new ChoiceRenderer<Project>("fullNameWithCustomer"));
form.add(billableProjectsList);
CheckGroup<Project> unbillablePrjct = .......
form.add(new FormComponentValidator(billableProjectsList, unbillablePrjct));
form.getFeedbackMessages().clear();
}
protected void onSubmit() {
SelectionForm.this.getFeedbackMessages().size());
TimesheetExportCriteriaPanel.this.SelectionForm.findForm("criteriaForm").getFeedbackMessages();
}
all the feedbackmessages value is empty and not retreieving anything .
I receive the error message from FormValidator correctly when i dont provide any inputs . When i provide the inputs and submit , the form refreshes and loads with the same error message .
I want it to clear when we provide valid input .
When checked on forums , i found for Wicket 6.x we need to use component.getFeedbackMessages() , but it is empty for me .
I am new to wicket .
Please help with the inputs .
public class FormComponentValidator extends AbstractFormValidator {
private static final long serialVersionUID = 1L;
private FormComponent<?>[] components;
#SuppressWarnings("unchecked")
public FormComponentValidator(FormComponent<?> selectedBillableProject, FormComponent<?> selectedUnBillableProject) {
components = new FormComponent[]{selectedBillableProject, selectedUnBillableProject};
}
/*
* (non-Javadoc)
* #see org.apache.wicket.markup.html.form.validation.IFormValidator#getDependentFormComponents()
*/
public FormComponent<?>[] getDependentFormComponents() {
return components;
}
/*
* (non-Javadoc)
* #see org.apache.wicket.markup.html.form.validation.IFormValidator#validate(org.apache.wicket.markup.html.form.Form)
*/
public void validate(Form<?> form ) {
if ((org.apache.commons.lang.StringUtils.isEmpty(components[0].getInput()) || components[0].getInput() == null )
&& (org.apache.commons.lang.StringUtils.isEmpty(components[1].getInput()) || components[1].getInput() == null)) {
error(components[0], "project.Required");
}
}
}
private void configureFeedback() {
// activate feedback panel
final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
feedbackPanel.setOutputMarkupId(true);
feedbackPanel.setVisible(false);
add(feedbackPanel);
// don't show filtered feedback errors in feedback panel
final int[] filteredErrorLevels = new int[] { FeedbackMessage.ERROR };
feedbackPanel.setFilter(new IFeedbackMessageFilter() {
#Override
public boolean accept(FeedbackMessage message) {
for (int errorLevel : filteredErrorLevels) {
if (message.getLevel() == errorLevel) {
return false;
}
}
return true;
}
When submitting a Form Wicket runs all configured validators on all FormComponents (like TextInput, TextArea, DropDownChoice, etc.). If there is a validation error then a FeedbackMessage is associated with its respective FormComponent.
When rendering a FeedbackPanel Wicket visits all FormComponents and renders their FeedbackMessages (errors, infos, etc.).
At the end of the request cycle Wicket removes all rendered FeedbackMessages. If a FeedbackMessage is not rendered by any IFeedback component (like FeedbackPanel) then it will stay for the next request cycle.
This is done by DefaultCleanupFeedbackMessageFilter.
Put a breakpoint at DefaultCleanupFeedbackMessageFilter#accept() and see whether the problematic message is being accepted or not.

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";
}

Wicket ImageResourceReference ist mounted multiple times everytime the page is reloaded

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);`

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 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