Example usage for org.apache.wicket.util.io Streams copy

List of usage examples for org.apache.wicket.util.io Streams copy

Introduction

In this page you can find the example usage for org.apache.wicket.util.io Streams copy.

Prototype

public static int copy(final InputStream in, final OutputStream out) throws IOException 

Source Link

Document

Writes the input stream to the output stream.

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);/*w  ww.j av a 2 s.  co  m*/
    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);/*  w ww .  j  a v  a2  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:info.jtrac.wicket.AttachmentLinkPanel.java

License:Apache License

public AttachmentLinkPanel(String id, final Attachment attachment) {

    super(id);// w  w  w .  jav a2  s.c  o m

    if (attachment == null) {
        add(new Label("attachment", ""));
        setVisible(false);
        return;
    }

    final String fileName = getResponse().encodeURL(attachment.getFileName()).toString();

    Link link = new Link("attachment") {
        // adapted from wicket.markup.html.link.DownloadLink
        // with the difference that the File is instantiated only after onClick
        @Override
        public void onClick() {
            getRequestCycle().setRequestTarget(new IRequestTarget() {

                @Override
                public void detach(RequestCycle requestCycle) {
                }

                @Override
                public void respond(RequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    r.setAttachmentHeader(fileName);
                    try {
                        File file = attachment.getFile(getJtrac().getJtracHome());
                        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);
                    }
                }
            });
        }
    };

    link.add(new Label("fileName", fileName));
    add(link);

}

From source file:main.java.info.jtrac.wicket.AttachmentLinkPanel.java

License:Apache License

public AttachmentLinkPanel(String id, final Attachment attachment) {

    super(id);/*  w  ww .  ja  v  a  2s.  c  om*/

    if (attachment == null) {
        add(new Label("attachment", ""));
        setVisible(false);
        return;
    }

    final String fileName = getResponse().encodeURL(attachment.getFileName()).toString();

    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().setRequestTarget(new IRequestTarget() {

                public void detach(RequestCycle requestCycle) {
                }

                public void respond(RequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    r.setAttachmentHeader(fileName);
                    try {
                        File file = AttachmentUtils.getFile(attachment, getJtrac().getJtracHome());
                        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);
                    }
                }
            });
        }
    };

    link.add(new Label("fileName", fileName));
    add(link);

}

From source file:org.brixcms.jcr.wrapper.BrixFileNode.java

License:Apache License

/**
 * Writes the node data to the specified output stream.
 *
 * @param stream/*from   w ww  .  ja v a2  s .c  o  m*/
 * @throws IOException
 */
public void writeData(OutputStream stream) throws IOException {
    Streams.copy(getDataAsStream(), stream);
}

From source file:org.brixcms.plugin.site.resource.admin.UploadResourcesPanel.java

License:Apache License

