Sometimes it can be useful to source content from an external location and integrate it within a Wicket Page. This panel allows external content to be injected into the body of the tag this panel is bound to on the page.

Note: you have to be careful of the injected markup to make sure that it is balanced and does not contain unclosed tags (or too many close tags) as this will mess up the browser DOM expecially in ModalWindow's.

URLResourcePanel.java
public class URLResourcePanel extends WebComponent {

	private static final Logger	log	= Logger.getLogger(URLResourcePanel.class);
	private final IModel	noResourceMessageModel;
        private final IModel    urlContainingModel;

	/**
	 * @param id
	 * @param urlContainingModel the url to replace the body of this panel with.
	 * @param noResourceMessageModel contains the string to display if the url cannot be resolved or doesn't load properly.
	 * 
	 */
	public URLResourcePanel(String id, IModel urlContainingModel, IModel noResourceMessageModel) {

		super(id)
                this.urlContainingModel = urlContainingModel;
		this.noResourceMessageModel = noResourceMessageModel;
		
		
	}

        /* (non-Javadoc)
	 * @see org.apache.wicket.Component#onComponentTagBody(org.apache.wicket.markup.MarkupStream, org.apache.wicket.markup.ComponentTag)
	 */
	@Override
	protected final void onComponentTagBody(MarkupStream markupStream,
			ComponentTag openTag) {

		try {
			String body = getBody();
			getResponse().write(body);
			return;
		}
		catch (Exception e) {
			// fall through
			
		}
		
		getResponse().write(noResourceMessageModel.getModelObjectAsString());
	}

	
        /* load the url content as the body of the component */
	private String getBody() throws IOException {

		String url = (String) getModelObject();
		
		UrlResourceStream resourceStream = new UrlResourceStream(new URL (url));
		
		String content = resourceStream.asString();			
		
		return content;
		
	}

	
}
  • No labels