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

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

Introduction

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

Prototype

public long getSize() 

Source Link

Usage

From source file:au.org.theark.study.web.component.managestudy.form.DetailForm.java

License:Open Source License

@Override
protected void onSave(Form<StudyModelVO> containerForm, AjaxRequestTarget target) {
    try {//w w  w.  j  a v  a 2  s  .  c om
        String message = "Estimated Year of Completion must be greater than Date Of Application";

        boolean customValidationFlag = false;

        if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() != null) {
            customValidationFlag = validateEstYearOfComp(
                    containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion(),
                    containerForm.getModelObject().getStudy().getDateOfApplication(), message, target);
        }

        // Store Study logo image
        if (fileUploadField != null && fileUploadField.getFileUpload() != null) {
            // Retrieve file and store as Blob in databasse
            FileUpload fileUpload = fileUploadField.getFileUpload();

            // Copy file to Blob object
            Blob payload = util.createBlob(fileUpload.getInputStream(), fileUpload.getSize());
            containerForm.getModelObject().getStudy().setStudyLogoBlob(payload);
            containerForm.getModelObject().getStudy().setFilename(fileUpload.getClientFileName());
        }

        if (subjectFileUploadField != null && subjectFileUploadField.getFileUpload() != null) {
            FileUpload subjectFileUpload = subjectFileUploadField.getFileUpload();
            Collection<SubjectVO> selectedSubjects = iArkCommonService.matchSubjectsFromInputFile(
                    subjectFileUpload, containerForm.getModelObject().getStudy().getParentStudy());
            // Link subjects in file to the selected study (where matched)
            containerForm.getModelObject().setSelectedSubjects(selectedSubjects);
        }

        if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() != null
                && customValidationFlag) {
            // If there was a value provided then upon successful validation proceed with save or update
            processSaveUpdate(containerForm.getModelObject(), target);
        } else if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() == null) {
            // If the value for estimate year of completion was not provided then we can proceed with save or update.
            processSaveUpdate(containerForm.getModelObject(), target);
        }
    } catch (EntityExistsException e) {
        this.error("The specified study already exists in the system.");
        log.error(e.getMessage());
    } catch (EntityCannotBeRemoved e) {
        this.error("The Study cannot be removed from the system.There are participants linked to the study");
        log.error(e.getMessage());
    } catch (IOException e) {
        this.error("There was an error transferring the specified Study logo image.");
        log.error(e.getMessage());
    } catch (ArkSystemException e) {
        this.error("A System exception has occurred. Please contact Support");
        log.error(e.getMessage());
    } catch (UnAuthorizedOperation e) {
        this.error("You (logged in user) is unauthorised to create/update or archive this study.");
        log.error(e.getMessage());
    } catch (CannotRemoveArkModuleException e) {
        this.error(
                "You cannot remove the modules as part of the update. There are System Users who are associated with this study and modules.");
        log.error(e.getMessage());
    }
}

From source file:au.org.theark.study.web.component.managestudy.StudyLogoValidator.java

License:Open Source License

