Example usage for org.apache.wicket.util.lang Bytes megabytes

List of usage examples for org.apache.wicket.util.lang Bytes megabytes

Introduction

In this page you can find the example usage for org.apache.wicket.util.lang Bytes megabytes.

Prototype

public static Bytes megabytes(final double megabytes) 

Source Link

Document

Instantiate immutable Bytes value object..

Usage

From source file:com.apachecon.memories.UploadForm.java

License:Apache License

public UploadForm(String id, List<String> contentTypes) {
    super(id);//from   w w w . ja va  2 s.co  m
    this.contentTypes = contentTypes;

    setMultiPart(true);
    setMaxSize(Bytes.megabytes(2));

    add(uploadField = new FileUploadField("uploadField"));
    uploadField.setRequired(true);
    add(new SubmitLink("submit"));
}

From source file:com.locke.tricks.u.U.java

License:Apache License

@SuppressWarnings("unchecked")
public U() {/* ww  w .jav  a 2 s  .  c  om*/

    final IColumn<Utility>[] columns = new IColumn[2];
    columns[0] = new PropertyColumn<Utility>(new Model<String>("Code"), "code", "code");
    columns[1] = new PropertyColumn<Utility>(new Model<String>("Output"), "output", "output");

    final DataTable<Utility> dataTable = new DataTable<Utility>("utilities", columns,
            this.utilitiesDataProvider, Integer.MAX_VALUE);
    dataTable.addTopToolbar(new HeadersToolbar(dataTable, new ISortStateLocator() {

        private ISortState sortState = new SingleSortState();

        public ISortState getSortState() {
            return this.sortState;
        }

        public void setSortState(final ISortState state) {
            this.sortState = state;
        }
    }));
    add(dataTable);

    this.utilities.add(new Utility("Time.now().toString()") {

        @Override
        public String getOutput() {
            return Time.now().toString();
        }
    });
    this.utilities.add(new Utility("Duration.ONE_WEEK.toString()") {

        @Override
        public String getOutput() {
            return Duration.ONE_WEEK.toString();
        }
    });
    this.utilities.add(new Utility("Duration.ONE_WEEK.add(Duration.ONE_DAY).toString()") {

        @Override
        public String getOutput() {
            return Duration.ONE_WEEK.add(Duration.ONE_DAY).toString();
        }
    });
    this.utilities.add(new Utility("Time.now().add(Duration.ONE_WEEK).toString()") {

        @Override
        public String getOutput() {
            return Time.now().add(Duration.ONE_WEEK).toString();
        }
    });
    this.utilities.add(new Utility("Bytes.valueOf(\"512K\") + Bytes.megabytes(1.3)") {

        @Override
        public String getOutput() {
            return Bytes.bytes(Bytes.valueOf("512K").bytes() + Bytes.megabytes(1.3).bytes()).toString();
        }
    });
    this.utilities.add(new Utility("Parsing \'13 + 13\' using MetaPattern") {

        @Override
        public String getOutput() {
            final IntegerGroup a = new IntegerGroup(MetaPattern.DIGITS);
            final IntegerGroup b = new IntegerGroup(MetaPattern.DIGITS);
            final MetaPattern sum = new MetaPattern(new MetaPattern[] { a, MetaPattern.OPTIONAL_WHITESPACE,
                    MetaPattern.PLUS, MetaPattern.OPTIONAL_WHITESPACE, b });
            final Matcher matcher = sum.matcher("13 + 13");
            if (matcher.matches()) {
                return Integer.toString(a.getInt(matcher) + b.getInt(matcher));
            }
            return "Failed to match.";
        }
    });
}

From source file:com.senacor.wbs.web.WorkBreakdownStructureApplication.java

License:Apache License

