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

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

Introduction

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

Prototype

public static void copy(final Reader input, final OutputStream output) throws IOException 

Source Link

Document

Copy chars from a Reader to bytes on an OutputStream using the default character encoding of the platform, and calling flush.

Usage

From source file:au.org.theark.core.web.component.button.ArkDownloadTemplateButton.java

License:Open Source License

@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
    byte[] data = writeOutXlsFileToBytes();
    if (data != null) {
        InputStream inputStream = new ByteArrayInputStream(data);
        OutputStream outputStream;
        try {/*  ww  w . j  a  va 2 s  .co  m*/
            final String tempDir = System.getProperty("java.io.tmpdir");
            final java.io.File file = new File(tempDir, templateFilename + ".xls");
            final String fileName = templateFilename + ".xls";
            outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);

            IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
            getRequestCycle()
                    .scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream) {
                        @Override
                        public void respond(IRequestCycle requestCycle) {
                            super.respond(requestCycle);
                            Files.remove(file);
                        }
                    }.setFileName(fileName).setContentDisposition(ContentDisposition.ATTACHMENT));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}

From source file:au.org.theark.core.web.component.customfieldupload.CustomFieldUploadStep1.java

License:Open Source License

private void saveFileInMemory() {
    // Set study in context
    Long studyId = (Long) SecurityUtils.getSubject().getSession()
            .getAttribute(au.org.theark.core.Constants.STUDY_CONTEXT_ID);
    Study study = iArkCommonService.getStudy(studyId);

    // Retrieve file and store as Blob in database
    // TODO: AJAX-ified and asynchronous and hit database
    FileUpload fileUpload = fileUploadField.getFileUpload();
    containerForm.getModelObject().setFileUpload(fileUpload);

    InputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    File temp = null;/*from ww w  .  j  a v a  2s. c  o  m*/
    try {
        // Copy all the contents of the file upload to a temp file (to read multiple times)...
        inputStream = containerForm.getModelObject().getFileUpload().getInputStream();
        // Create temp file
        temp = File.createTempFile("customFieldUploadBlob", ".tmp");
        containerForm.getModelObject().setTempFile(temp);
        // Delete temp file when program exits (just in case manual delete fails later)
        temp.deleteOnExit();
        // Write to temp file
        outputStream = new BufferedOutputStream(new FileOutputStream(temp));
        IOUtils.copy(inputStream, outputStream);
    } catch (IOException ioe) {
        log.error("IOException " + ioe.getMessage());
        // Something failed, so there is temp file is not valid (step 2 should check for null)
        temp.delete();
        temp = null;
        containerForm.getModelObject().setTempFile(temp);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Unable to close inputStream: " + e.getMessage());
            }
        }
        if (outputStream != null) {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error("Unable to close outputStream: " + e.getMessage());
            }
        }
    }

    // Set details of Upload object
    containerForm.getModelObject().getUpload().setStudy(study);
    String filename = containerForm.getModelObject().getFileUpload().getClientFileName();
    String fileFormatName = filename.substring(filename.lastIndexOf('.') + 1).toUpperCase();
    FileFormat fileFormat = new FileFormat();
    fileFormat = iArkCommonService.getFileFormatByName(fileFormatName);
    containerForm.getModelObject().getUpload().setFileFormat(fileFormat);

    byte[] byteArray = fileUpload.getMD5();
    String checksum = getHex(byteArray);
    containerForm.getModelObject().getUpload().setChecksum(checksum);
    containerForm.getModelObject().getUpload().setFilename(fileUpload.getClientFileName());
    wizardForm.setFileName(fileUpload.getClientFileName());
}

From source file:au.org.theark.lims.web.component.inventory.panel.box.display.GridBoxPanel.java

License:Open Source License

/**
 * Return a download link for the gridBox contents as an Excel Worksheet 
 * @param invCellList//from   w ww. java2  s  .c om
 * @return
 */