public void validate(IValidatable<List<FileUpload>> pValidatable) {

    List<FileUpload> fileUploadList = pValidatable.getValue();

    for (FileUpload fileUploadImage : fileUploadList) {

        String fileExtension = StringUtils.getFilenameExtension(fileUploadImage.getClientFileName());
        ValidationError error = new ValidationError();

        try {/*from w  ww.  j  av  a  2  s  .  c  o m*/
            // Check extension ok
            if (fileExtension != null && !fileExtensions.contains(fileExtension.toLowerCase())) {
                error.addMessageKey("study.studyLogoFileType");
                error.setVariable("extensions", fileExtensions.toString());
                pValidatable.error(error);
            } // Check size ok
            else if (fileUploadImage.getSize() > fileSize.bytes()) {
                error.addMessageKey("study.studyLogoFileSize");
                pValidatable.error(error);
            } else {
                // Read image, to work out width and height
                image = new SerializableBufferedImage(ImageIO.read(fileUploadImage.getInputStream()));

                if (image.getHeight() > 100) {
                    error.addMessageKey("study.studyLogoPixelSize");
                    pValidatable.error(error);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            error.addMessageKey("study.studyLogoImageError");
            pValidatable.error(error);
        }

    }

}

From source file:com.doculibre.constellio.wicket.panels.admin.searchInterface.LogoConfigPanel.java

License:Open Source License

public LogoConfigPanel(String id) {
    super(id);/*w w w.j av a2  s.  c om*/

    Form form = new Form("form");
    add(form);

    form.add(new FeedbackPanel("feedback"));

    final FileUploadField logoSmallField = new FileUploadField("logoSmall");
    form.add(logoSmallField);

    final FileUploadField logoLargeField = new FileUploadField("logoLarge");
    form.add(logoLargeField);

    Button submitButton = new Button("submitButton") {
        @Override
        public void onSubmit() {
            SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
                    .getSearchInterfaceConfigServices();
            SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

            FileUpload uploadLogoSmall = logoSmallField.getFileUpload();
            FileUpload uploadLogoLarge = logoLargeField.getFileUpload();

            if (uploadLogoSmall != null) {
                if (uploadLogoSmall.getSize() <= SearchInterfaceConfig.LOGO_MAXIMUM_SIZE) {
                    searchInterfaceConfig.setLogoSmallContent(uploadLogoSmall.getBytes());
                } else {
                    String size = FileSizeUtils.formatSize(uploadLogoSmall.getSize(), 3);
                    String maxSize = FileSizeUtils.formatSize(SearchInterfaceConfig.LOGO_MAXIMUM_SIZE, 3);
                    String[] params = new String[] { size, maxSize };
                    String error = new StringResourceModel("logoSmallTooBig", LogoConfigPanel.this, null,
                            params).getString();
                    error(error);
                    uploadLogoSmall = null;
                }

            }
            if (uploadLogoLarge != null) {

                if (uploadLogoLarge.getSize() <= SearchInterfaceConfig.LOGO_MAXIMUM_SIZE) {
                    searchInterfaceConfig.setLogoLargeContent(uploadLogoLarge.getBytes());
                } else {
                    String size = FileSizeUtils.formatSize(uploadLogoLarge.getSize(), 3);
                    String maxSize = FileSizeUtils.formatSize(SearchInterfaceConfig.LOGO_MAXIMUM_SIZE, 3);
                    String[] params = new String[] { size, maxSize };
                    String error = new StringResourceModel("logoLargeTooBig", LogoConfigPanel.this, null,
                            params).getString();
                    error(error);
                    uploadLogoLarge = null;
                }
            }
            if (uploadLogoSmall != null || uploadLogoLarge != null) {
                EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
                if (!entityManager.getTransaction().isActive()) {
                    entityManager.getTransaction().begin();
                }
                searchInterfaceConfigServices.makePersistent(searchInterfaceConfig);
                entityManager.getTransaction().commit();
            }
        }
    };
    form.add(submitButton);
}

From source file:com.socialsite.course.AddNotePanel.java

License:Open Source License

public AddNotePanel(String id, final IModel<Course> model) {
    super(id);/*from www. jav a2s  .co  m*/
    this.course = model.getObject();
    Form<Void> form = new Form<Void>("form");
    add(form);
    form.add(fileUploadField = new FileUploadField("file"));
    form.add(new RequiredTextField<String>("description", new PropertyModel<String>(this, "description")));
    form.add(new SubmitLink("submit") {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void onSubmit() {
            final FileUpload upload = fileUploadField.getFileUpload();
            if (upload == null || upload.getSize() == 0) {
                error("upload a file");
            } else if (upload.getSize() > 1024 * 1024) {
                // TODO change this to 10MB
                error("file size too large");
            } else {
                final Course course = courseDao.load(model.getObject().getId());
                Note note = new Note();
                note.setCourse(course);
                note.setTime(new Date());
                note.setDescription(description);
                note.setFileName(upload.getClientFileName());
                note.setData(upload.getBytes());
                note.setContentType(upload.getContentType());
                noteDao.save(note);

                CourseNoteMsg noteMsg = new CourseNoteMsg();
                noteMsg.setTime(new Date());
                noteMsg.setNote(note);
                noteMsg.setUsers(new HashSet<User>(course.getStudents()));

                messageDao.save(noteMsg);

            }
        }
    });

    add(feedback = new FeedbackPanel("feedback"));
}

From source file:com.socialsite.image.ImagePanel.java

License:Open Source License

/**
 * //from   w  w w  .  j av  a2 s .c  o  m
 * @param component
 *            component id
 * @param id
 *            id used to fetch the image
 * @param imageType
 *            type of the image (userimage , courseimage etc)
 * @param thumb
 *            will show thumb image if true
 * @param lastModified
 *            lastmodified date of the image
 */
public ImagePanel(final String component, final long id, final ImageType imageType, final Date lastModified,
        final boolean thumb, final boolean changeLink) {
    super(component);

    this.changeLink = changeLink;

    // allow the modal window to update the panel
    setOutputMarkupId(true);
    final ResourceReference imageResource = new ResourceReference(imageType.name());
    final Image userImage;
    final ValueMap valueMap = new ValueMap();
    valueMap.add("id", id + "");

    // the version is used to change the url dynamically if the image is
    // changed. This will allow the browser to cache images
    // reference http://code.google.com/speed/page-speed/docs/caching.html
    // #Use fingerprinting to dynamically enable caching.
    valueMap.add("version", lastModified.getTime() + "");
    if (thumb) {
        valueMap.add("thumb", "true");
    }
    add(userImage = new Image("userimage", imageResource, valueMap));
    userImage.setOutputMarkupId(true);

    final ModalWindow modal;
    add(modal = new ModalWindow("modal"));

    modal.setContent(new UploadPanel(modal.getContentId()) {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public String onFileUploaded(final FileUpload upload) {

            if (upload == null || upload.getSize() == 0) {
                // No image was provided
                error("Please upload an image.");
            } else if (!checkContentType(upload.getContentType())) {
                error("Only images of types png, jpg, and gif are allowed.");
            } else {
                saveImage(upload.getBytes());
            }

            return null;
        }

        @Override
        public void onUploadFinished(final AjaxRequestTarget target, final String filename,
                final String newFileUrl) {

            final ResourceReference imageResource = new ResourceReference(imageType.name());

            final ValueMap valueMap = new ValueMap();
            valueMap.add("id", id + "");
            // change the image lively
            valueMap.add("version", new Date().getTime() + "");
            if (thumb) {
                valueMap.add("thumb", "true");
            }

            userImage.setImageResourceReference(imageResource, valueMap);
            // update the image after the user changes it
            target.addComponent(userImage);
        }
    });
    modal.setTitle(" Select the image ");
    modal.setCookieName("modal");

    modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public boolean onCloseButtonClicked(final AjaxRequestTarget target) {
            return true;
        }
    });

    modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void onClose(final AjaxRequestTarget target) {
        }
    });

    add(new AjaxLink<Void>("changeimage") {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public boolean isVisible() {
            if (changeLink) {
                // TODO allow admins to change the university image and
                // allow
                // staffs to change the course image
                // it. don't show it for thumb images
                return hasRole(SocialSiteRoles.OWNER) || hasRole(SocialSiteRoles.STAFF);
            }
            return false;

        }

        @Override
        public void onClick(final AjaxRequestTarget target) {
            modal.show(target);
        }
    });
}

