Example usage for org.apache.wicket.request.http WebResponse setAttachmentHeader

List of usage examples for org.apache.wicket.request.http WebResponse setAttachmentHeader

Introduction

In this page you can find the example usage for org.apache.wicket.request.http WebResponse setAttachmentHeader.

Prototype

public void setAttachmentHeader(final String filename) 

Source Link

Document

Convenience method for setting the content-disposition:attachment header.

Usage

From source file:gr.abiss.calipso.wicket.AttachmentLinkPanel.java

License:Open Source License

public AttachmentLinkPanel(String id, final Attachment attachment, boolean addHeadScript) {
    super(id);/* ww w.j a  v a2 s  . com*/
    if (addHeadScript) {
        renderSighslideDirScript();
    }
    WebMarkupContainer attachmentContainer = new WebMarkupContainer("attachmentContainer");
    add(attachmentContainer);
    if (attachment == null) {
        attachmentContainer.setVisible(false);
        return;
    }
    final String fileName = getResponse().encodeURL(attachment.getFileName()).toString();
    String downloadLabel = null;
    WebMarkupContainer imageAttachmentContainer = new WebMarkupContainer("imageAttachment");
    attachmentContainer.add(imageAttachmentContainer);
    // if attachment is image, preview it
    if (fileName.endsWith(".png") || fileName.endsWith(".gif") || fileName.endsWith(".bmp")
            || fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
        BufferedImage icon = null;
        // read image
        try {
            File imageFileThumb = new File(getCalipso().getCalipsoHome() + File.separator
                    + attachment.getBasePath() + File.separator + "thumb_" + attachment.getFileName());
            if (imageFileThumb.exists()) {
                icon = ImageIO.read(imageFileThumb);
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to read thumb image", e);
        }
        // render html
        if (icon != null) {
            BufferedDynamicImageResource iconResource = new BufferedDynamicImageResource();
            iconResource.setImage(icon);
            Image image = new Image("imageThumb", iconResource);
            Link imageAttachmentLink = new Link("attachment") {
                // adapted from wicket.markup.html.link.DownloadLink
                // with the difference that the File is instantiated only
                // after onClick
                public void onClick() {
                    getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                        public void respond(IRequestCycle requestCycle) {
                            WebResponse r = (WebResponse) requestCycle.getResponse();
                            r.setAttachmentHeader(fileName);
                            try {
                                File previewfile = new File(getCalipso().getCalipsoHome() + File.separator
                                        + attachment.getBasePath() + File.separator + "small_"
                                        + attachment.getFileName());
                                logger.info("Looking for previewfile path: " + previewfile.getAbsolutePath());
                                InputStream is = new FileInputStream(previewfile);
                                try {
                                    Streams.copy(is, r.getOutputStream());
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        is.close();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            } catch (FileNotFoundException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        public void detach(IRequestCycle requestCycle) {
                            // TODO Auto-generated method stub

                        }
                    });
                }
            };
            imageAttachmentLink.add(image);
            imageAttachmentContainer.add(imageAttachmentLink);
            downloadLabel = attachment.isSimple() ? attachment.getOriginalFileName()
                    : localize("item_view_form.download");
        } else {
            imageAttachmentContainer.setVisible(false);
        }
    } else {
        imageAttachmentContainer.setVisible(false);
    }
    // attachment link
    Link link = new Link("attachment") {
        // adapted from wicket.markup.html.link.DownloadLink
        // with the difference that the File is instantiated only after
        // onClick
        public void onClick() {
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    try {
                        String ua = ((WebRequest) requestCycle.getRequest()).getHeader("User-Agent");
                        boolean isMSIE = (ua != null && ua.indexOf("MSIE") != -1);
                        logger.debug("Client browser is IE - " + isMSIE);
                        if (isMSIE) {
                            r.setAttachmentHeader(
                                    URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
                        } else {
                            // This works in FireFox - NEW W3C STANDART
                            // See
                            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html#RFC2231
                            r.setHeader("Content-Disposition",
                                    "attachment; filename*=UTF-8''" + URLEncoder.encode(
                                            attachment.isSimple() ? attachment.getOriginalFileName() : fileName,
                                            "UTF-8").replaceAll("\\+", "%20"));
                        }
                        r.setContentType(MimeTable.getDefaultTable().getContentTypeFor(fileName));
                    } catch (UnsupportedEncodingException e1) {
                        logger.error("Error encoding", e1);
                        r.setAttachmentHeader(fileName);
                    }
                    try {
                        File file = AttachmentUtils.getSavedAttachmentFile(attachment,
                                getCalipso().getCalipsoHome());
                        InputStream is = new FileInputStream(file);
                        try {
                            Streams.copy(is, r.getOutputStream());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                    // TODO Auto-generated method stub

                }
            });
        }
    };
    if (downloadLabel == null) {
        downloadLabel = fileName;
    }
    link.add(new Label("fileName", downloadLabel));
    attachmentContainer.add(link);
}

From source file:gr.abiss.calipso.wicket.fileUpload.AttachmentDownLoadableLinkPanel.java

License:Open Source License

public AttachmentDownLoadableLinkPanel(String id, final Attachment attachment) {
    super(id);//from ww w. j av a  2 s  .co  m
    renderSighslideDirScript();

    final String filaName = attachment.getFileName();
    String downloadLabel = null;

    // attachment link
    Link link = new Link("attachmentLink") {

        public void onClick() {

            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    try {
                        String ua = ((WebRequest) requestCycle.getRequest()).getHeader("User-Agent");
                        boolean isMSIE = (ua != null && ua.indexOf("MSIE") != -1);
                        logger.debug("Client browser is IE - " + isMSIE);
                        if (isMSIE) {
                            r.setAttachmentHeader(URLEncoder.encode(attachment.getFileName(), "UTF-8")
                                    .replaceAll("\\+", "%20"));
                        } else {

                            // This works in FireFox - NEW W3C STANDART
                            // See
                            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html#RFC2231
                            r.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder
                                    .encode(attachment.getFileName(), "UTF-8").replaceAll("\\+", "%20"));
                        }
                        r.setContentType(
                                MimeTable.getDefaultTable().getContentTypeFor(attachment.getFileName()));
                    } catch (UnsupportedEncodingException e1) {
                        logger.error("Some mess in Encoding");
                        r.setAttachmentHeader(attachment.getFileName());
                    }
                    try {
                        File file = AttachmentUtils.getSavedAttachmentFile(attachment,
                                getCalipso().getCalipsoHome());
                        InputStream is = new FileInputStream(file);
                        try {
                            Streams.copy(is, r.getOutputStream());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                    // TODO Auto-generated method stub

                }
            });

            // }
            // }

        }
    };
    downloadLabel = attachment.getFileName();
    add(link);
    link.add(new Label("fileName", downloadLabel));
}

