001: /*
002: * Copyright 2002-2005 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package info.jtrac.wicket;
018:
019: import info.jtrac.domain.Attachment;
020: import info.jtrac.util.AttachmentUtils;
021: import java.io.File;
022: import java.io.FileInputStream;
023: import java.io.FileNotFoundException;
024: import java.io.IOException;
025: import java.io.InputStream;
026: import org.apache.wicket.IRequestTarget;
027: import org.apache.wicket.RequestCycle;
028: import org.apache.wicket.markup.html.basic.Label;
029: import org.apache.wicket.markup.html.link.Link;
030: import org.apache.wicket.protocol.http.WebResponse;
031: import org.apache.wicket.util.io.Streams;
032:
033: /**
034: * link for downloading an attachment
035: */
036: public class AttachmentLinkPanel extends BasePanel {
037:
038: public AttachmentLinkPanel(String id, final Attachment attachment) {
039:
040: super (id);
041:
042: if (attachment == null) {
043: add(new Label("attachment", ""));
044: setVisible(false);
045: return;
046: }
047:
048: final String fileName = getResponse().encodeURL(
049: attachment.getFileName()).toString();
050:
051: Link link = new Link("attachment") {
052: // adapted from wicket.markup.html.link.DownloadLink
053: // with the difference that the File is instantiated only after onClick
054: public void onClick() {
055: getRequestCycle().setRequestTarget(
056: new IRequestTarget() {
057:
058: public void detach(RequestCycle requestCycle) {
059: }
060:
061: public void respond(
062: RequestCycle requestCycle) {
063: WebResponse r = (WebResponse) requestCycle
064: .getResponse();
065: r.setAttachmentHeader(fileName);
066: try {
067: File file = AttachmentUtils
068: .getFile(
069: attachment,
070: getJtrac()
071: .getJtracHome());
072: InputStream is = new FileInputStream(
073: file);
074: try {
075: Streams.copy(is, r
076: .getOutputStream());
077: } catch (IOException e) {
078: throw new RuntimeException(e);
079: } finally {
080: try {
081: is.close();
082: } catch (IOException e) {
083: throw new RuntimeException(
084: e);
085: }
086: }
087: } catch (FileNotFoundException e) {
088: throw new RuntimeException(e);
089: }
090: }
091: });
092: }
093: };
094:
095: link.add(new Label("fileName", fileName));
096: add(link);
097:
098: }
099:
100: }
|