private void processUploads() {
    final BrixNode parentNode = getModelObject();

    for (final FileUpload upload : uploads) {
        final String fileName = upload.getClientFileName();

        if (parentNode.hasNode(fileName)) {
            if (overwrite) {
                parentNode.getNode(fileName).remove();
            } else {
                class ModelObject implements Serializable {
                    @SuppressWarnings("unused")
                    private String fileName = upload.getClientFileName();
                }/* w w  w.j a v  a2s.  co  m*/

                getSession().error(getString("fileExists", new Model<ModelObject>(new ModelObject())));
                continue;
            }
        }

        BrixNode newNode = (BrixNode) parentNode.addNode(fileName, "nt:file");

        try {
            // copy the upload into a temp file and assign that
            // output stream to the node
            File temp = File.createTempFile(Brix.NS + "-upload-" + UUID.randomUUID().toString(), null);

            Streams.copy(upload.getInputStream(), new FileOutputStream(temp));
            upload.closeStreams();

            String mime = upload.getContentType();

            BrixFileNode file = BrixFileNode.initialize(newNode, mime);
            file.setData(file.getSession().getValueFactory().createBinary(new FileInputStream(temp)));
            file.getParent().save();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    SitePlugin.get().selectNode(this, parentNode, true);
}

From source file:org.brixcms.util.JcrUtils.java

License:Apache License

/**
 * Copies a resource from classpath to a {@link java.io.File}
 *
 * @param source      classpath to resource
 * @param destination destination file//from  w w w  . j a  v  a2s  .c  o  m
 */
public static void copyClassResourceToFile(String source, java.io.File destination) {
    final InputStream in = JcrUtils.class.getResourceAsStream(source);
    if (in == null) {
        throw new RuntimeException("Class resource: " + source + " does not exist");
    }

    try {
        final FileOutputStream fos = new FileOutputStream(destination);
        Streams.copy(in, fos);
        fos.close();
        in.close();
    } catch (IOException e) {
        throw new RuntimeException("Could not copy class resource: " + source + " to destination: "
                + destination.getAbsolutePath());
    }
}

From source file:org.geoserver.web.admin.LogPage.java

License:Open Source License

public LogPage(PageParameters params) {
    Form form = new Form("form");
    add(form);//  ww w .ja  v  a 2s .com

    /**
     * take geoserver log file location from Config as absolute path and only use if valid, 
     * otherwise fallback to (geoserver-root)/logs/geoserver.log as default.
     */
    String location = GeoServerExtensions.getProperty(LoggingUtils.GEOSERVER_LOG_LOCATION);
    if (location == null) {
        location = getGeoServerApplication().getGeoServer().getLogging().getLocation();
    }
    if (location == null) {
        try {
            GeoServerResourceLoader loader = getGeoServerApplication().getResourceLoader();
            location = new File(loader.findOrCreateDirectory("logs"), "geoserver.log").getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException("Unexpeced error, could not find the log file location", e);
        }
    }
    logFile = new File(location);

    if (!logFile.isAbsolute()) {
        // locate the geoserver.log file
        GeoServerDataDirectory dd = getGeoServerApplication().getBeanOfType(GeoServerDataDirectory.class);
        logFile = new File(dd.root(), logFile.getPath());
    }

    if (!logFile.exists()) {
        error("Could not find the GeoServer log file: " + logFile.getAbsolutePath());
    }

    try {
        if (params.getKey(LINES) != null) {
            if (params.getInt(LINES) > 0) {
                lines = params.getInt(LINES);
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error parsing the lines parameter: ", params.getKey(LINES));
    }

    form.add(new SubmitLink("refresh") {
        @Override
        public void onSubmit() {
            setResponsePage(LogPage.class, new PageParameters(LINES + "=" + String.valueOf(lines)));
        }
    });

    TextField lines = new TextField("lines", new PropertyModel(this, "lines"));
    lines.add(new MinimumValidator(1));
    form.add(lines);

    TextArea logs = new TextArea("logs", new GSLogsModel());
    logs.setOutputMarkupId(true);
    logs.setMarkupId("logs");
    add(logs);

    add(new Link("download") {

        @Override
        public void onClick() {
            RequestCycle.get().setRequestTarget(new IRequestTarget() {

                public void detach(RequestCycle requestCycle) {
                }

                public void respond(RequestCycle requestCycle) {

                    InputStream is = null;
                    try {
                        is = new FileInputStream(logFile);

                        WebResponse r = (WebResponse) requestCycle.getResponse();
                        r.setAttachmentHeader("geoserver.log");
                        r.setContentType("text/plain");
                        Streams.copy(is, r.getOutputStream());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                }

            });

        }
    });

}

From source file:org.hippoecm.frontend.JcrResourceRequestHandler.java

License:Apache License

/**
 * @see IRequestHandler#respond(IRequestCycle)
 *///from  w  ww.j  ava 2s . c o m
public void respond(IRequestCycle requestCycle) {
    InputStream stream = null;
    try {
        if (node == null) {
            HttpServletResponse response = (HttpServletResponse) requestCycle.getResponse()
                    .getContainerResponse();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            // 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");
            return;
        }

        // Determine encoding
        String encoding = null;
        if (node.hasProperty("jcr:encoding")) {
            encoding = node.getProperty("jcr:encoding").getString();
        }
        String mimeType = node.getProperty("jcr:mimeType").getString();
        Calendar lastModified = node.getProperty("jcr:lastModified").getDate();
        stream = node.getProperty("jcr:data").getStream();

        // Set content type based on markup type for page
        WebResponse response = (WebResponse) requestCycle.getResponse();
        if (encoding != null) {
            response.setContentType(mimeType + "; charset=" + encoding);
        } else {
            response.setContentType(mimeType);
        }

        if (!mimeType.toLowerCase().startsWith("image/")) {
            response.setHeader("Content-Disposition", "attachment; filename=" + node.getName());
        }

        // 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.valueOf(lastModified.getTime()));
        try {
            Streams.copy(stream, response.getOutputStream());
        } catch (IOException ioe) {
            throw new WicketRuntimeException(ioe);
        }
    } catch (RepositoryException ex) {
        log.error(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.obiba.onyx.marble.core.wicket.consent.ElectronicConsentPage.java

License:Open Source License

@SuppressWarnings("serial")
public ElectronicConsentPage(final Component finishButton) {

    pdfResource = new DynamicWebResource() {
        @Override//  ww  w.j  a  v a 2 s .c o  m
        protected ResourceState getResourceState() {
            return new ResourceState() {
                @Override
                public String getContentType() {
                    return "application/pdf";
                }

                @Override
                public byte[] getData() {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        Streams.copy(fdfProducer.getPdfTemplate(), baos);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return baos.toByteArray();
                }
            };
        }

    };

    fdfResource = new DynamicWebResource() {
        @Override
        protected ResourceState getResourceState() {
            return new ResourceState() {
                byte[] fdf;

                @Override
                public String getContentType() {
                    return "application/vnd.fdf";
                }

                @Override
                synchronized public byte[] getData() {
                    if (fdf == null) {
                        String pdfUrl = RequestUtils
                                .toAbsolutePath(urlFor(IResourceListener.INTERFACE) + PDF_OPEN_PARAMETERS);
                        log.info("PDF URL is {}", pdfUrl);
                        PageParameters params = new PageParameters();
                        params.add("accepted", "true");
                        params.add("finishLinkId", finishButton.getMarkupId());
                        String acceptUrl = RequestUtils
                                .toAbsolutePath(urlFor(ElectronicConsentUploadPage.class, params).toString());

                        params = new PageParameters();
                        params.add("accepted", "false");
                        params.add("finishLinkId", finishButton.getMarkupId());
                        String refuseUrl = RequestUtils
                                .toAbsolutePath(urlFor(ElectronicConsentUploadPage.class, params).toString());
                        try {
                            fdf = fdfProducer.buildFdf(pdfUrl, acceptUrl, refuseUrl);
                        } catch (IOException e) {
                            fdf = null;
                            throw new RuntimeException(e);
                        }
                    }
                    return fdf;
                }
            };
        }
    };

    add(new FdfEmbedTag());
}