@Override
protected void init() {
    super.init();
    if (spring) {
        // THIS LINE IS IMPORTANT - IT INSTALLS THE COMPONENT
        // INJECTOR THAT WILL
        // INJECT NEWLY CREATED COMPONENTS WITH THEIR SPRING
        // DEPENDENCIES
        addComponentInstantiationListener(new SpringComponentInjector(this));
    }//w w w  .  j  a v a 2s . co m
    // Autolink-Verhalten grundstzlich einschalten
    // getMarkupSettings().setAutomaticLinking(true);
    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(50));
    // Standard-Encoding fr Markup-Files
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    // Setzt im Response-Header Character encoding
    // d h.: Content-Type text/html;charset=<encoding>
    getRequestCycleSettings().setResponseRequestEncoding("utf-8");
    // getMarkupSettings().setStripWicketTags(true);
    // maximal 3 PageMaps verwalten (default 5)
    // eine PageMap pro Browserfenster
    getSessionSettings().setMaxPageMaps(3);
    getSessionSettings().setPageMapEvictionStrategy(new LeastRecentlyAccessedEvictionStrategy(3));
    getDebugSettings().setOutputMarkupContainerClassName(true);
    getDebugSettings().setLinePreciseReportingOnAddComponentEnabled(true);
    getDebugSettings().setLinePreciseReportingOnNewComponentEnabled(true);
    mountBookmarkablePage("/start", StartPage.class);
    mountBookmarkablePage("/gmap", GMapsPage.class);
    // Damit werden Komponentenresourcen wie Templates,
    // css, images, etc
    // zustzlich unter <web-content-root>/html gesucht
    getResourceSettings().addResourceFolder("/html");
}

From source file:com.senacor.wbs.web.WorkBreakdownStructureApplication.java

License:Apache License

/**
 * @see org.apache.wicket.Application#newSessionStore()
 *///  w ww.ja  v a  2s  .  com
/*
 * protected ISessionStore newSessionStore() { return new
 * HttpSessionStore(this) { public IPageVersionManager
 * newVersionManager(Page page) { // maximal 5 Versionen einer Seite
 * verwalten (default // 20) return new UndoPageVersionManager(page, 2); }
 * }; }
 */
@Override
protected ISessionStore newSessionStore() {
    return new SecondLevelCacheSessionStore(this,
            new DiskPageStore((int) Bytes.megabytes(20).bytes(), (int) Bytes.megabytes(500).bytes(), 50));
}

From source file:cz.zcu.kiv.eegdatabase.wui.ui.licenses.components.LicenseRequestForm.java

License:Apache License

private void addComponents() {
    FormComponent c = new RequiredTextField("firstName", new PropertyModel(persLicense, "firstName"));
    c.setLabel(ResourceUtils.getModel("label.license.request.firstname"));
    form.add(c);/* w ww  .  ja  v  a  2  s . co m*/

    c = new RequiredTextField("lastName", new PropertyModel(persLicense, "lastName"));
    c.setLabel(ResourceUtils.getModel("label.license.request.lastname"));
    form.add(c);

    c = new RequiredTextField("organisation", new PropertyModel(persLicense, "organisation"));
    c.setLabel(ResourceUtils.getModel("label.license.request.organisation"));
    form.add(c);

    c = new RequiredTextField("email", new PropertyModel(persLicense, "email"));
    c.add(EmailAddressValidator.getInstance());
    c.setLabel(ResourceUtils.getModel("label.license.request.email"));
    form.add(c);

    uploadField = new FileUploadField("attachement");
    uploadField.setLabel(ResourceUtils.getModel("label.license.request.attachement"));
    form.add(uploadField);
    form.setMaxSize(Bytes.megabytes(15));

    WicketUtils.addLabelsAndFeedback(form);
}

From source file:eu.esdihumboldt.hale.server.projects.war.components.UploadForm.java

License:Open Source License

/**
 * @see Form#Form(String)//w  w w  . j a  v  a  2 s .  c om
 */
public UploadForm(String id) {
    super(id);

    // multipart always needed for uploads
    setMultiPart(true);

    // input field for identifier text
    identifier = new TextField<String>("identifier", new Model<String>());
    // pattern validator
    identifier.add(new PatternValidator("[A-Za-z0-9 _\\-]+"));
    // validator that checks if the project name is already taken
    identifier.add(new IValidator<String>() {

        private static final long serialVersionUID = 275885544279441469L;

        @Override
        public void validate(IValidatable<String> validatable) {
            String name = validatable.getValue();
            for (String project : projects.getResources()) {
                // ignore case to avoid confusion
                if (name.equalsIgnoreCase(project)) {
                    validatable.error(new ValidationError().setMessage("Identifier already in use"));
                    break;
                }
            }
        }
    });
    FieldMessage identifierMessage = new FieldMessage("identifierMessage",
            new Model<String>("Unique identifier for the project"), identifier);
    identifier.add(new FieldValidatingBehavior("onblur", identifierMessage));
    identifier.setOutputMarkupId(true);
    identifier.setRequired(true);
    //      identifier.add(new DefaultFocus()); XXX not working well with ajax
    add(identifier);
    add(identifierMessage);

    // Add one file input field
    add(file = new FileUploadField("file"));
    add(new FeedbackPanel("feedback"));

    addAllowedContentType("application/zip");
    addAllowedContentType("application/x-zip");
    addAllowedContentType("application/x-zip-compressed");
    addAllowedContentType("application/octet-stream");

    //      setCustomTypeErrorMessage("Only ZIP archives are supported for upload");

    setMaxSize(Bytes.megabytes(20));
}

