Example usage for org.apache.wicket.request.handler.resource ResourceStreamRequestHandler setFileName

List of usage examples for org.apache.wicket.request.handler.resource ResourceStreamRequestHandler setFileName

Introduction

In this page you can find the example usage for org.apache.wicket.request.handler.resource ResourceStreamRequestHandler setFileName.

Prototype

public final ResourceStreamRequestHandler setFileName(String fileName) 

Source Link

Usage

From source file:com.evolveum.midpoint.web.component.AbstractAjaxDownloadBehavior.java

License:Apache License

public void onRequest() {

    IResourceStream resourceStream = getResourceStream();
    if (resourceStream == null) {
        return; // We hope the error was already processed and will be shown.
    }/*from  www.j a  va 2 s  . c o  m*/

    ResourceStreamRequestHandler reqHandler = new ResourceStreamRequestHandler(resourceStream) {
        @Override
        public void respond(IRequestCycle requestCycle) {
            super.respond(requestCycle);
        }
    }.setContentDisposition(ContentDisposition.ATTACHMENT).setCacheDuration(Duration.ONE_SECOND);
    if (StringUtils.isNotEmpty(getFileName())) {
        reqHandler.setFileName(getFileName());
    }
    getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(reqHandler);
}

From source file:com.swordlord.gozer.components.wicket.action.button.generic.GWCsvButton.java

License:Open Source License

@Override
public void onSubmit() {
    // TODO/*from  w  w w  .j  a va  2  s  .c om*/
    IGozerFrameExtension gfe = getGozerController().getGozerFrameExtension();
    ExcelRenderer renderer = new ExcelRenderer(getObjectTree(gfe), gfe, getApplication(),
            (IGozerSessionInfo) getSession());
    Workbook wb = renderer.renderTree();

    if (wb == null) {
        LOG.warn("Rendered ObjectTree is empty. Cancelling Excel rendering.");
        return;
    }

    ResourceStreamRequestHandler target = createTarget(wb);
    if (target == null) {
        // TODO: warn the user!!!
        return;
    } else {
        target.setFileName(gfe.getCaption().toLowerCase() + ".xls");
        RequestCycle.get().scheduleRequestHandlerAfterCurrent(target);
    }
}

From source file:com.swordlord.gozer.components.wicket.action.button.generic.GWFopButton.java

License:Open Source License