From source file:cz.zcu.kiv.eegdatabase.wui.ui.experiments.forms.ScenarioForm.java

License:Apache License

public ScenarioForm(String id, final ModalWindow window) {
    super(id, new CompoundPropertyModel<Scenario>(new Scenario()));

    add(new Label("addScenarioHeader", ResourceUtils.getModel("pageTitle.addScenario")));

    final FeedbackPanel feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);// w  w  w .ja  va2  s. c o m
    add(feedback);

    setMultiPart(true);

    Person owner = getModel().getObject().getPerson();
    if (owner == null)
        owner = EEGDataBaseSession.get().getLoggedUser();

    getModel().getObject().setPerson(owner);

    List<ResearchGroup> choices = researchGroupFacade.getResearchGroupsWhereAbleToWriteInto(owner);
    if (choices == null || choices.isEmpty())
        choices = Arrays.asList(getModel().getObject().getResearchGroup());

    DropDownChoice<ResearchGroup> groups = new DropDownChoice<ResearchGroup>("researchGroup", choices,
            new ChoiceRenderer<ResearchGroup>("title"));
    groups.setRequired(true);

    TextField<String> title = new TextField<String>("title");
    title.setLabel(ResourceUtils.getModel("label.scenarioTitle"));
    title.setRequired(true);
    // title.add(new TitleExistsValidator());

    TextField<Integer> length = new TextField<Integer>("scenarioLength", Integer.class);
    length.setRequired(true);
    length.add(RangeValidator.minimum(0));

    TextArea<String> description = new TextArea<String>("description");
    description.setRequired(true);
    description.setLabel(ResourceUtils.getModel("label.scenarioDescription"));

    final WebMarkupContainer fileContainer = new WebMarkupContainer("contailer");
    fileContainer.setVisibilityAllowed(false);
    fileContainer.setOutputMarkupPlaceholderTag(true);

    /*
     * TODO file field for xml was not visible in old portal. I dont know why. So I hided it but its implemented and not tested.
     */
    // hidded line in old portal
    final DropDownChoice<ScenarioSchemas> schemaList = new DropDownChoice<ScenarioSchemas>("schemaList",
            new Model<ScenarioSchemas>(), scenariosFacade.getListOfScenarioSchemas(),
            new ChoiceRenderer<ScenarioSchemas>("schemaName", "schemaId"));
    schemaList.setOutputMarkupPlaceholderTag(true);
    schemaList.setRequired(true);
    schemaList.setLabel(ResourceUtils.getModel("label.scenarioSchema"));
    schemaList.setVisibilityAllowed(false);

    final FileUploadField file = new FileUploadField("file", new ListModel<FileUpload>());
    file.setOutputMarkupId(true);
    file.setLabel(ResourceUtils.getModel("description.fileType.dataFile"));
    file.setOutputMarkupPlaceholderTag(true);

    // hidded line in old portal
    final FileUploadField xmlfile = new FileUploadField("xmlfile", new ListModel<FileUpload>());
    xmlfile.setOutputMarkupId(true);
    xmlfile.setLabel(ResourceUtils.getModel("label.xmlDataFile"));
    xmlfile.setOutputMarkupPlaceholderTag(true);
    xmlfile.setVisibilityAllowed(false);

    // hidded line in old portal
    final RadioGroup<Boolean> schema = new RadioGroup<Boolean>("schema", new Model<Boolean>(Boolean.FALSE));
    schema.add(new Radio<Boolean>("noschema", new Model<Boolean>(Boolean.FALSE), schema));
    schema.add(new Radio<Boolean>("fromschema", new Model<Boolean>(Boolean.TRUE), schema));
    schema.setOutputMarkupPlaceholderTag(true);
    schema.setVisibilityAllowed(false);
    schema.add(new AjaxFormChoiceComponentUpdatingBehavior() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            schemaList.setVisibilityAllowed(schema.getModelObject());
            xmlfile.setRequired(!xmlfile.isRequired());

            target.add(xmlfile);
            target.add(schemaList);
        }
    });

    CheckBox privateCheck = new CheckBox("privateScenario");
    final CheckBox dataAvailable = new CheckBox("dataAvailable", new Model<Boolean>());
    dataAvailable.add(new AjaxFormComponentUpdatingBehavior("onChange") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {

            fileContainer.setVisibilityAllowed(dataAvailable.getModelObject());
            file.setRequired(!file.isRequired());
            target.add(fileContainer);
        }
    });

    fileContainer.add(file, xmlfile, schema, schemaList);

    add(groups, title, length, description, privateCheck, dataAvailable, fileContainer);

    add(new AjaxButton("submitForm", this) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            FileUpload uploadedFile = file.getFileUpload();
            Scenario scenario = ScenarioForm.this.getModelObject();

            if (!scenariosFacade.canSaveTitle(scenario.getTitle(), scenario.getScenarioId())) {
                error(ResourceUtils.getString("error.titleAlreadyInDatabase"));
                target.add(feedback);
                return;
            } else {
                // loading non-XML scenario file
                if ((uploadedFile != null) && (!(uploadedFile.getSize() == 0))) {

                    String name = uploadedFile.getClientFileName();
                    // when uploading from localhost some browsers will specify the entire path, we strip it
                    // down to just the file name
                    name = Strings.lastPathComponent(name, '/');
                    name = Strings.lastPathComponent(name, '\\');

                    // File uploaded
                    String filename = name.replace(" ", "_");
                    scenario.setScenarioName(filename);

                    scenario.setMimetype(uploadedFile.getContentType());
                    try {
                        scenario.setFileContentStream(uploadedFile.getInputStream());
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                        error("Error while saving data.");
                        target.add(feedback);
                    }
                }

                // Creating new
                scenariosFacade.create(scenario);

                /*
                 * clean up after upload file, and set model to null or will be problem with page serialization when redirect start - DON'T DELETE IT !
                 */
                ScenarioForm.this.setModelObject(null);

                window.close(target);
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {

            target.add(feedback);
        }
    });

    add(new AjaxButton("closeForm", ResourceUtils.getModel("button.close")) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            window.close(target);
        }
    }.setDefaultFormProcessing(false));

    setOutputMarkupId(true);
}

