I use oracle-adf via xml menu model. Now I want to start download file on one of itemNode and without redirect. I'm tried to define action attribute with method which invokes hidden button's method(this button has inner fileDownloadActionListener) through javascript. But it doesn't work. Is it correct? or there is other way to decide this problem? Or may be it is impossible at all?
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn"
action=" "
visible="false"
clientComponent="true"
partialSubmit="false">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
Item node code:
<itemNode id="userInstructionsDownloadFlow" label="Инструкции пользователя"
focusViewId="#"
action="#{pageFlowScope.vocsReportsRegionController.invokeInstructionDownload}"
partialSubmit="true"
clientComponent="true"/>
Javascript cut:
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
Methods' description:
public void invokeInstructionDownload(){
FacesContext context = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(),
ExtendedRenderKitService.class);
erks.addScript(context, "handleInstructionsDownload();");
}
public void instructionsDownload(FacesContext context,
OutputStream out) throws IOException{
File f = new File("C:\\Users\\apozdnyakov\\Downloads\\Типы_контроля_время.xlsx");
FileInputStream fis;
byte[] b;
try {
fis = new FileInputStream(f);
int n;
while ((n = fis.available()) > 0) {
b = new byte[n];
int result = fis.read(b);
out.write(b, 0, b.length);
if (result == -1)
break;
}
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
}
I think there are a few possible reasons of your problem.
1- handleInstructionsDownload javascript function couldn't find the component, because of hierarchy of the jsf codes. You can add log in javascript function, for understanding that.
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
if (downloadBtn == null) {
console.log('The component is null!');
}
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If you see this log in javascript console you should control your hierarchy of jsf codes. And you should access to button by true component id.
2- invokeInstructionDownload java method couldn't find or call the javascript handleInstructionsDownload function. You can add log in the first line of the javascript function like that:
function handleInstructionsDownload(event) {
console.log('The js function fired!');
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If there is this log in console, you should change your javascript method calling. But I think your Java method is true :)
3- If these are not solutions of your problem, you can change your calling the hidden button like that.
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn" action=" "
visible="false"
clientComponent="true"
partialSubmit="false"
binding="#{pageFlowScope.vocsReportsRegionController.downloadInstructionsBtn}">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
ManagedBean code:
private RichButton downloadInstructionsBtn;
public RichButton getDownloadInstructionsBtn() {
return downloadInstructionsBtn;
}
public void setDownloadInstructionsBtn(RichButton downloadInstructionsBtn) {
this.downloadInstructionsBtn = downloadInstructionsBtn;
}
public void invokeInstructionDownload(){
ActionEvent actionEvent = new ActionEvent((UIComponent) downloadInstructionsBtn);
actionEvent.queue();
}
Related
I have webapp in Vaadin Framework 8. I have Windows GUI app in C#.
The gui app is using WebBrowser component to display webapp. WebBrowser component is internally using IE11 core through ActiveX. I can successfully load and display the webapp in the gui app browser component.
I need to pass data from webapp to the gui app.
The webapp has many rows loaded on server side, only few are displayed in grid. I want to pass all data from webapp to gui app in some format (csv or json).
I have tryed some approaches, but I wasn't successfull.
[Approach 1]
Webapp: attach downloadable resource (csv) to Link with predefined id using FileDownloader. Download by user mouse click works fine, file save dialog pops up and data are downloaded successfully.
Link link = new Link("Data");
link.setId("myId");
StreamResource resource = getMyResource(data);
FileDownloader downloader = new FileDownloader(resource);
downloader.extend(link);
Page.getCurrent().getJavaScript().addFunction("test", new JavaScriptFunction() {
#Override
public void call(JsonArray arguments) {
Page.getCurrent().getJavaScript()
.execute("document.getElementById('myId').click()");
}
});
Gui app: raise onClick event on link and capture WebBrowser.FileDownload event, capture WebBrowser.Navigate event.
I have failed to raise onClick event from C# using:
HtmlElement el = webBrowser.Document.GetElementById("myId");
el.RaiseEvent("onClick");
el.InvokeMember("click");
webBrowser.Document.InvokeScript("document.getElementById('myId').click();", null);
webBrowser.Document.InvokeScript("test", null);
Result:
WebBrowser.FileDownload event doesn't work (is fired but can't capture url nor data), capture WebBrowser.Navigate event works partialy (can see resource url, but can't download data using byte[] b = new WebClient().DownloadData(e.Url);).
[Approach 2]
Similar to approach 1. I tryed to get resource url, put the direct url to Link and download the resource in c# using direct link. I can construct the same resource url as is used by browser to download data when user clicks the link.
Extended file downloader that keeps resource, key and connector:
public class ExtendedFileDownloader extends FileDownloader {
private String myKey;
private Resource myResource;
private ClientConnector myConnector;
public ExtendedFileDownloader(StreamResource resource, ClientConnector connector) {
super(resource);
myConnector = connector;
}
#Override
protected void setResource(String key, Resource resource) {
super.setResource(key, resource);
myKey = key;
myResource = resource;
}
public String getResourceUrl() {
ResourceReference ref =
ResourceReference.create(
myResource,
(myConnector != null) ? myConnector : this,
myKey);
String url = ref.getURL();
return url;
}
}
In view:
// fix app://path... urls to /<base-path>/path urls
private String fixResourceReferenceUrl(String resourceReferenceUrl) {
String resourceReferencePath = resourceReferenceUrl.replace("app://", "");
String uiBaseUrl = ui.getUiRootPath();
String fixedUrl = uiBaseUrl + "/" + resourceReferencePath;
return fixedUrl;
}
Link link2 = new Link("Data2");
link2.setId("myId2");
StreamResource resource = getMyResource(data);
ExtendedFileDownloader downloader = new ExtendedFileDownloader(resource, this);
String fixedResourceUrl = fixResourceReferenceUrl(downloader.getResourceUrl());
link2.setResource(new ExternalResource(fixedResourceUrl));
Result:
The data cannot be downloaded using this link, server error 410 or NotFound errors.
Any Ideas ? Any other approaches to try ?
I have finally solved the problem. The solution is very close to approach 2.
The resource url is passed in element with custom attribute. C# WebClient needs to set cookies from WebBrowser and Referer HTTP headers. The data can be successfully downloaded by C# app.
Element attribute in vaadin webapp can be set using Vaadin-addon Attributes.
Cookies in C# app can be retrieved using this solution.
// Fix resource urls begining with app://
public String fixResourceReferenceUrl(String resourceReferenceUrl) {
try {
String uiRootPath = UI.getCurrent().getUiRootPath();
URI location = Page.getCurrent().getLocation();
String appLocation = new URIBuilder()
.setScheme(location.getScheme())
.setHost(location.getHost())
.setPort(location.getPort())
.setPath(uiRootPath)
.build()
.toString();
String resourceReferencePath = resourceReferenceUrl.replace("app://", "");
String fixedUrl = appLocation + "/" + resourceReferencePath;
return fixedUrl;
}
catch (Exception e) {
return null;
}
}
In view (using ExtendedFileDownloader from above):
Link link = new Link("Data");
link.setId("myId");
StreamResource resource = getMyResource(data);
ExtendedFileDownloader downloader = new ExtendedFileDownloader(resource);
downloader.extend(link);
Attribute attr = new Attribute("x-my-data", fixResourceReferenceUrl(downloader.getResourceUrl()));
attr.extend(link);
link.setVisible(true);
In C# app:
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetGetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
ref int size,
Int32 dwFlags,
IntPtr lpReserved);
private const Int32 InternetCookieHttponly = 0x2000;
public static String GetUriCookies(String uri)
{
// Determine the size of the cookie
int datasize = 8192 * 16;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(uri, null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(
uri,
null, cookieData,
ref datasize,
InternetCookieHttponly,
IntPtr.Zero))
return null;
}
return cookieData.ToString();
}
private void button_Click(object sender, EventArgs e)
{
HtmlElement el = webBrowser.Document.GetElementById("myId");
String url = el.GetAttribute("x-my-data");
String cookies = GetUriCookies(url);
WebClient wc = new WebClient();
wc.Headers.Add("Cookie", cookies);
wc.Headers.Add("Referer", WEB_APP_URL); // url of webapp base path, http://myhost/MyUI
byte[] data = wc.DownloadData(url);
}
My problem is simple but I have no clue how to solve it. I have a feedbackPanel and I want to show an error message if the BootstrapDownloadLink fails. With a submit I could easily do:
protected void onSubmit(AjaxRequestTarget target) {
...
error("File_not_found"); //Wicket will print this on the feedback panel
target.add(getModalPanel().getFeedbackPanel()); //But i need to refresh it first
}
But the button is inside a panel which I fill with a populateItem and is the only way I know to insert Bootstrap Styles to it. The code of the button:
BootstrapDownloadLink downloadDocument = new BootstrapDownloadLink(IDITEMREPEATER, file) {
#Override
public void onClick() {
File file = (File)getModelObject();
if(file.exists()) {
IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));
} else {
error(getString("error_fichero_no_existe"));
/// ???? need to refresh-> getModalPanel().getFeedbackPanel()
}
}
};
downloadDocument.setIconType(GlyphIconType.clouddownload);
downloadDocument.add(new AttributeModifier("title", getString("documentos.descargar")));
downloadDocument.add(new AttributeModifier("class", " btn btn-info negrita btn-xs center-block"));
downloadDocument.setVisible(Boolean.TRUE);
list.add(downloadDocument);
You could create or extend from an AjaxDownloadLink, for example like here.
The main idea is to have an AjaxBehavior that does the download, and you get a public void onClick(AjaxRequestTarget target) in which you can add the FeedbackPanel
downloadBehavior = new AbstractAjaxBehavior()
{
private static final long serialVersionUID = 3472918725573624819L;
#Override
public void onRequest()
{
[...]
ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(
AjaxDownloadLink.this.getModelObject(), name);
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}
};
And use that behavior in the onclick:
#Override
public void onClick(AjaxRequestTarget aTarget)
{
String url = downloadBehavior.getCallbackUrl().toString();
if (addAntiCache) {
url = url + (url.contains("?") ? "&" : "?");
url = url + "antiCache=" + System.currentTimeMillis();
}
// the timeout is needed to let Wicket release the channel
aTarget.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
}
You can use target.addChildren(getPage(), IFeedback.class). This will add all instances of IFeedback interface in the page to the AjaxRequestTarget.
You can also use FeedbackPanel.class instead of the interface.
Or use getPage().visit(new IVisitor() {...}) to find a specific feedback panel if you don't want to add others which are not related.
I am new to programming and couldn't find an answer to fit my question, and am unsure where else to turn. As stated in the title, I'm looking to download a file using HtmlUnit in Java, but the download button on the page has no href or onclick I can access. Button follows:
<button class="btn btn-download btn-primary pull-right" id="eta_download" style="display: block;">
<span class="glyphicon glyphicon-download-alt"></span>
</button>
clicking this button causes a normal browser to do some processing and loading for a short amount of time, then open a tab that triggers the download of a gzip file containing a tiff satellite image. I am doing this in a Swing app.
The site I need to download gzipped tiff from
Can anyone help me get this to work?
My code follows:
// Call from whithin new Thread. Get the download
private void getDownload(String latitude, String longitude, String start, String end) throws Exception
{
// Create the browser
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
// Report to user. Loading page...
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading EEFLUX...");
}
});
// Load page
HtmlPage page = webClient.getPage("https://eeflux-level1.appspot.com/");
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Filling in values");
}
});
// Get Latitude, Lomgitude and Date Fields
HtmlInput latitudeField = (HtmlInput) page.getElementById("latitude");
HtmlInput longitudeField = (HtmlInput) page.getElementById("longitude");
HtmlInput date_start_Field = (HtmlInput) page.getElementById("date_start");
HtmlInput date_end_Field = (HtmlInput) page.getElementById("date_end");
// Set the values of fields to that passed into method
latitudeField.setAttribute("value", latitude);
longitudeField.setAttribute("value", longitude);
date_start_Field.setAttribute("value", start);
date_end_Field.setAttribute("value", end);
// Get the Search "Button" then click
HtmlAnchor search = (HtmlAnchor) page.getHtmlElementById("searchForImages");
page = search.click();
// wait for Javascripts jobs to finish
JavaScriptJobManager manager = page.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 7; i++)
{
final int j = i;
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading after Search: " + j);
}
});
Thread.sleep(1000);
}
// Get the list of regions Satellites captured and click to open dropdown
HtmlDivision image_dropdown = (HtmlDivision) page.getElementById("image_dropdown");
image_dropdown.click();
// Get the list of regions
HtmlUnorderedList region_list = (HtmlUnorderedList) image_dropdown.getLastElementChild();
// get iterator for list
Iterator<DomElement> web_list = region_list.getChildElements().iterator();
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Accessing region list");
}
});
// for each Element, download Actual ET image (and later Grass Reference)
while(web_list.hasNext())
{
DomElement region = web_list.next();
System.out.println(region.getTextContent());
HtmlPage page2 = region.click();
// wait for Javascripts jobs to finish
manager = page2.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 2; i++)
{
final int j = i;
// Report to user
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading Image Type page: " + j);
}
});
System.out.println(manager.getJobCount());
Thread.sleep(1000);
}
// Get the Actual ET download Button
HtmlButton ETButton = page2.getHtmlElementById("eta_download");
// Get the Download Page????
HtmlPage page3 = ETButton.click();
UnexpectedPage download_ET = new UnexpectedPage(page3.getWebResponse(), page3.getEnclosingWindow());
// Get the Stream
GZIPInputStream in_ET = (GZIPInputStream) download_ET.getWebResponse().getContentAsStream();
// Try writing the stream (to standard out for now)
try
{
byte[] buffer = new byte[2048];
int len;
while((len = in_ET.read(buffer)) != -1)
{
System.out.write(buffer, 0, len);
}
}
finally
{
// Close the stream
in_ET.close();
}
// just do one till this works
break;
}
}
This is a good start :)
I looked at the request being sent when clicking the button :
As you can see there are several parameters being sent (latitude, longitude, date_end, image_id). In the response, you have the download URL.
This request is generated with some Javascript code, probably this :
function downloadImage(divName,urlProduct){
$(document).ready(function(){
$(divName).on('click', function(){
onlyshowLoading();
$.ajax({
url: urlProduct,
type: "POST",
data: JSON.stringify({
"lat": $('#latitude').val(),
"lng": $('#longitude').val(),
"date_info": $('#date_start').val() + ' to ' + $('#date_end').val(),
'image_id': $("#dropdown:first-child").text().split(" / ")[1],
}),
dataType: 'json',
cache: true,
error: function(){
AjaxOnError();
},
success: function(data){
AjaxOnSuccess();
if (typeof ETa_adjusted == "undefined" || ETa_adjusted == null){
$("#ETrF_adjusted").hide();
$("#EToF_adjusted").hide();
$("#ETa_adjusted").hide();
$("#etrF_adj_download").hide();
$("#etoF_adj_download").hide();
$("#eta_adj_download").hide();
} else{
$("#ETrF_adjusted").show();
$("#EToF_adjusted").show();
$("#ETa_adjusted").show();
$("#etrF_adj_download").show();
$("#etoF_adj_download").show();
$("#eta_adj_download").show();
}
var key = Object.keys(data);
typeName = data[key]
window.open(typeName.url, '_blank');
}
});
});
})
}
So it's possible that HtmlUnit is unable to execute this code, because of Jquery or whatever.
You could create your own WebRequest object, and reproduce the Javascript logic, then you will get the download URL.
It's an interesting subject, if you want to know more I'm in the middle of writing an ebook about web scraping with Java : Java Web Scraping Handbook
EDIT: This occurs during any component AJAX call.
I am building a web application using ICEFaces 3.2.0 community along with Spring Security 3.2 Everything has been going very well up until a few days ago. I have an ACE AutoCompleteEntry component in the page with a backing bean attached to the value as the following example:
<ace:autoCompleteEntry id="autoCompleteState"
label="State"
labelPosition="top"
value="#{autoCompleteEntry.selectedText}"
rows="10" width="160"
filterMatchMode="startsWith">
<f:selectItems value="#{autoCompleteEntry.states}"/>
</ace:autoCompleteEntry>
The backing bean attached is as follows:
#ManagedBean(name=AutoCompleteEntry.BEAN_NAME)
#SessionScoped
public class AutoCompleteEntry implements Serializable {
public static final String BEAN_NAME = "autoCompleteEntry";
public static final String STATE_FILENAME = "State_Names.txt";
public static final String RESOURCE_PATH = "/resources/selectinputtext/";
public AutoCompleteEntry() {
}
public List<SelectItem> states;
public List<SelectItem> getStates() {
if(states == null) {
states = new ArrayList<SelectItem>();
for(String state : readStateFile()) {
states.add(new SelectItem(state));
}
}
return states;
}
private String selectedText = null;
public String getSelectedText() {return selectedText;}
public void setSelectedText(String selectedText) {this.selectedText = selectedText;}
private static List<String> readStateFile() {
InputStream fileIn = null;
BufferedReader in = null;
try {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
fileIn = ec.getResourceAsStream(AutoCompleteEntry.RESOURCE_PATH + STATE_FILENAME);
if(fileIn != null) {
in = new BufferedReader(new InputStreamReader(fileIn));
List<String> loadedStates = new ArrayList<String>(53);
String read;
while((read = in.readLine()) != null) {
loadedStates.add(read);
}
return loadedStates;
}
}catch (IOException failedRead) {
failedRead.printStackTrace();
}finally {
try {
if(in != null) {
in.close();
}
}catch (IOException failedClose) {
failedClose.printStackTrace();
}
}
List<String> errorReturn = new ArrayList<String>(1);
errorReturn.add("Error Loading State List");
return errorReturn;
}
}
The problem is that each time I attempt to test the component instead of bringing up a list of the States it redirects to an absolute path of my main page, which results in a 404. In developer tools I see an error of:
> Uncaught TypeError: Cannot read property 'value' of undefined
bridge.uncompressed.js.jsf:2701
namespace.onAfterUpdate.viewIDElement bridge.uncompressed.js.jsf:2701
apply bridge.uncompressed.js.jsf:122
(anonymous function) bridge.uncompressed.js.jsf:484
(anonymous function) bridge.uncompressed.js.jsf:363
(anonymous function) bridge.uncompressed.js.jsf:240
broadcast bridge.uncompressed.js.jsf:483
(anonymous function) bridge.uncompressed.js.jsf:1928
sendEvent jsf.js.jsf:1447
AjaxEngine.req.sendRequest jsf.js.jsf:1333
request jsf.js.jsf:1834
fullSubmit bridge.uncompressed.js.jsf:2309
submit bridge.uncompressed.js.jsf:2314
iceSubmit compat.uncompressed.js.jsf:1523
onclick
The developer tools log shows:
> [window] persisted focus for element "autoCompleteState_input"
bridge.uncompressed.js.jsf:1252
[window] full submit to localhost:8181/HHCA_Portal/pages/secure/HHCA.jsf
javax.faces.execute: #all
javax.faces.render: patientRecordsForm
javax.faces.source: autoCompleteState_input
view ID: v33tl98j
event type: unknown bridge.uncompressed.js.jsf:1252
XHR finished loading: "localhost:8181/HHCA_Portal/pages/secure/HHCA.jsf".
jsf.js.jsf:1334
AjaxEngine.req.sendRequest jsf.js.jsf:1334
request jsf.js.jsf:1834
fullSubmit bridge.uncompressed.js.jsf:2309
ice.ace.AjaxRequest ace-jquery.uncompressed.js.jsf:20854
ice.ace.ab ace-jquery.uncompressed.js.jsf:20779
ice.ace.Autocompleter.getUpdatedChoices autocompleteentry.js.jsf:695
ice.ace.Autocompleter.onObserverEvent autocompleteentry.js.jsf:637
(anonymous function)
I have spent many hours working on this and other issues, and I have run out of ideas. If someone has some kind of assistance I would really appreciate the help.
If you are using JSF 2 then you can add your own exception handler , this should be able to capture ajax requests.
<factory>
<exception-handler-factory>
test.MyExceptionHandlerFactory
</exception-handler-factory>
</factory>
see the examples here ,
http://balusc.blogspot.com/2012/03/full-ajax-exception-handler.html
http://wmarkito.wordpress.com/2012/04/05/adding-global-exception-handling-using-jsf-2-x-exceptionhandler/
I get the following problem when trying to display a list of items. For each item, I have to display an image which is dynamically loaded via a Wicket WebResource. The items are loaded step by step — 50 at a time — upon user scrolling, using an Ajax scroll.
[ERROR] 2011-04-19 09:58:18,000 btpool0-1 org.apache.wicket.RequestCycle.logRuntimeException (host=, request=, site=):
org.apache.wicket.WicketRuntimeException: component documentList:scroller:batchElem:666:content:item:3:batchItemContent:linkToPreview:imageThumbnail not found on page com.webapp.document.pages.DocumentListPage[id = 1]
listener interface = [RequestListenerInterface name=IResourceListener, method=public abstract void org.apache.wicket.IResourceListener.onResourceRequested()]
org.apache.wicket.protocol.http.request.InvalidUrlException: org.apache.wicket.WicketRuntimeException: component documentList:scroller:batchElem:666:content:item:3:batchItemContent:linkToPreview:imageThumbnail
not found on page com.webapp.document.pages.DocumentListPage[id = 1] listener interface = [RequestListenerInterface name=IResourceListener, method=public abstract void org.apache.wicket.IResourceListener.onResourceRequested()]
at org.apache.wicket.protocol.http.WebRequestCycleProcessor.resolve(WebRequestCycleProcessor.java:262)
at org.apache.wicket.RequestCycle.step(RequestCycle.java:1310)
at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1428)
at org.apache.wicket.RequestCycle.request(RequestCycle.java:545)
at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:479)
at org.apache.wicket.protocol.http.WicketFilter$$EnhancerByGuice$$51619816.CGLIB$doGet$6()
at org.apache.wicket.protocol.http.WicketFilter$$EnhancerByGuice$$51619816$$FastClassByGuice$$6d42bf5d.invoke()
at com.google.inject.internal.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:64)
at com.freiheit.monitoring.PerformanceMonitoringMethodInterceptor.invoke(PerformanceMonitoringMethodInterceptor.java:115)
at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:64)
at com.google.inject.internal.InterceptorStackCallback.intercept(InterceptorStackCallback.java:44)
at org.apache.wicket.protocol.http.WicketFilter$$EnhancerByGuice$$51619816.doGet()
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:312)
at org.apache.wicket.protocol.http.WicketFilter$$EnhancerByGuice$$51619816.CGLIB$doFilter$4()
How can this problem be solved?
Here is the part of the code responsible for adding the image:
previewLink.add(createThumbnailSmall("imageThumbnail", documentModel));
in
createThumbnailSmall(final String id, final IModel<BaseDocument> documentModel) {
// thumbnailResource is an object that contains the path of the image
if (thumbnailResource != null) {
final WebResource resource = getWebResource(thumbnailResource);
final Image image = new Image(id, resource);
return image;
}
return new InvisibleContainer(id);
}
WebResource getWebResource(final DocumentResource documentResource) {
return new WebResource() {
private static final long serialVersionUID = 1L;
#Override
public IResourceStream getResourceStream() {
return new BaseStreamResource(documentResource);
}
};
}
where BaseStreamResource is the following:
public class BaseStreamResource extends AbstractResourceStream {
private InputStream _fileInputStream = null;
private DocumentResource _resource = null;
public BaseStreamResource(final DocumentResource documentResource) {
_resource = documentResource;
}
#Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
if (_fileInputStream == null) {
try {
if (_resource == null) {
throw new ResourceStreamNotFoundException("Resource was null");
}
_fileInputStream = _resource.getFileInputStream();
} catch (final ResourceNotAvailableException ex) {
throw new ResourceStreamNotFoundException(ex);
}
}
return _fileInputStream;
}
In HTML:
<a wicket:id="linkToPreview" href="#">
<img wicket:id="imageThumbnail" alt="Attachment"></img></a>
The code added hasn't really added any clues for me, but maybe I can help narrow it down a bit anyway.
The stacktrace includes a reference to com.webapp.document.pages.DocumentListPage, which is likely calling some of the code you've posted. The error indicates a bad url, so debugging into that class, adding debug prints, and looking at the values of any field containing a url might be worthwhile.
It might even help to modify the code in DocumentListPage (maybe temporarily for debugging) to catch org.apache.wicket.protocol.http.request.InvalidUrlException and adding debugging prints specifically when the exception is caught.
This isn't really an answer, but it's too big for a comment, and maybe it'll help you get closer to an answer.
The following solution solved the problem:
- extend WebResource class
- add extended class as a resource to application shared resources
Ex:
public class MyWebResource extends WebResource {
final ValueMap map = new ValueMap();
#Override
public IResourceStream getResourceStream() {
String fileName = getFileName();
File file = new File(basePath, fileName);
if (!file.exists()) {
LOG.error("File does not exist: " + file);
throw new IllegalStateException("File does not exist: " + file);
}
return new FileResourceStream(file);
}
public final void addResource() {
Application.get().getSharedResources().add(getClass().getName(), this);
}
protected String getFileName() {
return getParameters().getString("id");
}
public final String urlFor(final String fileName) {
final ResourceReference resourceReference = new ResourceReference(getClass().getName());
final String encodedValue = WicketURLEncoder.QUERY_INSTANCE.encode(fileName);
map.add("id", encodedValue);
final CharSequence result = RequestCycle.get().urlFor(resourceReference, map);
if (result == null) {
throw new IllegalStateException("The resource was not added! "
+ "In your Application class add the following line:"
+ "MyConcreteResource.INSTANCE.addResource()");
}
String absoluteUrl = RequestUtils.toAbsolutePath(result.toString());
return absoluteUrl;
}
}
In Application class, in init(), I have added MyWebResource to shared resources:
public void init() {
...
new MyWebResource().addResource();
...
}