@Override
public void onSubmit() {
    IGozerSessionInfo session = getGozerSession();

    FopTemplateManager ftm = FopTemplateManager.instance();

    // make sure they are reloaded every time we use the template manager
    // TODO: probably undo this and have a special singleton reset mechanism
    ftm.initialiseTemplates();// w w w  .  jav  a2 s .  co  m

    // TODO
    IGozerFrameExtension gfe = getGozerController().getGozerFrameExtension();
    FopRenderer renderer = new FopRenderer(getObjectTree(gfe), gfe, getApplication(), session);

    String fop = renderer.renderTree();

    ResourceStreamRequestHandler target = convertFO2PDF(fop, session.getCurrentUser().toString(),
            gfe.getCaption());

    if (target == null) {
        // TODO: warn the user!!!
        return;
    } else {
        target.setFileName(gfe.getCaption().toLowerCase() + ".pdf");

        //rc.getResponse().setCharacterEncoding("ISO-8859-1");
        //LOG.info(MessageFormat.format("Current character encoding for response: {0}", rc.getResponse().getCharacterEncoding()));

        RequestCycle.get().scheduleRequestHandlerAfterCurrent(target);
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.components.utils.FileUtils.java

License:Apache License

/**
 * Prepared request handler for file download.
 * //from w w  w.  j  av a  2  s  .co m
 * @param file
 * @return
 */
public static ResourceStreamRequestHandler prepareDownloadFile(final FileDTO file) {

    if (file == null || file.getFile() == null)
        return null;

    IResourceStream stream = new FileResourceStream(file.getFile());

    ResourceStreamRequestHandler resourceStreamRequestHandler = new ResourceStreamRequestHandler(stream) {

        @Override
        public void detach(IRequestCycle requestCycle) {
            super.detach(requestCycle);

            if (!Files.remove(file.getFile())) {
                log.error("Temporary file " + file.getFile().getAbsolutePath() + " cannot be deleted.");
            }
        }
    };
    return resourceStreamRequestHandler.setFileName(file.getFileName())
            .setContentDisposition(ContentDisposition.ATTACHMENT);
}

From source file:org.apache.syncope.client.console.pages.BasePage.java

License:Apache License

public BasePage(final PageParameters parameters) {
    super(parameters);

    // Native WebSocket
    add(new WebSocketBehavior() {

        private static final long serialVersionUID = 3109256773218160485L;

        @Override//  ww  w .  j  a v  a2s. c  om
        protected void onConnect(final ConnectedMessage message) {
            super.onConnect(message);

            SyncopeConsoleSession.get().scheduleAtFixedRate(new ApprovalsWidget.ApprovalInfoUpdater(message), 0,
                    30, TimeUnit.SECONDS);

            if (BasePage.this instanceof Dashboard) {
                SyncopeConsoleSession.get().scheduleAtFixedRate(new JobWidget.JobInfoUpdater(message), 0, 10,
                        TimeUnit.SECONDS);
                SyncopeConsoleSession.get().scheduleAtFixedRate(
                        new ReconciliationWidget.ReconciliationJobInfoUpdater(message), 0, 10,
                        TimeUnit.SECONDS);
            }
        }

    });

    body = new WebMarkupContainer("body");
    Serializable leftMenuCollapse = SyncopeConsoleSession.get()
            .getAttribute(SyncopeConsoleSession.MENU_COLLAPSE);
    if ((leftMenuCollapse instanceof Boolean) && ((Boolean) leftMenuCollapse)) {
        body.add(new AttributeAppender("class", " sidebar-collapse"));
    }
    add(body);

    notificationPanel = new NotificationPanel(Constants.FEEDBACK);
    body.addOrReplace(notificationPanel.setOutputMarkupId(true));

    // header, footer
    body.add(new Label("version", SyncopeConsoleApplication.get().getVersion()));
    body.add(new Label("username", SyncopeConsoleSession.get().getSelfTO().getUsername()));

    body.add(new ApprovalsWidget("approvalsWidget", getPageReference()).setRenderBodyOnly(true));

    // right sidebar
    SystemInfo systemInfo = SyncopeConsoleSession.get().getSystemInfo();
    body.add(new Label("hostname", systemInfo.getHostname()));
    body.add(new Label("processors", systemInfo.getAvailableProcessors()));
    body.add(new Label("os", systemInfo.getOs()));
    body.add(new Label("jvm", systemInfo.getJvm()));

    Link<Void> dbExportLink = new Link<Void>("dbExportLink") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick() {
            try {
                HttpResourceStream stream = new HttpResourceStream(new ConfigurationRestClient().dbExport());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(
                        stream.getFilename() == null ? SyncopeConsoleSession.get().getDomain() + "Content.xml"
                                : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                SyncopeConsoleSession.get().error(getString(Constants.ERROR) + ": " + e.getMessage());
            }
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(dbExportLink, WebPage.ENABLE,
            StandardEntitlement.CONFIGURATION_EXPORT);
    body.add(dbExportLink);

    // menu
    WebMarkupContainer liContainer = new WebMarkupContainer(getLIContainerId("dashboard"));
    body.add(liContainer);
    liContainer.add(BookmarkablePageLinkBuilder.build("dashboard", Dashboard.class));

    liContainer = new WebMarkupContainer(getLIContainerId("realms"));
    body.add(liContainer);
    BookmarkablePageLink<? extends BasePage> link = BookmarkablePageLinkBuilder.build("realms", Realms.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.REALM_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("topology"));
    body.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("topology", Topology.class);
    StringBuilder bld = new StringBuilder();
    bld.append(StandardEntitlement.CONNECTOR_LIST).append(",").append(StandardEntitlement.RESOURCE_LIST)
            .append(",");
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, bld.toString());
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("reports"));
    body.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("reports", Reports.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.REPORT_LIST);
    liContainer.add(link);

    WebMarkupContainer confLIContainer = new WebMarkupContainer(getLIContainerId("configuration"));
    body.add(confLIContainer);
    WebMarkupContainer confULContainer = new WebMarkupContainer(getULContainerId("configuration"));
    confLIContainer.add(confULContainer);

    liContainer = new WebMarkupContainer(getLIContainerId("workflow"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("workflow", Workflow.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.WORKFLOW_DEF_READ);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("audit"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("audit", Audit.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.AUDIT_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("logs"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("logs", Logs.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.LOG_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("securityquestions"));
    confULContainer.add(liContainer);
    bld = new StringBuilder();
    bld.append(StandardEntitlement.SECURITY_QUESTION_CREATE).append(",")
            .append(StandardEntitlement.SECURITY_QUESTION_DELETE).append(",")
            .append(StandardEntitlement.SECURITY_QUESTION_UPDATE);
    link = BookmarkablePageLinkBuilder.build("securityquestions", SecurityQuestions.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, bld.toString());
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("types"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("types", Types.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.SCHEMA_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("roles"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("roles", Roles.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.ROLE_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("policies"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("policies", Policies.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.POLICY_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("notifications"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("notifications", Notifications.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.NOTIFICATION_LIST);
    liContainer.add(link);

    liContainer = new WebMarkupContainer(getLIContainerId("parameters"));
    confULContainer.add(liContainer);
    link = BookmarkablePageLinkBuilder.build("parameters", Parameters.class);
    MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, StandardEntitlement.CONFIGURATION_LIST);
    liContainer.add(link);

    body.add(new AjaxLink<Void>("collapse") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            SyncopeConsoleSession.get().setAttribute(SyncopeConsoleSession.MENU_COLLAPSE,
                    SyncopeConsoleSession.get().getAttribute(SyncopeConsoleSession.MENU_COLLAPSE) == null ? true
                            : !(Boolean) SyncopeConsoleSession.get()
                                    .getAttribute(SyncopeConsoleSession.MENU_COLLAPSE));
        }
    });
    body.add(new Label("domain", SyncopeConsoleSession.get().getDomain()));
    body.add(new BookmarkablePageLink<Page>("logout", Logout.class));

    // set 'active' menu item for everything but extensions
    // 1. check if current class is set to top-level menu
    Component containingLI = body.get(getLIContainerId(getClass().getSimpleName().toLowerCase()));
    // 2. if not, check if it is under 'Configuration'
    if (containingLI == null) {
        containingLI = confULContainer.get(getLIContainerId(getClass().getSimpleName().toLowerCase()));
    }
    // 3. when found, set CSS coordinates for menu
    if (containingLI != null) {
        containingLI.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "active");
            }
        });

        if (confULContainer.getId().equals(containingLI.getParent().getId())) {
            confULContainer.add(new Behavior() {

                private static final long serialVersionUID = 3109256773218160485L;

                @Override
                public void onComponentTag(final Component component, final ComponentTag tag) {
                    tag.put("class", "treeview-menu menu-open");
                    tag.put("style", "display: block;");
                }

            });

            confLIContainer.add(new Behavior() {

                private static final long serialVersionUID = 3109256773218160485L;

                @Override
                public void onComponentTag(final Component component, final ComponentTag tag) {
                    tag.put("class", "treeview active");
                }
            });
        }
    }

    // Extensions
    ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) SyncopeConsoleApplication
            .get().getServletContext().getAttribute(ConsoleInitializer.CLASSPATH_LOOKUP);
    List<Class<? extends BaseExtPage>> extPageClasses = classPathScanImplementationLookup.getExtPageClasses();

    WebMarkupContainer extensionsLI = new WebMarkupContainer(getLIContainerId("extensions"));
    extensionsLI.setOutputMarkupPlaceholderTag(true);
    extensionsLI.setVisible(!extPageClasses.isEmpty());
    body.add(extensionsLI);

    ListView<Class<? extends BaseExtPage>> extPages = new ListView<Class<? extends BaseExtPage>>("extPages",
            extPageClasses) {

        private static final long serialVersionUID = 4949588177564901031L;

        @Override
        protected void populateItem(final ListItem<Class<? extends BaseExtPage>> item) {
            WebMarkupContainer containingLI = new WebMarkupContainer("extPageLI");
            item.add(containingLI);
            if (item.getModelObject().equals(BasePage.this.getClass())) {
                containingLI.add(new Behavior() {

                    private static final long serialVersionUID = 1469628524240283489L;

                    @Override
                    public void onComponentTag(final Component component, final ComponentTag tag) {
                        tag.put("class", "active");
                    }
                });
            }

            ExtPage ann = item.getModelObject().getAnnotation(ExtPage.class);

            BookmarkablePageLink<Page> link = new BookmarkablePageLink<>("extPage", item.getModelObject());
            link.add(new Label("extPageLabel", ann.label()));
            MetaDataRoleAuthorizationStrategy.authorize(link, WebPage.ENABLE, ann.listEntitlement());
            containingLI.add(link);

            Label extPageIcon = new Label("extPageIcon");
            extPageIcon.add(new AttributeModifier("class", "fa " + ann.icon()));
            link.add(extPageIcon);
        }
    };
    extPages.setOutputMarkupId(true);
    extensionsLI.add(extPages);

    if (getPage() instanceof BaseExtPage) {
        extPages.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "treeview-menu menu-open");
                tag.put("style", "display: block;");
            }

        });

        extensionsLI.add(new Behavior() {

            private static final long serialVersionUID = 1469628524240283489L;

            @Override
            public void onComponentTag(final Component component, final ComponentTag tag) {
                tag.put("class", "treeview active");
            }
        });
    }
}

From source file:org.apache.syncope.client.console.pages.Configuration.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setupSyncopeConf() {
    final WebMarkupContainer parameters = new WebMarkupContainer("parameters");
    parameters.setOutputMarkupId(true);//w  w  w  . j a  va2s  .  c  o  m
    add(parameters);

    setWindowClosedCallback(syncopeConfWin, parameters);

    AjaxLink<Void> confLink = new IndicatingAjaxLink<Void>("confLink") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            syncopeConfWin.setPageCreator(new ModalWindow.PageCreator() {

                private static final long serialVersionUID = -7834632442532690940L;

                @Override
                public Page createPage() {
                    return new ConfModalPage(getPageReference(), editNotificationWin, parameters);
                }
            });

            syncopeConfWin.show(target);
        }
    };
    parameters.add(confLink);

    Link<Void> dbExportLink = new Link<Void>("dbExportLink") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick() {
            try {
                HttpResourceStream stream = new HttpResourceStream(confRestClient.dbExport());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(stream.getFilename() == null ? "content.xml" : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
            }
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(dbExportLink, ENABLE,
            xmlRolesReader.getEntitlement("Configuration", "export"));
    add(dbExportLink);
}

From source file:org.apache.syncope.client.console.panels.SAML2SPPanel.java

License:Apache License

public SAML2SPPanel(final String id) {
    super(id);/*  ww w . ja v  a 2  s .c o m*/

    add(new Link<Void>("downloadMetadata") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick() {
            try {
                HttpResourceStream stream = new HttpResourceStream(ClientBuilder.newClient()
                        .target(RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(
                                UrlUtils.rewriteToContextRelative("saml2sp/metadata", RequestCycle.get()))))
                        .request().get());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(stream.getFilename() == null
                        ? SyncopeConsoleSession.get().getDomain() + "-SAML-SP-Metadata.xml"
                        : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                LOG.error("While exporting SAML 2.0 SP metadata", e);
                SyncopeConsoleSession.get().error(getString(Constants.ERROR) + ": " + e.getMessage());
            }
        }
    });
}

From source file:org.apache.syncope.client.console.wicket.markup.html.form.AjaxDownload.java

License:Apache License

@Override
public void onRequest() {
    HttpResourceStream stream = getResourceStream();
    ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(stream);
    String key = StringUtils.isNotBlank(fileKey) ? fileKey + "_" : "";
    String ext = "";
    if (StringUtils.isNotBlank(mimeType)) {
        String extByMimeType = MIME_TYPES_LOADER.getFileExt(mimeType);
        ext = StringUtils.isBlank(extByMimeType) ? ".bin" : ("." + extByMimeType);
    }//w  ww .  j a  v a2s . co  m
    String fileName = key + (stream.getFilename() == null ? name : stream.getFilename()) + ext;

    handler.setFileName(fileName);
    handler.setContentDisposition(ContentDisposition.ATTACHMENT);
    getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}

From source file:org.apache.syncope.client.console.wicket.markup.html.form.BinaryFieldPanel.java

License:Apache License

public BinaryFieldPanel(final String id, final String name, final IModel<String> model, final String mimeType) {
    super(id, name, model);
    this.mimeType = mimeType;

    previewer = previewUtils.getPreviewer(mimeType);

    uploadForm = new StatelessForm<>("uploadForm");
    uploadForm.setMultiPart(true);//w ww.j av  a 2s  .com
    uploadForm.setMaxSize(Bytes.megabytes(4));
    add(uploadForm);

    container = new WebMarkupContainer("previewContainer") {

        private static final long serialVersionUID = 2628490926588791229L;

        @Override
        public void renderHead(final IHeaderResponse response) {
            if (previewer == null) {
                FileinputJsReference.INSTANCE.renderHead(response);
                final JQuery fileinputJS = $(fileUpload).chain(new IFunction() {

                    private static final long serialVersionUID = -2285418135375523652L;

                    @Override
                    public String build() {
                        return "fileinput({" + "'showRemove':false, " + "'showUpload':false, "
                                + "'previewFileType':'any'})";
                    }
                });
                response.render(OnDomReadyHeaderItem.forScript(fileinputJS.get()));
            }
        }
    };
    container.setOutputMarkupId(true);

    emptyFragment = new Fragment("panelPreview", "emptyFragment", container);
    emptyFragment.setOutputMarkupId(true);
    container.add(emptyFragment);
    uploadForm.add(container);

    field = new TextField<>("textField", model);
    add(field.setLabel(new Model<>(name)).setOutputMarkupId(true));

    uploadForm.add(
            new Label("preview", StringUtils.isBlank(mimeType) ? StringUtils.EMPTY : "(" + mimeType + ")"));

    downloadLink = new AjaxLink<Void>("downloadLink") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            try {
                HttpResourceStream stream = new HttpResourceStream(buildResponse());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(stream.getFilename() == null ? name : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                SyncopeConsoleSession.get()
                        .error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage());
            }
        }
    };
    downloadLink.setOutputMarkupId(true);
    uploadForm.add(downloadLink);

    FileInputConfig config = new FileInputConfig();
    config.showUpload(false);
    config.showRemove(false);
    config.showPreview(false);

    fileUpload = new BootstrapFileInputField("fileUpload", new ListModel<>(new ArrayList<FileUpload>()),
            config);
    fileUpload.setOutputMarkupId(true);

    fileUpload.add(new AjaxFormSubmitBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onSubmit(final AjaxRequestTarget target) {
            final FileUpload uploadedFile = fileUpload.getFileUpload();
            if (uploadedFile != null) {
                final byte[] uploadedBytes = uploadedFile.getBytes();
                final String uploaded = new String(Base64.encodeBase64(uploadedBytes),
                        SyncopeConstants.DEFAULT_CHARSET);
                field.setModelObject(uploaded);
                target.add(field);

                if (previewer == null) {
                    container.addOrReplace(emptyFragment);
                } else {
                    final Component panelPreview = previewer.preview(uploadedBytes);
                    changePreviewer(panelPreview);
                    fileUpload.setModelObject(null);
                    uploadForm.addOrReplace(fileUpload);
                }

                downloadLink.setEnabled(StringUtils.isNotBlank(uploaded));

                target.add(container);
            }
        }
    });
    uploadForm.add(fileUpload);

    IndicatingAjaxLink<Void> resetLink = new IndicatingAjaxLink<Void>("resetLink") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            field.setModelObject(null);
            target.add(field);
            downloadLink.setEnabled(false);
            container.addOrReplace(emptyFragment);
            uploadForm.addOrReplace(container);
            target.add(uploadForm);
        }
    };
    uploadForm.add(resetLink);
}