From source file:eu.esdihumboldt.hale.server.templates.war.components.TemplateUploadForm.java

License:Open Source License

/**
 * Constructor//from  w  ww  .  j ava  2  s .com
 * 
 * @param id the component ID
 * @param templateId the identifier of the template to update, or
 *            <code>null</code> to create a new template
 */
public TemplateUploadForm(String id, String templateId) {
    super(id);
    this.templateId = templateId;

    Form<Void> form = new Form<Void>("upload") {

        private static final long serialVersionUID = 716487990605324922L;

        @Override
        protected void onSubmit() {
            List<FileUpload> uploads = file.getFileUploads();
            if (uploads != null && !uploads.isEmpty()) {
                final boolean newTemplate = TemplateUploadForm.this.templateId == null;
                final String templateId;
                final File dir;
                File oldContent = null;
                if (newTemplate) {
                    // attempt to reserve template ID
                    Pair<String, File> template;
                    try {
                        template = templates.reserveResource(determinePreferredId(uploads));
                    } catch (ScavengerException e) {
                        error(e.getMessage());
                        return;
                    }
                    templateId = template.getFirst();
                    dir = template.getSecond();
                } else {
                    templateId = TemplateUploadForm.this.templateId;
                    dir = new File(templates.getHuntingGrounds(), templateId);

                    // archive old content
                    try {
                        Path tmpFile = Files.createTempFile("hale-template", ".zip");
                        try (OutputStream out = Files.newOutputStream(tmpFile);
                                ZipOutputStream zos = new ZipOutputStream(out)) {
                            IOUtils.zipDirectory(dir, zos);
                        }
                        oldContent = tmpFile.toFile();
                    } catch (IOException e) {
                        log.error("Error saving old template content to archive", e);
                    }

                    // delete old content
                    try {
                        FileUtils.cleanDirectory(dir);
                    } catch (IOException e) {
                        log.error("Error deleting old template content", e);
                    }
                }

                try {
                    for (FileUpload upload : uploads) {
                        if (isZipFile(upload)) {
                            // extract uploaded file
                            IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream()));
                        } else {
                            // copy uploaded file
                            File target = new File(dir, upload.getClientFileName());
                            ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target));
                        }
                    }

                    // trigger scan after upload
                    if (newTemplate) {
                        templates.triggerScan();
                    } else {
                        templates.forceUpdate(templateId);
                    }

                    TemplateProject ref = templates.getReference(templateId);
                    if (ref != null && ref.isValid()) {
                        info("Successfully uploaded project");
                        boolean infoUpdate = (updateInfo != null) ? (updateInfo.getModelObject()) : (false);
                        onUploadSuccess(this, templateId, ref.getProjectInfo(), infoUpdate);
                    } else {
                        if (newTemplate) {
                            templates.releaseResourceId(templateId);
                        } else {
                            restoreContent(dir, oldContent);
                        }
                        error((ref != null) ? (ref.getNotValidMessage())
                                : ("Uploaded files could not be loaded as HALE project"));
                    }

                } catch (Exception e) {
                    if (newTemplate) {
                        templates.releaseResourceId(templateId);
                    } else {
                        restoreContent(dir, oldContent);
                    }
                    log.error("Error while uploading file", e);
                    error("Error saving the file");
                }
            } else {
                warn("Please provide a file for upload");
            }
        }

        @Override
        protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
            if (e instanceof SizeLimitExceededException) {
                final String msg = "Only files up to  " + bytesToString(getMaxSize(), Locale.US)
                        + " can be uploaded.";
                error(msg);
            } else {
                final String msg = "Error uploading the file: " + e.getLocalizedMessage();
                error(msg);

                log.warn(msg, e);
            }
        }

    };
    add(form);

    // multipart always needed for uploads
    form.setMultiPart(true);

    // max size for upload
    if (UserUtil.isAdmin()) {
        // admin max upload size
        form.setMaxSize(Bytes.megabytes(100));
    } else {
        // normal user max upload size
        // TODO differentiate between logged in and anonymous user?
        form.setMaxSize(Bytes.megabytes(15));
    }

    // Add file input field for multiple files
    form.add(file = new FileUploadField("file"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // add anonym/recaptcha panel
    boolean loggedIn = UserUtil.getLogin() != null;
    WebMarkupContainer anonym = new WebMarkupContainer("anonym");

    if (loggedIn) {
        anonym.add(new WebMarkupContainer("recaptcha"));
    } else {
        anonym.add(new RecaptchaPanel("recaptcha"));
    }

    anonym.add(
            new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass()));

    anonym.setVisible(!loggedIn);
    form.add(anonym);

    // update panel
    WebMarkupContainer update = new WebMarkupContainer("update");
    update.setVisible(templateId != null);

    updateInfo = new CheckBox("updateInfo", Model.of(true));
    update.add(updateInfo);

    form.add(update);

    // feedback panel
    form.add(new BootstrapFeedbackPanel("feedback"));
}

