Example usage for org.apache.wicket.markup.html.form.upload FileUpload writeTo

List of usage examples for org.apache.wicket.markup.html.form.upload FileUpload writeTo

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.form.upload FileUpload writeTo.

Prototype

public void writeTo(final File file) throws Exception 

Source Link

Document

Saves this file upload to a given file on the server side.

Usage

From source file:ca.travelagency.config.CompanyPage.java

License:Apache License

private Form<Void> uploadForm() {
    Form<Void> form = new Form<Void>(UPLOAD_FORM) {
        private static final long serialVersionUID = 1L;

        @Override//  ww w  . ja v  a2 s. c o  m
        protected void onSubmit() {
            FileUpload fileUpload = fileUploadField.getFileUpload();
            if (fileUpload == null) {
                return;
            }
            String code = ApplicationProperties.make().getCode();
            File companyLogoFile = UploadUtils.getCompanyLogoFile(code);
            try {
                companyLogoFile.createNewFile();
                fileUpload.writeTo(companyLogoFile);
            } catch (Exception e) {
                throw new RuntimeException("Unable to write logo image", e);
            }
        }
    };
    form.setMultiPart(true);
    form.setMaxSize(Bytes.kilobytes(100));

    form.add(new ComponentFeedbackPanel(FEEDBACK, form));

    fileUploadField = new FileUploadField(UPLOAD_FIELD, new ListModel<FileUpload>());
    form.add(fileUploadField);

    return form;
}

From source file:com.evolveum.midpoint.web.page.admin.configuration.PageImportObject.java

License:Apache License

private void saveFilePerformed(AjaxRequestTarget target) {
    OperationResult result = new OperationResult(OPERATION_IMPORT_FILE);

    FileUploadField file = (FileUploadField) get(
            createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT));
    final FileUpload uploadedFile = file.getFileUpload();
    if (uploadedFile == null) {
        error(getString("pageImportObject.message.nullFile"));
        target.add(getFeedbackPanel());//from  ww  w.  j a va 2 s . c o  m

        return;
    }

    InputStream stream = null;
    File newFile = null;
    try {
        // Create new file
        MidPointApplication application = getMidpointApplication();
        WebApplicationConfiguration config = application.getWebApplicationConfiguration();
        File folder = new File(config.getImportFolder());
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdir();
        }

        newFile = new File(folder, uploadedFile.getClientFileName());
        // Check new file, delete if it already exists
        if (newFile.exists()) {
            newFile.delete();
        }
        // Save file
        Task task = createSimpleTask(OPERATION_IMPORT_FILE);
        newFile.createNewFile();
        uploadedFile.writeTo(newFile);

        InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8");
        stream = new ReaderInputStream(reader, reader.getEncoding());
        getModelService().importObjectsFromStream(stream, model.getObject(), task, result);

        result.recomputeStatus();
    } catch (Exception ex) {
        result.recordFatalError("Couldn't import file.", ex);
        LoggingUtils.logException(LOGGER, "Couldn't import file", ex);
    } finally {
        if (stream != null) {
            IOUtils.closeQuietly(stream);
        }
        if (newFile != null) {
            FileUtils.deleteQuietly(newFile);
        }
    }

    showResult(result);
    target.add(getFeedbackPanel());
}

From source file:com.evolveum.midpoint.web.page.admin.reports.PageNewReport.java

License:Apache License

private void importReportFromFilePerformed(AjaxRequestTarget target) {
    OperationResult result = new OperationResult(OPERATION_IMPORT_REPORT);

    FileUploadField file = (FileUploadField) get(
            createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT));
    final FileUpload uploadedFile = file.getFileUpload();
    if (uploadedFile == null) {
        error(getString("PageNewReport.message.nullFile"));
        target.add(getFeedbackPanel());/*  ww  w .j  a v a  2 s  .c  om*/

        return;
    }

    InputStream stream = null;
    File newFile = null;
    try {
        // Create new file
        MidPointApplication application = getMidpointApplication();
        WebApplicationConfiguration config = application.getWebApplicationConfiguration();
        File folder = new File(config.getImportFolder());
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdir();
        }

        newFile = new File(folder, uploadedFile.getClientFileName());
        // Check new file, delete if it already exists
        if (newFile.exists()) {
            newFile.delete();
        }
        // Save file
        //            Task task = createSimpleTask(OPERATION_IMPORT_FILE);
        newFile.createNewFile();
        uploadedFile.writeTo(newFile);

        InputStreamReader reader = new InputStreamReader(new FileInputStream(newFile), "utf-8");
        //            reader.
        stream = new ReaderInputStream(reader, reader.getEncoding());
        byte[] reportIn = IOUtils.toByteArray(stream);

        setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(reportIn))));
    } catch (Exception ex) {
        result.recordFatalError("Couldn't import file.", ex);
        LoggingUtils.logException(LOGGER, "Couldn't import file", ex);
    } finally {
        if (stream != null) {
            IOUtils.closeQuietly(stream);
        }
        if (newFile != null) {
            FileUtils.deleteQuietly(newFile);
        }
    }

    showResult(result);
    target.add(getFeedbackPanel());
}