From source file:gr.abiss.calipso.wicket.ItemList.java

License:Open Source License

private void addExcelExport() {
    add(new Link("export") {
        public void onClick() {
            // temporarily switch off paging of results
            itemSearch.setPageSize(-1);//ww w.j a  v  a 2 s  .c o m
            final ExcelUtils eu = new ExcelUtils(getCalipso().findItems(itemSearch), itemSearch, this);
            // restore page size
            itemSearch.setPageSize(pageSize);
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {
                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    r.setAttachmentHeader("calipso-export-" + DateUtils.formatForFileName() + ".xls");
                    try {
                        eu.exportToExcel().write(r.getOutputStream());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                }
            });
        }
    });
}

From source file:org.brixcms.plugin.snapshot.ManageSnapshotsPanel.java

License:Apache License

public ManageSnapshotsPanel(String id, final IModel<Workspace> model) {
    super(id, model);

    add(new FeedbackPanel("feedback"));

    IModel<List<Workspace>> snapshotsModel = new LoadableDetachableModel<List<Workspace>>() {
        @Override//from   ww w .  j a  va2  s.  c  o m
        protected List<Workspace> load() {
            List<Workspace> list = SnapshotPlugin.get().getSnapshotsForWorkspace(getModelObject());
            return getBrix().filterVisibleWorkspaces(list, Context.ADMINISTRATION);
        }
    };

    add(new ListView<Workspace>("snapshots", snapshotsModel) {
        @Override
        protected IModel<Workspace> getListItemModel(IModel<? extends List<Workspace>> listViewModel,
                int index) {
            return new WorkspaceModel(listViewModel.getObject().get(index));
        }

        @Override
        protected void populateItem(final ListItem<Workspace> item) {
            Workspace workspace = item.getModelObject();
            final String name = SnapshotPlugin.get().getUserVisibleName(workspace, true);
            final String comment = SnapshotPlugin.get().getComment(workspace);

            Link<Object> link = new Link<Object>("browse") {
                @Override
                public void onClick() {
                    Workspace workspace = item.getModelObject();
                    model.setObject(workspace);
                }
            };
            item.add(link);

            Link restoreLink = new Link<Void>("restore") {
                @Override
                public void onClick() {
                    Workspace target = ManageSnapshotsPanel.this.getModelObject();
                    SnapshotPlugin.get().restoreSnapshot(item.getModelObject(), target);
                    getSession().info(ManageSnapshotsPanel.this.getString("restoreSuccessful"));
                }

                /**
                 * Take care that restoring is only allowed in case the workspaces aren't the same
                 */
                @Override
                public boolean isEnabled() {
                    if (item.getModelObject().getId()
                            .equals(ManageSnapshotsPanel.this.getModelObject().getId())) {
                        return false;
                    }
                    return true;
                }

                @Override
                public boolean isVisible() {
                    Workspace target = ManageSnapshotsPanel.this.getModelObject();
                    Action action = new RestoreSnapshotAction(Context.ADMINISTRATION, item.getModelObject(),
                            target);
                    return getBrix().getAuthorizationStrategy().isActionAuthorized(action);
                }
            };

            /*
             * in case the link is enabled, make sure it is intended...
             */
            if (restoreLink.isEnabled()) {
                restoreLink.add(new SimpleAttributeModifier("onClick",
                        "return confirm('" + getLocalizer().getString("restoreOnClick", this) + "')"));
            }

            item.add(restoreLink);

            item.add(new Link<Void>("delete") {
                @Override
                public void onClick() {
                    Workspace snapshot = item.getModelObject();
                    snapshot.delete();
                }

                @Override
                public boolean isVisible() {
                    Action action = new DeleteSnapshotAction(Context.ADMINISTRATION, item.getModelObject());
                    return getBrix().getAuthorizationStrategy().isActionAuthorized(action);
                }
            });

            item.add(new Label("label", name));

            item.add(new Label("commentlabel", comment));
        }
    });

    add(new Link<Object>("downloadWorkspace") {
        @Override
        public void onClick() {
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {
                public void detach(IRequestCycle requestCycle) {
                }

                public void respond(IRequestCycle requestCycle) {
                    WebResponse resp = (WebResponse) requestCycle.getResponse();
                    resp.setAttachmentHeader("workspace.xml");
                    String id = ManageSnapshotsPanel.this.getModelObject().getId();
                    Brix brix = getBrix();
                    JcrSession session = brix.getCurrentSession(id);
                    HttpServletResponse containerResponse = (HttpServletResponse) resp.getContainerResponse();
                    ServletOutputStream containerResponseOutputStream = null;
                    try {
                        containerResponseOutputStream = containerResponse.getOutputStream();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    session.exportSystemView(brix.getRootPath(), containerResponseOutputStream, false, false);
                }
            });
        }
    });

    /**
     * Form to create a new Snapshot and put any comment to it
     */
    Form<Object> commentForm = new Form<Object>("commentForm") {
        @Override
        public boolean isVisible() {
            Workspace target = ManageSnapshotsPanel.this.getModelObject();
            Action action = new CreateSnapshotAction(Context.ADMINISTRATION, target);
            return getBrix().getAuthorizationStrategy().isActionAuthorized(action);
        }
    };

    final TextArea<String> area = new TextArea<String>("area", new Model<String>());
    commentForm.add(area);

    commentForm.add(new SubmitLink("createSnapshot") {
        /**
         * @see org.apache.wicket.markup.html.form.IFormSubmittingComponent#onSubmit()
         */
        @Override
        public void onSubmit() {
            String comment = area.getModelObject();
            SnapshotPlugin.get().createSnapshot(ManageSnapshotsPanel.this.getModelObject(), comment);
            area.setModelObject("");
        }
    });
    add(commentForm);

    Form<Object> uploadForm = new Form<Object>("uploadForm") {
        @Override
        public boolean isVisible() {
            Workspace target = ManageSnapshotsPanel.this.getModelObject();
            Action action = new RestoreSnapshotAction(Context.ADMINISTRATION, target);
            return getBrix().getAuthorizationStrategy().isActionAuthorized(action);
        }
    };

    final FileUploadField upload = new FileUploadField("upload", new Model<FileUpload>());
    uploadForm.add(upload);

    uploadForm.add(new SubmitLink("submit") {
        @Override
        public void onSubmit() {
            List<FileUpload> uploadList = upload.getModelObject();
            if (uploadList != null) {
                for (FileUpload u : uploadList) {
                    try {
                        InputStream s = u.getInputStream();
                        String id = ManageSnapshotsPanel.this.getModelObject().getId();
                        Brix brix = getBrix();
                        JcrSession session = brix.getCurrentSession(id);

                        if (session.itemExists(brix.getRootPath())) {
                            session.getItem(brix.getRootPath()).remove();
                        }
                        session.importXML("/", s, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
                        session.save();

                        brix.initWorkspace(ManageSnapshotsPanel.this.getModelObject(), session);

                        getSession().info(ManageSnapshotsPanel.this.getString("restoreSuccessful"));
                    } catch (IOException e) {
                        throw new BrixException(e);
                    }
                }
            }
        }
    });

    add(uploadForm);
}

From source file:org.dcm4chee.wizard.panel.BasicConfigurationPanel.java

License:LGPL

private Link<Object> getExportLink() {
    return new Link<Object>("export") {
        private static final long serialVersionUID = 1L;

        @Override/*from  ww w.  j av  a  2  s . com*/
        public void onClick() {

            RequestCycle.get().replaceAllRequestHandlers(new IRequestHandler() {

                @Override
                public void detach(IRequestCycle requestCycle) {
                }

                @Override
                public void respond(IRequestCycle requestCycle) {

                    OutputStream out = null;
                    try {
                        WebResponse response = (WebResponse) getRequestCycle().getResponse();
                        response.setContentType("application/zip");
                        response.setAttachmentHeader("configuration.zip");
                        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                        out = zos;
                        ZipEntry entry = new ZipEntry("configuration.xml");
                        zos.putNextEntry(entry);
                        DicomConfiguration dicomConfiguration = ((WizardApplication) getApplication())
                                .getDicomConfigurationManager().getDicomConfiguration();
                        ((PreferencesDicomConfiguration) dicomConfiguration).getDicomConfigurationRoot()
                                .exportSubtree(zos);
                        zos.flush();
                        zos.closeEntry();
                    } catch (ZipException ze) {
                        log.warn("Problem creating zip file: " + ze);
                    } catch (ClientAbortException cae) {
                        log.warn("Client aborted zip file download: " + cae);
                    } catch (Exception e) {
                        log.error("An error occurred while attempting to stream zip file for download: ", e);
                    } finally {
                        try {
                            if (out != null)
                                out.close();
                        } catch (Exception ignore) {
                        }
                    }
                }
            });
        }
    };
}

From source file:org.hippoecm.frontend.dialog.NodeInfo.java

License:Apache License

/**
 * @see org.apache.wicket.request.IRequestHandler#respond(org.apache.wicket.request.IRequestCycle)
 *//*from   ww  w . j  a v a2  s . co  m*/
public void respond(IRequestCycle requestCycle) {
    final Application app = Application.get();

    // Determine encoding
    final String encoding = app.getRequestCycleSettings().getResponseRequestEncoding();

    // Set content type based on markup type for page
    final WebResponse response = (WebResponse) requestCycle.getResponse();
    response.setContentType("text/xml; charset=" + encoding);

    // Make sure it is not cached by a client
    response.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    response.setHeader("Cache-Control", "no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setLastModifiedTime(Time.now());

    // set filename
    response.setAttachmentHeader(FILE_NAME);

    UserSession session = UserSession.get();

    try {

        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        try {
            PrintStream ps = new PrintStream(fos);

            ps.println("Hippo CMS Error report");
            ps.println("========================================");

            ps.print("version : ");
            ps.print(getCMSVersion());
            ps.println();

            ps.print("time    : ");
            ps.print(Time.now().toString());
            ps.println();

            javax.jcr.Session jcrSession = session.getJcrSession();
            if (jcrSession != null) {
                ps.print("user    : ");
                ps.print(session.getJcrSession().getUserID());
                ps.println();
            }

            HttpServletRequest hsr = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
            ps.print("server  : ");
            ps.print(hsr.getServerName());
            ps.println();

            String node = System.getProperty("org.apache.jackrabbit.core.cluster.node_id");
            if (node != null) {
                ps.print("node    : ");
                ps.print(hsr.getServerName());
                ps.println();
            }

            ps.print("java    : ");
            ps.print(System.getProperty("java.version"));
            ps.println();

            ps.println();

            ps.println("error   :");
            ps.print(ex.getClass().getName());
            ps.print(": ");
            ps.print(ex.getLocalizedMessage());
            ps.println();

            ex.printStackTrace(ps);
            ps.println();

            if (jcrSession != null) {
                ps.println("session :");

                Map<NodePath, NodeInfo> modificationTree = getModificationTree(jcrSession);
                int widths[] = new int[Column.values().length];
                for (Map.Entry<NodePath, NodeInfo> entry : modificationTree.entrySet()) {
                    NodeInfo info = entry.getValue();
                    for (Column col : Column.values()) {
                        int width = col.getWidth(info);
                        if (width > widths[col.ordinal()]) {
                            widths[col.ordinal()] = width;
                        }
                    }
                }
                int row = 0;
                for (Map.Entry<NodePath, NodeInfo> entry : modificationTree.entrySet()) {
                    NodeInfo info = entry.getValue();
                    if (row % 5 == 0 && row != 0) {
                        ps.println();
                    }
                    ps.print("  ");
                    for (Column col : Column.values()) {
                        String val = col.render(info);
                        ps.print(val);
                        int fill = widths[col.ordinal()] - val.length();
                        for (int i = 0; i < fill; i++) {
                            ps.print(' ');
                        }
                        ps.print("   ");
                    }
                    ps.println();
                    row++;
                }
            }
            ps.println();

            ps.println("========================================");

        } finally {
            fos.close();
        }
        response.write(fos.toByteArray());
    } catch (FileNotFoundException e) {
        log.error("Tempfile missing during export", e);
    } catch (IOException e) {
        log.error("IOException during export", e);
    }
}

From source file:org.sakaiproject.sitestats.tool.wicket.pages.ReportDataPage.java

License:Educational Community License

protected void exportXls() {
    String fileName = getExportFileName();
    byte[] hssfWorkbookBytes = Locator.getFacade().getReportManager().getReportAsExcel(report, fileName);

    RequestCycle.get().scheduleRequestHandlerAfterCurrent(new EmptyRequestHandler());
    WebResponse response = (WebResponse) getResponse();
    response.setContentType("application/vnd.ms-excel");
    response.setAttachmentHeader(fileName + ".xls");
    response.setHeader("Cache-Control", "max-age=0");
    response.setContentLength(hssfWorkbookBytes.length);
    OutputStream out = null;//from w w w .j  a v a2 s  .c  om
    try {
        out = response.getOutputStream();
        out.write(hssfWorkbookBytes);
        out.flush();
    } catch (IOException e) {
        LOG.error(e);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:org.sakaiproject.sitestats.tool.wicket.pages.ReportDataPage.java

License:Educational Community License

protected void exportCsv() {
    String fileName = getExportFileName();
    String csvString = Locator.getFacade().getReportManager().getReportAsCsv(report);

    RequestCycle.get().scheduleRequestHandlerAfterCurrent(new EmptyRequestHandler());
    WebResponse response = (WebResponse) getResponse();
    response.setContentType("text/comma-separated-values");
    response.setAttachmentHeader(fileName + ".csv");
    response.setHeader("Cache-Control", "max-age=0");
    response.setContentLength(csvString.length());
    OutputStream out = null;/*from   www . j av a2  s . com*/
    try {
        out = response.getOutputStream();
        out.write(csvString.getBytes());
        out.flush();
    } catch (IOException e) {
        LOG.error(e);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:org.sakaiproject.sitestats.tool.wicket.pages.ReportDataPage.java

License:Educational Community License

protected void exportPdf() {
    String fileName = getExportFileName();
    byte[] pdf = Locator.getFacade().getReportManager().getReportAsPDF(report);

    RequestCycle.get().scheduleRequestHandlerAfterCurrent(new EmptyRequestHandler());
    WebResponse response = (WebResponse) getResponse();
    response.setContentType("application/pdf");
    response.setAttachmentHeader(fileName + ".pdf");
    response.setHeader("Cache-Control", "max-age=0");
    response.setContentLength(pdf.length);
    OutputStream out = null;// w ww .j av  a2 s.c o m
    try {
        out = response.getOutputStream();
        out.write(pdf);
        out.flush();
    } catch (IOException e) {
        LOG.error(e);
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}