From source file:eu.esdihumboldt.hale.server.templates.war.components.UploadForm.java

License:Open Source License

/**
 * @see Panel#Panel(String)//from w  w  w .  jav a2 s.  c  om
 */
public UploadForm(String id) {
    super(id);

    Form<Void> form = new Form<Void>("upload") {

        private static final long serialVersionUID = 716487990605324922L;

        @Override
        protected void onSubmit() {
            // attempt to reserve template ID
            Pair<String, File> template;
            try {
                template = templates.reserveResource(null);
            } catch (ScavengerException e) {
                error(e.getMessage());
                return;
            }
            final String templateId = template.getFirst();
            final File dir = template.getSecond();

            try {
                List<FileUpload> uploads = file.getFileUploads();
                if (uploads != null && !uploads.isEmpty()) {
                    for (FileUpload upload : uploads) {
                        if (isZipFile(upload)) {
                            // extract uploaded file
                            IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream()));
                        } else {
                            // copy uploaded file
                            File target = new File(dir, upload.getClientFileName());
                            ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target));
                        }
                    }

                    // trigger scan after upload
                    templates.triggerScan();

                    ProjectReference<Void> ref = templates.getReference(templateId);
                    if (ref != null && ref.getProjectInfo() != null) {
                        info("Successfully uploaded project");
                        onUploadSuccess(this, templateId, ref.getProjectInfo());
                    } else {
                        templates.releaseResourceId(templateId);
                        error("Uploaded files could not be loaded as HALE project");
                    }
                } else {
                    templates.releaseResourceId(templateId);
                    warn("Please provide a file for upload");
                }
            } catch (Exception e) {
                templates.releaseResourceId(templateId);
                log.error("Error while uploading file", e);
                error("Error saving the file");
            }
        }

        @Override
        protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
            if (e instanceof SizeLimitExceededException) {
                final String msg = "Only files up to  " + bytesToString(getMaxSize(), Locale.US)
                        + " can be uploaded.";
                error(msg);
            } else {
                final String msg = "Error uploading the file: " + e.getLocalizedMessage();
                error(msg);

                log.warn(msg, e);
            }
        }

    };
    add(form);

    // multipart always needed for uploads
    form.setMultiPart(true);

    // max size for upload
    form.setMaxSize(Bytes.megabytes(1));

    // Add file input field for multiple files
    form.add(file = new FileUploadField("file"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // add anonym/recaptcha panel
    boolean loggedIn = UserUtil.getLogin() != null;
    WebMarkupContainer anonym = new WebMarkupContainer("anonym");

    if (loggedIn) {
        anonym.add(new WebMarkupContainer("recaptcha"));
    } else {
        anonym.add(new RecaptchaPanel("recaptcha"));
    }

    anonym.add(
            new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass()));

    anonym.setVisible(!loggedIn);
    form.add(anonym);

    // feedback panel
    form.add(new BootstrapFeedbackPanel("feedback"));
}

From source file:it.av.eatt.web.page.RistoranteEditPicturePage.java

License:Apache License

/**
 * @param parameters// www .j  av a  2s.  c  o  m
 * @throws JackWicketException
 */