From source file:com.marc.lastweek.business.services.images.impl.ImageServiceImpl.java

License:Open Source License

public void saveTemporalImage(FileUpload fileUpload, Folder temporalFolder) {
    try {//from w w w. j  a va 2 s . c  o  m
        File newFile = createImageFile(temporalFolder, fileUpload.getClientFileName());
        // Save to new file
        fileUpload.writeTo(newFile);

    } catch (Exception e) {
        throw new IllegalStateException("Unable to write file");
    }

}

From source file:drat.proteus.DratStartForm.java

License:Apache License

private void handleSubmit(String command) {
    FileUpload fileUpload = fileUploadField.getFileUpload();
    boolean downloadPhase = command.toUpperCase().equals("GO") || command.toUpperCase().equals("CRAWL");
    try {//  ww w  .  ja v a  2s. c o m
        String pathValue = pathField.getModelObject();
        LOG.info("Running DRAT: [" + command + "] on path: [" + pathValue + "]");

        if (pathValue == null || pathValue.isEmpty()) {
            File file = new File(
                    System.getProperty("java.io.tmpdir") + File.separator + fileUpload.getClientFileName());
            if (downloadPhase) {
                fileUpload.writeTo(file);
                File unzippedFile = Unzipper.unzip(file);
                file.delete();
                startDrat(unzippedFile.getCanonicalPath(), command);
                setResponsePage(DratWorkflow.class);
                return;
            } else {
                LOG.info("Omitting uploading of zip: current phase: [" + command + "]");
                startDrat(file.getAbsolutePath(), command);
                setResponsePage(DratWorkflow.class);
                return;
            }
        }

        if (pathValue.startsWith("http://")) {
            parseAsVersionControlledRepo(pathValue, command, downloadPhase);
        } else {
            try {
                File file = new File(pathValue);
                if (file.exists()) {
                    startDrat(pathValue, command);
                } else {
                    setResponsePage(HomePage.class);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                setResponsePage(HomePage.class);
                return;
            }
        }
        setResponsePage(DratWorkflow.class);
    } catch (Exception e) {
        e.printStackTrace();
        setResponsePage(HomePage.class);
    }
}

From source file:eu.esdihumboldt.hale.server.webtransform.war.pages.UploadAndTransForm.java

License:Open Source License

/**
 * @see Form#onSubmit()/*ww w.j ava 2  s .c o  m*/
 */
@Override
protected void onSubmit() {
    List<FileUpload> uploads = file.getFileUploads();
    if (uploads == null || uploads.isEmpty()) {
        error("Please specify files to transform.");
        return;
    }

    final TransformationWorkspace workspace = new TransformationWorkspace();

    List<InstanceReader> readers = Lists.transform(uploads, new Function<FileUpload, InstanceReader>() {

        private int count;

        @Override
        public InstanceReader apply(@Nullable final FileUpload input) {
            /*
             * Copy uploaded file to source folder, because the
             * input stream retrieved from the FileUpload is
             * automatically closed with the end of the request.
             */
            File file = new File(workspace.getSourceFolder(), (count++) + "_" + input.getClientFileName());
            try {
                input.writeTo(file);
            } catch (IOException e) {
                throw new IllegalStateException("Unable to read uploaded source file", e);
            }

            InstanceReader reader = null;
            try {
                LocatableInputSupplier<? extends InputStream> in = new FileIOSupplier(file);
                reader = HaleIO.findIOProvider(InstanceReader.class, in, input.getClientFileName());
                if (reader != null) {
                    reader.setSource(in);
                }
            } catch (Exception e) {
                throw new IllegalStateException("Unable to read uploaded source file", e);
            }
            if (reader == null) {
                throw new IllegalStateException("Could not find I/O provider for source file.");
            }
            return reader;
        }
    });

    try {
        workspace.transform(projectId, readers, target);
        setResponsePage(StatusPage.class,
                new PageParameters().add(StatusPage.PARAMETER_WORKSPACE, workspace.getId()));
    } catch (Exception e) {
        log.error("Error launching transformation process", e);
        error("Error launching transformation process");
        workspace.delete();
    }
}

From source file:eu.uqasar.web.pages.qmodel.QModelImportPage.java

License:Apache License

/**
 * Method to invoke parser xml instance.
 *
 * @Param upload File uploaded ready to parse
 * @return QModel created/*from   w ww  .j a  v a  2s.c  om*/
 * @throws IOException 
 * @throws JAXBException
 * @throws uQasarException
 */
private QModel parse(FileUpload upload, boolean xml) throws IOException, JAXBException, uQasarException {

    QModel qmodel;
    File newFile = new File(upload.getClientFileName());
    if (newFile.exists()) {
        newFile.delete();
    }

    newFile.createNewFile();
    upload.writeTo(newFile);

    //Parse file and save info
    if (xml) {
        qmodel = QModelXmlDomParser.parseFile(newFile);
    } else {
        qmodel = QModelJsonParser.parseFile(newFile);
    }

    List<String> nodeKeyList = qmodelService.getAllNodeKeys();

    if (Collections.frequency(nodeKeyList, qmodel.getNodeKey()) > 0) {
        throw new uQasarException("nodeKey");
    }

    newFile.delete();
    return qmodel;
}

From source file:eu.uqasar.web.pages.tree.projects.ProjectImportPage.java

License:Apache License

private Project parseProject(FileUpload upload, String content) throws uQasarException, Exception {
    File file = new File(upload.getClientFileName());
    if (file.exists()) {
        file.delete();/*www.jav  a2 s  .com*/
    }
    file.createNewFile();
    upload.writeTo(file);

    Project p = content.equals(XML_CONTENT) ? QProjectXmlDomParser.parseFile(file)
            : QProjectJsonParser.parseFile(file);

    List<String> nodeKeyList = treeNodeService.getAllNodeKeys();

    if (Collections.frequency(nodeKeyList, p.getNodeKey()) > 0) {
        throw new uQasarException("nodeKey");
    }

    file.delete();
    return p;
}

From source file:eu.uqasar.web.upload.FileUploadHelper.java

License:Apache License

/**
 * The default implementation simply writes the content of the uploaded file
 * to the target path.//  w  w w .  jav a 2 s  .c o  m
 *
 * @param file The uploaded file to be stored in the target path.
 * @param target The path where the uploaded file will be written to.
 * @return The path where the uploaded file was written to.
 * @throws IOException if any error occurs during writing of the file.
 */
Path processFileUpload(FileUpload file, Path target) throws IOException {
    file.writeTo(target.toFile());
    return target;
}

From source file:gr.abiss.calipso.util.AttachmentUtils.java

License:Open Source License

/**
 * //w  ww .  j av a  2 s. c  o m
 * @param attachment
 * @param jtracHome
 * @return
 */
private static File makePermanentAttachmentFile(Attachment attachment, FileUpload fileUpload, String home) {
    if (attachment.getItem().getSpace().getId() == 0 || attachment.getItem().getId() == 0
            || attachment.getHistory().getId() == 0) {
        throw new RuntimeException(
                "Only call this AFTER persisting Item > History > Attachment and associating "
                        + "them with the current session as their IDs are required for proper save.");
    }

    buildBasePath(attachment);
    //logger.info("Created basepath: "+attachment.getBasePath());
    // make file
    File newFile = new File(home + attachment.getBasePath() + attachment.getFileName());
    try {
        ensureFileExists(newFile);
        // write file
        fileUpload.writeTo(newFile);

        if (attachment.getFileName().endsWith(".png") || attachment.getFileName().endsWith(".gif")
                || attachment.getFileName().endsWith(".bmp") || attachment.getFileName().endsWith(".jpeg")
                || attachment.getFileName().endsWith(".jpg")) {

            File imageFileSmall = new File(home + File.separator + attachment.getBasePath() + File.separator
                    + "small_" + attachment.getFileName());
            if (!imageFileSmall.exists()) {
                imageFileSmall.createNewFile();
            }
            File imageFileThumb = new File(home + File.separator + attachment.getBasePath() + File.separator
                    + "thumb_" + attachment.getFileName());
            if (!imageFileThumb.exists()) {
                imageFileThumb.createNewFile();
            }

            // get image from upload
            BufferedImage bufferedImage = ImageIO.read(newFile);

            // generate and save small version for preview
            Thumbnail tn = new Thumbnail(bufferedImage);
            // create a big icon
            tn.getThumbnail(600);
            tn.saveThumbnail(imageFileSmall, Thumbnail.IMAGE_JPEG);
            tn = null;

            // create thumbnail from small image.
            bufferedImage = ImageIO.read(imageFileSmall);
            tn = new Thumbnail(bufferedImage);

            // create small icon
            tn.getThumbnail(100);
            tn.saveThumbnail(imageFileThumb, Thumbnail.IMAGE_JPEG);

        }
    } catch (Exception e) {
        throw new RuntimeException("Error saving icon.", e);
    }
    return newFile;
}