Example usage for org.apache.wicket.util.file File File

List of usage examples for org.apache.wicket.util.file File File

Introduction

In this page you can find the example usage for org.apache.wicket.util.file File File.

Prototype

public File(final String parent, final String child) 

Source Link

Document

Constructor.

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 {/*from www . j  av  a  2s .  c  om*/
            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.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/* ww  w .  java  2 s.  c o  m*/
 * @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  w w w .j  a v  a2  s . c o m*/
        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:org.artifactory.webapp.wicket.resource.LogoResource.java

License:Open Source License

@Override
protected byte[] getImageData(Attributes attributes) {
    InputStream inputStream = null;
    try {/*  ww w  .  j  a v a 2s  .  c om*/
        File file = new File(artifactoryHome.getLogoDir(), "logo");
        inputStream = file.inputStream();
        return IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        throw new RuntimeException("Can't read image file", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.cast.cwm.ResourceDirectory.java

License:Open Source License

/**
 * creates a new resource response based on the request attributes
 * /*from ww  w  .  j  a  v a 2s  .  c  o m*/
 * @param attributes
 *            current request attributes from client
 * @return resource response for answering request
 */
@Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
    String relativePath = "";
    PageParameters parameters = attributes.getParameters();
    for (int i = 0; i < parameters.getIndexedCount(); i++) {
        relativePath += parameters.get(i);
        relativePath += '/';
    }
    if (relativePath.endsWith("/"))
        relativePath = relativePath.substring(0, relativePath.length() - 1);
    log.trace("relativePath is {}", relativePath);

    String absolutePath = new File(sourceDirectory, relativePath).getAbsolutePath();

    final ResourceResponse resourceResponse = new ResourceResponse();

    final IResourceStream resourceStream = getResourceStream(absolutePath);

    // bail out if resource stream could not be found
    if (resourceStream == null) {
        return sendResourceError(absolutePath, resourceResponse, HttpServletResponse.SC_NOT_FOUND,
                "Unable to find resource");
    }

    // allow caching
    resourceResponse.setCacheScope(WebResponse.CacheScope.PUBLIC);
    resourceResponse.setCacheDuration(cacheDuration);

    // add Last-Modified header (to support HEAD requests and If-Modified-Since)
    resourceResponse.setLastModified(resourceStream.lastModifiedTime());

    if (resourceResponse.dataNeedsToBeWritten(attributes)) {
        String contentType = resourceStream.getContentType();

        if (contentType == null && Application.exists())
            contentType = Application.get().getMimeType(absolutePath);

        // set Content-Type (may be null)
        resourceResponse.setContentType(contentType);

        try {
            // read resource data
            final byte[] bytes;

            bytes = IOUtils.toByteArray(resourceStream.getInputStream());

            // send Content-Length header
            resourceResponse.setContentLength(bytes.length);

            // send response body with resource data
            resourceResponse.setWriteCallback(new WriteCallback() {
                @Override
                public void writeData(Attributes attributes) {
                    attributes.getResponse().write(bytes);
                }
            });
        } catch (IOException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(absolutePath, resourceResponse, 500, "Unable to read resource stream");
        } catch (ResourceStreamNotFoundException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(absolutePath, resourceResponse, 500, "Unable to open resource stream");
        } finally {
            try {
                resourceStream.close();
            } catch (IOException e) {
                log.warn("Unable to close the resource stream", e);
            }
        }
    }

    return resourceResponse;
}

From source file:org.cast.cwm.xml.FileResource.java

License:Open Source License

private File getRelativeFile(String relativePath) {
    return new File(file.getParentFile(), relativePath);
}

From source file:org.cast.cwm.xml.FileXmlDocumentSource.java

License:Open Source License

/**
 * Return a FileResource at a location relative to this one.
 *///from www . j  a  v a  2 s  .  c om
public FileResource getRelativeResource(String relativePath) {
    File fullPath = new File(file.getParentFile(), relativePath);
    return new FileResource(fullPath);
}

From source file:org.cast.cwm.xml.FileXmlDocumentSource.java

License:Open Source License

/** Return a ResourceReference to a relatively-addressed item
 * /*from  w ww  . ja va2  s  .c  om*/
 * @param relativePath path relative to the path of this Resource
 * @return a ResourceReference that will resolve to {@link #getRelative(relativePath)}
 */
@Override
public ResourceReference getRelativeReference(final String relativePath) {
    String filePath = new File(file.getParentFile(), relativePath).getAbsolutePath().substring(1);
    return new ResourceReference(FileXmlDocumentSource.class, filePath) {
        private static final long serialVersionUID = 1L;

        @Override
        public IResource getResource() {
            return getRelativeResource(relativePath);
        }
    };
}

From source file:org.cast.cwm.xml.service.XmlService.java

License:Open Source License

@Override
public File findTransformFile(String href) {
    for (String directory : transformerDirectories) {
        File file = new File(directory, href);
        if (file.exists())
            return file;
    }/*from  w  w w  . j a va  2s.c o m*/
    return null;
}

From source file:org.cast.isi.ISIApplication.java

License:Open Source License

/**
* Load XML documents//from   ww w  .  j  av  a2s  .  c  om
*/
protected void loadXmlFiles() {
    log.debug("Loading ISI XML Files");

    String davServer = getDavServer();
    if (davServer != null) {
        final String davUser = configuration.getProperty("isi.davUser");
        final String davPassword = configuration.getProperty("isi.davPassword");

        DavClientManager manager = DavClientManager.get();
        manager.setDefaultAuthentication(davUser, davPassword);
        manager.createClient(davServer, davServer, getContentDir());
    }

    // Load glossary if there is one
    String glossaryFileName = configuration.getProperty("isi.glossaryFile");
    if (glossaryOn == false) {
        log.debug("Glossary is turned off");
    } else if (Strings.isEmpty(glossaryFileName)) {
        log.debug("No glossary file");
    } else { // when the glossary is on

        final XmlDocument glossaryDoc;
        if (davServer != null) {
            IInputStreamProvider glossaryResource = new DavResource(davServer,
                    getContentDir() + "/" + glossaryFileName);
            glossaryDoc = xmlService.loadXmlDocument("glossary", glossaryResource, new DtbookParser(), null);
        } else {
            File glossaryFile = new File(getContentDir(), glossaryFileName);
            glossaryDoc = xmlService.loadXmlDocument("glossary", glossaryFile, new DtbookParser(), null);
        }

        // Set up Glossary
        Databinder.ensureSession(new SessionUnit() {
            public Object run(Session sess) {
                glossary = GlossaryService.get().parseXmlGlossaryDocument(glossaryDoc);
                return null;
            }
        });
    }

    // Load student content files
    String fileList = configuration.getProperty("isi.studentContentFiles");
    if (StringUtils.isEmpty(fileList)) {
        fileList = DEFAULT_STUDENT_CONTENT_FILE_NAMES;
    } else {
        fileList = fileList.trim();
    }
    studentContentFiles = fileList.split("\\s*,\\s*");
    documentObservers.add(new XmlDocumentObserver(getSectionElement(), getPageElement())); // Use set so sub-classed applications can add to it as well
    for (String file : studentContentFiles) {
        XmlDocument doc;
        if (davServer != null) {
            log.debug("attempting to load DavResource file = {}", getContentDir() + "/" + file);
            log.debug("loading the DavResource on the Server = {}", davServer);
            IInputStreamProvider resource = new DavResource(davServer, getContentDir() + "/" + file);
            doc = xmlService.loadXmlDocument(file, resource, new DtbookParser(), documentObservers);
        } else {
            log.debug("attempting to load Resource file = {}", getContentDir() + "/" + file);
            File resource = new File(getContentDir(), file);
            doc = xmlService.loadXmlDocument(file, resource, new DtbookParser(), documentObservers);
        }
        studentContent.add(doc);
    }

    // Load email content files
    if (emailOn) {
        String emailFileName = EMAIL_FILE_NAME;
        if (davServer != null) {
            IInputStreamProvider emailResource = new DavResource(davServer,
                    getContentDir() + "/" + emailFileName);
            emailContent = xmlService.loadXmlDocument("email", emailResource, new DtbookParser(), null);
        } else {
            File emailResource = new File(getContentDir(), emailFileName);
            emailContent = xmlService.loadXmlDocument("email", emailResource, new DtbookParser(), null);
        }
    }
    log.debug("Finished loading ISI XML Files");
}