From source file:cz.zcu.kiv.eegdatabase.wui.ui.scenarios.form.ScenarioForm.java

License:Apache License

public ScenarioForm(String id, IModel<Scenario> model, final FeedbackPanel feedback) {

    super(id, new CompoundPropertyModel<Scenario>(model));

    setMultiPart(true);/* w w  w .java 2  s.  c  o m*/

    Person owner = model.getObject().getPerson();
    if (owner == null) {
        owner = EEGDataBaseSession.get().getLoggedUser();
    }

    model.getObject().setPerson(owner);

    List<ResearchGroup> choices = researchGroupFacade.getResearchGroupsWhereAbleToWriteInto(owner);
    if (choices == null || choices.isEmpty()) {
        choices = Arrays.asList(model.getObject().getResearchGroup());
    }

    DropDownChoice<ResearchGroup> groups = new DropDownChoice<ResearchGroup>("researchGroup", choices,
            new ChoiceRenderer<ResearchGroup>("title"));
    groups.setRequired(true);

    TextField<String> title = new TextField<String>("title");
    title.setLabel(ResourceUtils.getModel("label.scenarioTitle"));
    title.setRequired(true);

    TextField<Integer> length = new TextField<Integer>("scenarioLength", Integer.class);
    length.setRequired(true);
    length.add(RangeValidator.minimum(0));

    TextArea<String> description = new TextArea<String>("description");
    description.setRequired(true);
    description.setLabel(ResourceUtils.getModel("label.scenarioDescription"));

    final WebMarkupContainer fileContainer = new WebMarkupContainer("contailer");
    fileContainer.setVisibilityAllowed(false);
    fileContainer.setOutputMarkupPlaceholderTag(true);

    /*
     * TODO file field for xml was not visible in old portal. I dont know why. So I hided it but its implemented and not tested.
     */
    // hidded line in old portal
    final DropDownChoice<ScenarioSchemas> schemaList = new DropDownChoice<ScenarioSchemas>("schemaList",
            new Model<ScenarioSchemas>(), scenariosFacade.getListOfScenarioSchemas(),
            new ChoiceRenderer<ScenarioSchemas>("schemaName", "schemaId"));
    schemaList.setOutputMarkupPlaceholderTag(true);
    schemaList.setRequired(true);
    schemaList.setLabel(ResourceUtils.getModel("label.scenarioSchema"));
    schemaList.setVisibilityAllowed(false);

    final FileUploadField file = new FileUploadField("file", new ListModel<FileUpload>());
    file.setOutputMarkupId(true);
    file.setLabel(ResourceUtils.getModel("description.fileType.dataFile"));
    file.setOutputMarkupPlaceholderTag(true);

    // hidded line in old portal
    final FileUploadField xmlfile = new FileUploadField("xmlfile", new ListModel<FileUpload>());
    xmlfile.setOutputMarkupId(true);
    xmlfile.setLabel(ResourceUtils.getModel("label.xmlDataFile"));
    xmlfile.setOutputMarkupPlaceholderTag(true);
    xmlfile.setVisibilityAllowed(false);

    // hidded line in old portal
    final RadioGroup<Boolean> schema = new RadioGroup<Boolean>("schema", new Model<Boolean>(Boolean.FALSE));
    schema.add(new Radio<Boolean>("noschema", new Model<Boolean>(Boolean.FALSE), schema));
    schema.add(new Radio<Boolean>("fromschema", new Model<Boolean>(Boolean.TRUE), schema));
    schema.setOutputMarkupPlaceholderTag(true);
    schema.setVisibilityAllowed(false);
    schema.add(new AjaxFormChoiceComponentUpdatingBehavior() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            schemaList.setVisibilityAllowed(schema.getModelObject());
            xmlfile.setRequired(!xmlfile.isRequired());

            target.add(xmlfile);
            target.add(schemaList);
        }
    });

    CheckBox privateCheck = new CheckBox("privateScenario");
    final CheckBox dataAvailable = new CheckBox("dataAvailable", new Model<Boolean>());
    dataAvailable.add(new AjaxFormComponentUpdatingBehavior("onChange") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {

            fileContainer.setVisibilityAllowed(dataAvailable.getModelObject());
            file.setRequired(!file.isRequired());
            target.add(fileContainer);
        }
    });

    SubmitLink submit = new SubmitLink("submit") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onSubmit() {

            FileUpload uploadedFile = file.getFileUpload();
            Scenario scenario = ScenarioForm.this.getModelObject();

            if (!scenariosFacade.canSaveTitle(scenario.getTitle(), scenario.getScenarioId())) {
                error(ResourceUtils.getString("error.titleAlreadyInDatabase"));
                return;
            } else {
                // loading non-XML scenario file
                if ((uploadedFile != null) && (!(uploadedFile.getSize() == 0))) {

                    String name = uploadedFile.getClientFileName();
                    // when uploading from localhost some browsers will specify the entire path, we strip it
                    // down to just the file name
                    name = Strings.lastPathComponent(name, '/');
                    name = Strings.lastPathComponent(name, '\\');

                    // File uploaded
                    String filename = name.replace(" ", "_");
                    scenario.setScenarioName(filename);

                    scenario.setMimetype(uploadedFile.getContentType());
                    try {
                        scenario.setFileContentStream(uploadedFile.getInputStream());
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }

                if (scenario.getScenarioId() > 0) {
                    // Editing existing
                    // scenarioTypeDao.update(scenarioType);
                    scenariosFacade.update(scenario);
                } else {
                    // Creating new
                    scenariosFacade.create(scenario);
                }
                /*
                 * clean up after upload file, and set model to null or will be problem with page serialization when redirect start - DON'T DELETE IT !
                 */
                ScenarioForm.this.setModelObject(null);

                setResponsePage(ScenarioDetailPage.class,
                        PageParametersUtils.getDefaultPageParameters(scenario.getScenarioId()));
            }

        }
    };

    fileContainer.add(file, xmlfile, schema, schemaList);

    add(groups, title, length, description, privateCheck, dataAvailable, submit, fileContainer);
}

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