From source file:org.apache.syncope.console.pages.Configuration.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setupSyncopeConf() {
    WebMarkupContainer parameters = new WebMarkupContainer("parameters");
    add(parameters);/*w  ww  . j  av a  2s.  c om*/
    MetaDataRoleAuthorizationStrategy.authorize(parameters, ENABLE,
            xmlRolesReader.getAllAllowedRoles("Configuration", "list"));

    final ConfTO conf = confRestClient.list();

    final Form<?> form = new Form<Void>("confForm");
    form.setModel(new CompoundPropertyModel(conf));
    parameters.add(form);

    form.add(new AttributesPanel("parameters", conf, form, false));

    IndicatingAjaxLink<Void> save = new IndicatingAjaxLink<Void>("saveParameters") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            final ConfTO updatedConf = (ConfTO) form.getModelObject();

            try {
                for (AttributeTO attr : updatedConf.getAttrs()) {
                    if (attr.getValues().isEmpty()
                            || attr.getValues().equals(Collections.singletonList(StringUtils.EMPTY))) {

                        confRestClient.delete(attr.getSchema());
                    } else {
                        confRestClient.set(attr);
                    }
                }

                info(getString(Constants.OPERATION_SUCCEEDED));
                feedbackPanel.refresh(target);
            } catch (Exception e) {
                LOG.error("While updating configuration parameters", e);
                error(getString(Constants.ERROR) + ": " + e.getMessage());
                feedbackPanel.refresh(target);
            }
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(save, ENABLE,
            xmlRolesReader.getAllAllowedRoles("Configuration", "set"));
    form.add(save);

    Link<Void> dbExportLink = new Link<Void>("dbExportLink") {

        private static final long serialVersionUID = -4331619903296515985L;

        @Override
        public void onClick() {
            try {
                HttpResourceStream stream = new HttpResourceStream(confRestClient.dbExport());

                ResourceStreamRequestHandler rsrh = new ResourceStreamRequestHandler(stream);
                rsrh.setFileName(stream.getFilename() == null ? "content.xml" : stream.getFilename());
                rsrh.setContentDisposition(ContentDisposition.ATTACHMENT);

                getRequestCycle().scheduleRequestHandlerAfterCurrent(rsrh);
            } catch (Exception e) {
                error(getString(Constants.ERROR) + ": " + e.getMessage());
            }
        }
    };
    MetaDataRoleAuthorizationStrategy.authorize(dbExportLink, ENABLE,
            xmlRolesReader.getAllAllowedRoles("Configuration", "export"));
    add(dbExportLink);
}