protected Link<String> buildXLSDownloadLink(final List<InvCell> invCellList) {
    Link<String> link = new Link<String>("downloadGridBoxDataLink") {

        private static final long serialVersionUID = 1L;

        public void onClick() {
            byte[] data = createWorkBookAsByteArray(invCellList);
            if (data != null) {
                InputStream inputStream = new ByteArrayInputStream(data);
                OutputStream outputStream;
                try {
                    final String tempDir = System.getProperty("java.io.tmpdir");
                    final java.io.File file = new File(tempDir, limsVo.getInvBox().getName() + ".xls");
                    final String fileName = limsVo.getInvBox().getName() + ".xls";
                    outputStream = new FileOutputStream(file);
                    IOUtils.copy(inputStream, outputStream);

                    IResourceStream resourceStream = new FileResourceStream(
                            new org.apache.wicket.util.file.File(file));
                    getRequestCycle().scheduleRequestHandlerAfterCurrent(
                            new ResourceStreamRequestHandler(resourceStream) {
                                @Override
                                public void respond(IRequestCycle requestCycle) {
                                    super.respond(requestCycle);
                                    Files.remove(file);
                                }
                            }.setFileName(fileName).setContentDisposition(ContentDisposition.ATTACHMENT));
                } catch (FileNotFoundException e) {
                    log.error(e.getMessage());
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    };

    return link;
}

From source file:au.org.theark.study.web.component.attachments.SearchResultListPanel.java

License:Open Source License

private AjaxButton buildDownloadButton(final SubjectFile subjectFile) {
    AjaxButton ajaxButton = new AjaxButton(au.org.theark.study.web.Constants.DOWNLOAD_FILE) {

        private static final long serialVersionUID = 1L;

        @Override/*from  ww w .ja v  a 2  s.c  om*/
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            // Attempt to download the Blob as an array of bytes
            byte[] data = null;
            try {

                //               data = subjectFile.getPayload();//.getBytes(1, (int) subjectFile.getPayload().length());

                Long studyId = subjectFile.getLinkSubjectStudy().getStudy().getId();
                String subjectUID = subjectFile.getLinkSubjectStudy().getSubjectUID();
                String fileId = subjectFile.getFileId();
                String checksum = subjectFile.getChecksum();

                data = arkCommonService.retriveArkFileAttachmentByteArray(studyId, subjectUID,
                        au.org.theark.study.web.Constants.ARK_SUBJECT_ATTACHEMENT_DIR, fileId, checksum);

                if (data != null) {
                    InputStream inputStream = new ByteArrayInputStream(data);
                    OutputStream outputStream;

                    final String tempDir = System.getProperty("java.io.tmpdir");
                    final java.io.File file = new File(tempDir, subjectFile.getFilename());
                    final String fileName = subjectFile.getFilename();
                    outputStream = new FileOutputStream(file);
                    IOUtils.copy(inputStream, outputStream);

                    IResourceStream resourceStream = new FileResourceStream(
                            new org.apache.wicket.util.file.File(file));
                    getRequestCycle().scheduleRequestHandlerAfterCurrent(
                            new ResourceStreamRequestHandler(resourceStream) {
                                @Override
                                public void respond(IRequestCycle requestCycle) {
                                    super.respond(requestCycle);
                                    Files.remove(file);
                                }
                            }.setFileName(fileName).setContentDisposition(ContentDisposition.ATTACHMENT));
                }
            } catch (ArkSystemException e) {
                this.error("Unexpected error: Download request could not be fulfilled.");
                log.error("ArkSystemException" + e.getMessage(), e);
            } catch (FileNotFoundException e) {
                this.error("Unexpected error: Download request could not be fulfilled.");
                log.error("FileNotFoundException" + e.getMessage(), e);
            } catch (IOException e) {
                this.error("Unexpected error: Download request could not be fulfilled.");
                log.error("IOException" + e.getMessage(), e);
            }

            target.add(arkCrudContainerVO.getSearchResultPanelContainer());
            target.add(containerForm);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            this.error("Unexpected error: Download request could not be fulfilled.");
            log.error("Unexpected error: Download request could not be fulfilled.");
        };
    };

    ajaxButton.setVisible(true);
    ajaxButton.setDefaultFormProcessing(false);

    //if (subjectFile.getPayload() == null)
    //ajaxButton.setVisible(false);

    return ajaxButton;
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.rest.BaseResource.java

License:Open Source License

/**
 * Serves a short description HTML page at the service root
 *
 * @return//from w w w  . j av a2 s  . c om
 */
@GET
@Produces({ MediaType.TEXT_XML })
public Response getDescription() {
    final StreamingOutput writer = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try (InputStream is = getClass().getResourceAsStream("/restIndex.html")) {
                IOUtils.copy(is, output);
            } finally {
                output.close();
            }
        }
    };
    return Response.ok(writer).type(MediaType.TEXT_HTML).build();
}

From source file:fiftyfive.wicket.resource.MergedResourceBuilderTest.java

License:Apache License

/**
 * Download the resource at the given URI and make sure its contents
 * are identical to a merged list of files from the test fixture.
 *//*ww  w  .  j av  a 2 s. c o  m*/
protected void assertDownloaded(WicketTester tester, String uri, String... files) throws IOException {
    ByteArrayOutputStream expected = new ByteArrayOutputStream();
    for (String filename : files) {
        InputStream is = getClass().getResourceAsStream(filename);
        try {
            IOUtils.copy(is, expected);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    WicketTestUtils.assertDownloadEquals(tester, uri, expected.toByteArray());
}

From source file:net.dontdrinkandroot.extensions.wicket.resource.AbstractFileThumbnailResource.java

License:Apache License

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    final File file = this.resolveFile(attributes);

    final Integer width = this.resolveWidth(attributes);

    final byte[] imageBytes;
    try {/*  w w w . ja  v  a  2s . c o  m*/
        if (width == null) {
            final FileInputStream fis = new FileInputStream(file);
            final ByteArrayOutputStream imageBytesStream = new ByteArrayOutputStream();
            IOUtils.copy(fis, imageBytesStream);
            imageBytes = imageBytesStream.toByteArray();
            IOUtils.closeQuietly(fis);
        } else {
            final BufferedImage bufferedImage = ImageIO.read(file);
            final int oldWidth = bufferedImage.getWidth();
            final int oldHeight = bufferedImage.getHeight();
            final int newWidth = width;
            final int newHeight = newWidth * oldHeight / oldWidth;
            final BufferedImage scaledImage = new BufferedImage(newWidth, newHeight,
                    BufferedImage.TYPE_INT_RGB);
            final Graphics2D g2d = (Graphics2D) scaledImage.getGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(bufferedImage, 0, 0, newWidth, newHeight, 0, 0, oldWidth, oldHeight, null);
            g2d.dispose();
            final ByteArrayOutputStream imageBytesStream = new ByteArrayOutputStream();
            ImageIO.write(scaledImage, "jpg", imageBytesStream);
            imageBytes = imageBytesStream.toByteArray();
        }
    } catch (final IOException e) {
        throw new WicketRuntimeException(e);
    }

    final ResourceResponse resourceResponse = new ResourceResponse() {
        @Override
        public WriteCallback getWriteCallback() {
            return new WriteCallback() {
                @Override
                public void writeData(final Attributes attributes) {
                    try {
                        this.writeStream(attributes, new ByteArrayInputStream(imageBytes));
                    } catch (IOException e) {
                        throw new WicketRuntimeException(e);
                    }
                }
            };
        }
    };
    resourceResponse.setContentType("image/jpeg");
    resourceResponse.setLastModified(Time.millis(file.lastModified()));
    resourceResponse.setCacheDuration(this.getCacheDuration());
    resourceResponse.setContentLength(imageBytes.length);

    return resourceResponse;
}

From source file:net.dontdrinkandroot.wicket.resource.AbstractFileThumbnailResource.java

License:Apache License

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {

    final File file = this.resolveFile(attributes);

    final Integer width = this.resolveWidth(attributes);

    final byte[] imageBytes;
    try {/* www  .ja  v  a2  s .  c  o m*/

        if (width == null) {

            final FileInputStream fis = new FileInputStream(file);
            final ByteArrayOutputStream imageBytesStream = new ByteArrayOutputStream();
            IOUtils.copy(fis, imageBytesStream);
            imageBytes = imageBytesStream.toByteArray();
            IOUtils.closeQuietly(fis);

        } else {

            final BufferedImage bufferedImage = ImageIO.read(file);
            final int oldWidth = bufferedImage.getWidth();
            final int oldHeight = bufferedImage.getHeight();
            final int newWidth = width.intValue();
            final int newHeight = newWidth * oldHeight / oldWidth;
            final BufferedImage scaledImage = new BufferedImage(newWidth, newHeight,
                    BufferedImage.TYPE_INT_RGB);
            final Graphics2D g2d = (Graphics2D) scaledImage.getGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(bufferedImage, 0, 0, newWidth, newHeight, 0, 0, oldWidth, oldHeight, null);
            g2d.dispose();
            final ByteArrayOutputStream imageBytesStream = new ByteArrayOutputStream();
            ImageIO.write(scaledImage, "jpg", imageBytesStream);
            imageBytes = imageBytesStream.toByteArray();

        }

    } catch (final IOException e) {
        throw new WicketRuntimeException(e);
    }

    final ResourceResponse resourceResponse = new ResourceResponse() {

        @Override
        public WriteCallback getWriteCallback() {

            return new WriteCallback() {

                @Override
                public void writeData(final Attributes attributes) {

                    try {
                        this.writeStream(attributes, new ByteArrayInputStream(imageBytes));
                    } catch (IOException e) {
                        throw new WicketRuntimeException(e);
                    }
                }
            };
        }
    };
    resourceResponse.setContentType("image/jpeg");
    resourceResponse.setLastModified(Time.millis(file.lastModified()));
    resourceResponse.setCacheDuration(this.getCacheDuration());
    resourceResponse.setContentLength(imageBytes.length);

    return resourceResponse;
}

From source file:org.apache.jetspeed.security.mfa.TestCaptchaImageResource.java

License:Apache License

@Override
public void setUp() throws Exception {
    PropertiesConfiguration config = new PropertiesConfiguration();

    InputStream input = null;/*from  w  w  w  .j a  va2  s . com*/

    try {
        input = Thread.currentThread().getContextClassLoader().getResourceAsStream("mfa.properties");
        config.load(input);
    } finally {
        IOUtils.closeQuietly(input);
    }

    captchaConfig = new CaptchaConfiguration(config);
    captchaConfig.setUseImageBackground(true);

    ByteArrayOutputStream output = null;

    try {
        input = Thread.currentThread().getContextClassLoader().getResourceAsStream("Jetspeed_white_sm-1.jpg");
        output = new ByteArrayOutputStream();
        IOUtils.copy(input, output);
        background = output.toByteArray();
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
    }

    tempCaptchaFile = File.createTempFile("captcha-", ".jpg");
}

From source file:org.apache.syncope.client.console.resources.FilesystemResource.java

License:Apache License

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    ResourceResponse response = new ResourceResponse();

    final File baseDir = new File(basePath);
    if (baseDir.exists() && baseDir.canRead() && baseDir.isDirectory()) {
        String reqPath = attributes.getRequest().getUrl().getPath();
        final String subPath = reqPath.substring(reqPath.indexOf(baseCtx) + baseCtx.length()).replace('/',
                File.separatorChar);
        LOG.debug("Request for {}", subPath);

        response.setWriteCallback(new WriteCallback() {

            @Override//from  w w w  .  j  a  v a 2  s  . c o  m
            public void writeData(final Attributes attributes) throws IOException {
                FileInputStream resourceIS = null;
                try {
                    resourceIS = new FileInputStream(new File(baseDir, subPath));
                    IOUtils.copy(resourceIS, attributes.getResponse().getOutputStream());
                } catch (IOException e) {
                    LOG.error("Could not read from {}", baseDir.getAbsolutePath() + subPath, e);
                } finally {
                    IOUtils.closeQuietly(resourceIS);
                }
            }
        });
    } else {
        LOG.error("{} not found, not readable or not a directory", basePath);
    }

    return response;
}