License:Apache License

public QModelImportPage(PageParameters parameters) {
    super(parameters);
    logger.info("QModelImportPage::QModelImportPage start");
    final Form<?> form = new Form<Void>("form") {

        /**/*from   w  w  w . j a v a2s.  co  m*/
         *
         */
        private static final long serialVersionUID = 4949407424211758709L;

        @Override
        protected void onSubmit() {
            logger.info("QModelImportPage::onSubmit starts");
            errorMessage = "";

            try {

                FileUpload upload = file.getFileUpload();
                if (upload == null) {
                    errorMessage = "qmodel.empty.file.error";
                    logger.info("QModelImportPage::onSubmit no file uploaded");
                } else {
                    logger.info("QModelImportPage::onSubmit some file uploaded");

                    if (upload.getSize() > Bytes.kilobytes(MAX_SIZE).bytes()) {
                        errorMessage = "qmodel.max.file.error";
                        logger.info("QModelImportPage::onSubmit MAX_SIZE size" + upload.getSize());
                    } else {
                        logger.info("QModelImportPage::onSubmit file name " + upload.getClientFileName()
                                + " File-Size: " + Bytes.bytes(upload.getSize()).toString() + "content-type "
                                + upload.getContentType());

                        user = UQasar.getSession().getLoggedInUser();
                        if (user.getCompany() != null) {
                            company = companyService.getById(user.getCompany().getId());
                        }

                        if (upload.getContentType() != null && upload.getContentType().equals(XML_CONTENT)) {
                            //parsing
                            qm = parse(upload, true);
                        } else if (upload.getContentType() != null
                                && (upload.getContentType().equals(JSON_CONTENT)
                                        || upload.getContentType().equals(OCT_CONTENT))) {
                            //json candidate
                            qm = parse(upload, false);
                        } else {
                            //file not valid
                            errorMessage = "qmodel.type.file.error";
                        }
                    }
                }

                if (qm != null) {
                    qm.setUpdateDate(DateTime.now().toDate());
                    if (qm.getCompanyId() != 0) {
                        qm.setCompany(companyService.getById(qm.getCompanyId()));
                    } else {
                        if (company != null) {
                            qm.setCompany(company);
                            qm.setCompanyId(company.getId());
                        }
                    }
                    qm = (QModel) qmodelService.create(qm);
                }
            } catch (uQasarException ex) {
                if (ex.getMessage().contains("nodeKey")) {
                    errorMessage = "qmodel.key.unique";
                }
            } catch (JsonProcessingException ex) {
                logger.info("JsonProcessingException----------------------------------------");
                if (ex.getMessage().contains("expecting comma to separate ARRAY entries")) {
                    errorMessage = "qmodel.json.parse.error";
                } else if (ex.getMessage().contains("Unexpected character")) {
                    errorMessage = "qmodel.json.char.error";
                } else if (ex.getMessage().contains("Can not construct instance")) {
                    errorMessage = "qmodel.json.enum.error";
                } else {
                    logger.info("JsonProcessingException----------------------------");
                    errorMessage = "qmodel.xml.parse.error";
                }
            } catch (JAXBException ex) {
                logger.info("JAXBException----------------------------");
                errorMessage = "qmodel.xml.parse.error";
            } catch (Exception ex) {
                logger.info("IOException----------------------------");
                errorMessage = "qmodel.import.importError";
            } finally {
                PageParameters parameters = new PageParameters();
                if (null != errorMessage && !errorMessage.equals("")) {
                    logger.info("Attaching error message");
                    parameters.add(QModelImportPage.LEVEL_PARAM, FeedbackMessage.ERROR);
                    parameters.add(QModelImportPage.MESSAGE_PARAM,
                            getLocalizer().getString(errorMessage, this));
                    setResponsePage(QModelImportPage.class, parameters);
                } else {

                    logger.info("qmodel successfully created: redirection");
                    //qmodel successfully created: redirection
                    parameters.add(BasePage.LEVEL_PARAM, FeedbackMessage.SUCCESS);
                    parameters.add(BasePage.MESSAGE_PARAM,
                            getLocalizer().getString("treenode.imported.message", this));
                    parameters.add("qmodel-key", qm.getNodeKey());
                    parameters.add("name", qm.getName());
                    setResponsePage(QModelViewPage.class, parameters);
                }
            }
        }
    };

    // create the file upload field
    file = new FileUploadField("file");
    form.addOrReplace(file);

    form.add(new Label("max", new AbstractReadOnlyModel<String>() {
        /**
         *
         */
        private static final long serialVersionUID = 3532428309651830468L;

        @Override
        public String getObject() {
            return (Bytes.kilobytes(MAX_SIZE)).toString();
        }
    }));

    // add progress bar
    form.add(new UploadProgressBar("progress", form, file));

    ServletContext context = ((WebApplication) getApplication()).getServletContext();
    // Download xml example
    File filexml = new File(context.getRealPath("/assets/files/qmodel.xml"));
    DownloadLink xmlLink = new DownloadLink("xmlLink", filexml);
    form.add(xmlLink);

    // Download json example
    File filejson = new File(context.getRealPath("/assets/files/qmodel.json"));
    DownloadLink jsonLink = new DownloadLink("jsonLink", filejson);
    form.add(jsonLink);

    add(form);

    logger.info("QModelImportPage::QModelImportPage ends");
}

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