public RistoranteEditPicturePage(PageParameters parameters) throws JackWicketException {

    String ristoranteId = parameters.getString("ristoranteId", "");
    if (StringUtils.isNotBlank(ristoranteId)) {
        this.ristorante = ristoranteService.getByID(ristoranteId);
    } else {
        setRedirect(true);
        setResponsePage(getApplication().getHomePage());
    }

    form = new Form<Ristorante>("ristorantePicturesForm");
    add(form);
    form.setOutputMarkupId(true);
    form.setMultiPart(true);
    form.setMaxSize(Bytes.megabytes(1));
    uploadField = new FileUploadField("uploadField");
    form.add(uploadField);
    form.add(new UploadProgressBar("progressBar", form));
    form.add(new SubmitButton("submitForm", form));

    picturesList = new ListView<RistorantePicture>("picturesList", ristorante.getPictures()) {
        @Override
        protected void populateItem(final ListItem<RistorantePicture> item) {
            //Button disabled, because the getPicture is not yet implemented
            item.add(new AjaxFallbackButton("publish-unpublish", form) {
                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    item.getModelObject().setActive(!item.getModelObject().isActive());
                    try {
                        ristorantePictureService.save(item.getModelObject());
                        ristorante = ristoranteService.getByID(ristorante.getId());
                    } catch (JackWicketException e) {
                        error(getString("genericErrorMessage"));
                    }
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                        target.addComponent(form);
                    }
                }

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    if (item.getModelObject().isActive()) {
                        tag.getAttributes().put("title", getString("button.unpublish"));
                        tag.getAttributes().put("class", "unpublishPictureButton");
                    } else {
                        tag.getAttributes().put("title", getString("button.publish"));
                        tag.getAttributes().put("class", "publishPictureButton");
                    }
                }
            }.setVisible(false));
            item.add(new AjaxFallbackButton("remove", form) {
                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    try {
                        RistorantePicture picture = item.getModelObject();
                        ristorante.getPictures().remove(picture);
                        ristoranteService.updateNoRevision(ristorante);
                        ristorantePictureService.remove(picture);
                        ristorante = ristoranteService.getByID(ristorante.getId());
                    } catch (JackWicketException e) {
                        error(getString("genericErrorMessage"));
                    }
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                        target.addComponent(form);
                    }
                }
            });
            item.add(new Image("picture", new DynamicImageResource() {
                @Override
                protected byte[] getImageData() {
                    return item.getModelObject().getPicture();
                }
            }));
        }
    };
    picturesList.setOutputMarkupId(true);
    picturesList.setReuseItems(true);
    form.add(picturesList);

}

From source file:it.av.youeat.web.page.BaseEaterAccountPage.java

License:Apache License

public BaseEaterAccountPage(PageParameters pageParameters) {
    if (!pageParameters.getNamedKeys().contains(YoueatHttpParams.YOUEAT_ID)) {
        throw new YoueatException("Missing user id");
    }/*from   www .j  ava2 s  . c o  m*/
    String eaterId = pageParameters.get(YoueatHttpParams.YOUEAT_ID).toString("");
    eater = eaterService.getByID(eaterId);

    accountForm = new Form<Eater>("account", new CompoundPropertyModel<Eater>(eater));
    accountForm.setOutputMarkupId(true);
    add(accountForm);
    accountForm.add(new RequiredTextField<String>("firstname"));
    accountForm.add(new RequiredTextField<String>("lastname"));
    DropDownChoice<Country> country = new DropDownChoice<Country>(Eater.COUNTRY, countryService.getAll());
    country.setRequired(true);
    accountForm.add(country);
    accountForm.add(new DropDownChoice<Language>("language", languageService.getAll(), new LanguageRenderer()));

    Form formAvatar = new Form("formAvatar");
    add(formAvatar);
    formAvatar.setOutputMarkupId(true);
    formAvatar.setMultiPart(true);
    formAvatar.setMaxSize(Bytes.megabytes(1));
    FileUploadField uploadField = new FileUploadField("uploadField");
    formAvatar.add(uploadField);
    // formAvatar.add(new UploadProgressBar("progressBar", accountForm));
    formAvatar.add(new SubmitAvatarButton("submitForm", formAvatar));
    imagecontatiner = new WebMarkupContainer("imageContainer");
    imagecontatiner.setOutputMarkupId(true);
    formAvatar.add(imagecontatiner);

    avatar = new NonCachingImage("avatar", new ImageAvatarResource(eater));
    avatar.setOutputMarkupPlaceholderTag(true);
    imagecontatiner.add(avatar);
    avatarDefault = ImagesAvatar.getAvatar("avatarDefault", eater, this, true);
    if (eater.getAvatar() != null) {
        avatarDefault.setVisible(false);
    } else {
        avatar.setVisible(false);
    }
    imagecontatiner.add(avatarDefault);

}