License:Apache License

public ProjectImportPage(PageParameters parameters) {
    super(parameters);

    upload = new FileUploadField("file");

    final Form<?> form = new Form<Void>("form") {

        private static final long serialVersionUID = -8541751079487127243L;

        @Override//ww w .j  av  a  2s  . c  om
        protected void onSubmit() {
            Project p = null;
            try {
                FileUpload file = upload.getFileUpload();
                if (file == null) {
                    logger.info("File upload failed");
                    error = true;
                } else {
                    if (file.getSize() > Bytes.kilobytes(MAX_SIZE).bytes()) {
                        logger.info("File is too big");
                        error = true;
                    } else {
                        String content = file.getContentType();
                        if (content != null) {
                            logger.info("Parser called");
                            p = parseProject(file, content);
                            p = (Project) treeNodeService.create(p);

                            // set company to qmodel
                            user = UQasar.getSession().getLoggedInUser();
                            if (user != null && user.getCompany() != null) {
                                p.setCompany(user.getCompany());
                            }
                        } else {
                            logger.info("Upload file is invalid");
                            error = true;
                        }
                    }
                }
            } catch (uQasarException ex) {
                if (ex.getMessage().contains("nodeKey")) {
                    error = true;
                    logger.info("duplicated nodeKey");
                    errorMessage = "import.key.unique";
                }
            } catch (Exception ex) {
                error = true;
                logger.error(ex.getMessage(), ex);
            } finally {
                PageParameters parameters = new PageParameters();

                if (error) {
                    parameters.add(BasePage.LEVEL_PARAM, FeedbackMessage.ERROR);

                    if (errorMessage != null && errorMessage.contains("key")) {
                        parameters.add(QModelImportPage.MESSAGE_PARAM,
                                getLocalizer().getString(errorMessage, this));
                    } else {
                        parameters.add(BasePage.MESSAGE_PARAM,
                                getLocalizer().getString("import.importError", this));
                    }
                    setResponsePage(ProjectImportPage.class, parameters);
                } else {
                    parameters.add(BasePage.LEVEL_PARAM, FeedbackMessage.SUCCESS);
                    parameters.add(BasePage.MESSAGE_PARAM,
                            getLocalizer().getString("import.importMessage", this));
                    // TODO what if p == null?
                    parameters.add("project-key", p != null ? p.getNodeKey() : "?");
                    setResponsePage(ProjectViewPage.class, parameters);
                }
            }
        }
    };
    form.add(upload);
    form.setMaxSize(Bytes.kilobytes(MAX_SIZE));
    form.add(new Label("max", new AbstractReadOnlyModel<String>() {

        private static final long serialVersionUID = 3532428309651830468L;

        @Override
        public String getObject() {
            return form.getMaxSize().toString();
        }
    }));

    form.add(new UploadProgressBar("progress", form, upload));
    form.add(new Button("uploadButton", new StringResourceModel("upload.button", this, null)));

    add(form);

}

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

License:Open Source License

protected Map<String, FileUpload> getNonNullUploads() {
    // only keeps the non-null file uploads
    // TODO: add number suffix to simple attachment keys, enable multiple file uploads
    Map<String, FileUpload> fileUploads = new HashMap<String, FileUpload>();
    for (String fileUploadKey : fileUploadFields.keySet()) {
        FileUploadField fileUploadField = fileUploadFields.get(fileUploadKey);
        FileUpload fileUpload = fileUploadField.getFileUpload();
        if (fileUploadKey.equalsIgnoreCase(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT)) {
            fileUploadKey = Field.FIELD_TYPE_SIMPLE_ATTACHEMENT;
        }/*from  w w w  .ja  v  a  2s .  c  om*/
        logger.debug("Upload Field " + fileUploadKey + " FileUpload: " + fileUpload);
        if (fileUpload != null && fileUpload.getSize() > 0) {
            fileUploads.put(fileUploadKey, fileUpload);
        }
    }
    logger.debug("Returning fileUploads: " + fileUploads);
    return fileUploads;
}