Example usage for org.apache.wicket.ajax.markup.html AjaxLink setEnabled

List of usage examples for org.apache.wicket.ajax.markup.html AjaxLink setEnabled

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.markup.html AjaxLink setEnabled.

Prototype

public final Component setEnabled(final boolean enabled) 

Source Link

Document

Sets whether this component is enabled.

Usage

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

License:Apache License

private ResultStatusModalPage(final Builder builder) {
    super();/*from  www .ja  v  a 2s  . c  o m*/
    this.subject = builder.subject;
    statusUtils = new StatusUtils(this.userRestClient);
    if (builder.mode == null) {
        this.mode = UserModalPage.Mode.ADMIN;
    } else {
        this.mode = builder.mode;
    }

    final BaseModalPage page = this;

    final WebMarkupContainer container = new WebMarkupContainer("container");
    container.setOutputMarkupId(true);
    add(container);

    final Fragment fragment = new Fragment("resultFrag",
            mode == UserModalPage.Mode.SELF ? "userSelfResultFrag" : "propagationResultFrag", this);
    fragment.setOutputMarkupId(true);
    container.add(fragment);

    if (mode == UserModalPage.Mode.ADMIN) {
        // add Syncope propagation status
        PropagationStatus syncope = new PropagationStatus();
        syncope.setResource("Syncope");
        syncope.setStatus(PropagationTaskExecStatus.SUCCESS);

        List<PropagationStatus> propagations = new ArrayList<PropagationStatus>();
        propagations.add(syncope);
        propagations.addAll(subject.getPropagationStatusTOs());

        fragment.add(new Label("info",
                ((subject instanceof UserTO) && ((UserTO) subject).getUsername() != null)
                        ? ((UserTO) subject).getUsername()
                        : ((subject instanceof RoleTO) && ((RoleTO) subject).getName() != null)
                                ? ((RoleTO) subject).getName()
                                : String.valueOf(subject.getId())));

        final ListView<PropagationStatus> propRes = new ListView<PropagationStatus>("resources", propagations) {

            private static final long serialVersionUID = -1020475259727720708L;

            @Override
            protected void populateItem(final ListItem<PropagationStatus> item) {
                final PropagationStatus propTO = (PropagationStatus) item.getDefaultModelObject();

                final ListView attributes = getConnObjectView(propTO);

                final Fragment attrhead;
                if (attributes.getModelObject() == null || attributes.getModelObject().isEmpty()) {
                    attrhead = new Fragment("attrhead", "emptyAttrHeadFrag", page);
                } else {
                    attrhead = new Fragment("attrhead", "attrHeadFrag", page);
                }

                item.add(attrhead);
                item.add(attributes);

                attrhead.add(new Label("resource", propTO.getResource()));

                attrhead.add(new Label("propagation",
                        propTO.getStatus() == null ? "UNDEFINED" : propTO.getStatus().toString()));

                final Image image;
                final String alt, title;
                final ModalWindow failureWindow = new ModalWindow("failureWindow");
                final AjaxLink<?> failureWindowLink = new AjaxLink<Void>("showFailureWindow") {

                    private static final long serialVersionUID = -7978723352517770644L;

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

                switch (propTO.getStatus()) {

                case SUCCESS:
                case SUBMITTED:
                case CREATED:
                    image = new Image("icon", IMG_STATUSES + Status.ACTIVE.toString() + Constants.PNG_EXT);
                    alt = "success icon";
                    title = "success";
                    failureWindow.setVisible(false);
                    failureWindowLink.setEnabled(false);
                    break;

                default:
                    image = new Image("icon", IMG_STATUSES + Status.SUSPENDED.toString() + Constants.PNG_EXT);
                    alt = "failure icon";
                    title = "failure";
                }

                image.add(new Behavior() {

                    private static final long serialVersionUID = 1469628524240283489L;

                    @Override
                    public void onComponentTag(final Component component, final ComponentTag tag) {
                        tag.put("alt", alt);
                        tag.put("title", title);
                    }
                });
                final FailureMessageModalPage executionFailureMessagePage;
                if (propTO.getFailureReason() == null) {
                    executionFailureMessagePage = new FailureMessageModalPage(failureWindow.getContentId(),
                            StringUtils.EMPTY);
                } else {
                    executionFailureMessagePage = new FailureMessageModalPage(failureWindow.getContentId(),
                            propTO.getFailureReason());
                }

                failureWindow.setPageCreator(new ModalWindow.PageCreator() {

                    private static final long serialVersionUID = -7834632442532690940L;

                    @Override
                    public Page createPage() {
                        return executionFailureMessagePage;
                    }
                });
                failureWindow.setCookieName("failureWindow");
                failureWindow.setCssClassName(ModalWindow.CSS_CLASS_GRAY);
                failureWindowLink.add(image);
                attrhead.add(failureWindowLink);
                attrhead.add(failureWindow);
            }
        };
        fragment.add(propRes);
    }

    final AjaxLink<Void> close = new IndicatingAjaxLink<Void>("close") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            if (mode == UserModalPage.Mode.SELF && anonymousUser.equals(SyncopeSession.get().getUsername())) {
                SyncopeSession.get().invalidate();
            }
            builder.window.close(target);
        }
    };
    container.add(close);

    setOutputMarkupId(true);
}

From source file:org.apache.syncope.console.SyncopeApplication.java

License:Apache License

public void setupEditProfileModal(final WebPage page, final UserSelfRestClient userSelfRestClient) {
    // Modal window for editing user profile
    final ModalWindow editProfileModalWin = new ModalWindow("editProfileModal");
    editProfileModalWin.setCssClassName(ModalWindow.CSS_CLASS_GRAY);
    editProfileModalWin.setInitialHeight(EDIT_PROFILE_WIN_HEIGHT);
    editProfileModalWin.setInitialWidth(EDIT_PROFILE_WIN_WIDTH);
    editProfileModalWin.setCookieName("edit-profile-modal");
    page.add(editProfileModalWin);/*  w w  w  .  j  av a 2  s  .  co  m*/

    final AjaxLink<Page> editProfileLink = new AjaxLink<Page>("editProfileLink") {

        private static final long serialVersionUID = -7978723352517770644L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            final UserTO userTO = SyncopeSession.get().isAuthenticated() ? userSelfRestClient.read()
                    : new UserTO();

            editProfileModalWin.setPageCreator(new ModalWindow.PageCreator() {

                private static final long serialVersionUID = -7834632442532690940L;

                @Override
                public Page createPage() {
                    return new UserSelfModalPage(page.getPageReference(), editProfileModalWin, userTO);
                }
            });

            editProfileModalWin.show(target);
        }
    };

    editProfileLink.add(new Label("username", SyncopeSession.get().getUsername()));

    if ("admin".equals(SyncopeSession.get().getUsername())) {
        editProfileLink.setEnabled(false);
    }

    page.add(editProfileLink);
}

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

License:Apache License

public MultiFieldPanel(final String id, final IModel<List<E>> model, final FieldPanel<E> panelTemplate,
        final boolean eventTemplate) {

    super(id, model);

    // -----------------------
    // Object container definition
    // -----------------------
    container = new WebMarkupContainer("multiValueContainer");
    container.setOutputMarkupId(true);/*from   w  w w .j  ava2s. c o  m*/
    add(container);
    // -----------------------

    view = new ListView<E>("view", model) {

        private static final long serialVersionUID = -9180479401817023838L;

        @Override
        protected void populateItem(final ListItem<E> item) {
            final FieldPanel<E> fieldPanel = panelTemplate.clone();

            if (eventTemplate) {
                fieldPanel.getField().add(new AjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

                    private static final long serialVersionUID = -1107858522700306810L;

                    @Override
                    protected void onUpdate(final AjaxRequestTarget target) {
                        send(getPage(), Broadcast.BREADTH, new MultiValueSelectorEvent(target));
                    }
                });
            }

            fieldPanel.setNewModel(item);
            item.add(fieldPanel);

            AjaxLink<Void> minus = new IndicatingAjaxLink<Void>("drop") {

                private static final long serialVersionUID = -7978723352517770644L;

                @Override
                public void onClick(final AjaxRequestTarget target) {
                    //Drop current component
                    model.getObject().remove(item.getModelObject());
                    fieldPanel.getField().clearInput();
                    target.add(container);

                    if (eventTemplate) {
                        send(getPage(), Broadcast.BREADTH, new MultiValueSelectorEvent(target));
                    }
                }
            };

            item.add(minus);

            if (model.getObject().size() <= 1) {
                minus.setVisible(false);
                minus.setEnabled(false);
            } else {
                minus.setVisible(true);
                minus.setEnabled(true);
            }

            final Fragment fragment;
            if (item.getIndex() == model.getObject().size() - 1) {
                final AjaxLink<Void> plus = new IndicatingAjaxLink<Void>("add") {

                    private static final long serialVersionUID = -7978723352517770644L;

                    @Override
                    public void onClick(final AjaxRequestTarget target) {
                        //Add current component
                        model.getObject().add(null);
                        target.add(container);
                    }
                };

                fragment = new Fragment("panelPlus", "fragmentPlus", container);

                fragment.add(plus);
            } else {
                fragment = new Fragment("panelPlus", "emptyFragment", container);
            }
            item.add(fragment);
        }
    };

    container.add(view.setOutputMarkupId(true));
    setOutputMarkupId(true);
}

From source file:org.cast.cwm.tag.component.TagList.java

License:Open Source License

public TagList(String id, final PersistedObject target, final User student) {
    super(id);/*from   w ww.ja  v a2 s  .c o m*/
    this.setOutputMarkupId(true);
    this.target = target;
    this.user = student == null ? CwmSession.get().getUser() : student;

    RefreshingView<Tag> list = new RefreshingView<Tag>("tag") {
        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        @Override
        protected Iterator getItemModels() {
            allUserTags = TagService.get().tagsForUser(user);

            List<Tag> tags = new ArrayList<Tag>(allUserTags);
            for (Tagging ting : TagService.get().taggingsForTarget(user, target)) {
                tags.remove(ting.getTag());
            }

            return new ModelIteratorAdapter<Tag>(tags.iterator()) {

                @Override
                protected IModel<Tag> model(Tag object) {
                    return new CompoundPropertyModel(object);
                }
            };
        }

        @Override
        protected void populateItem(Item<Tag> item) {
            final Tag t = item.getModelObject();
            AjaxLink<Void> link = new AjaxLink<Void>("link") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget ajaxtarget) {
                    TagService.get().findTaggingCreate(user, target, t.getName());
                    ajaxtarget.add(TagList.this);
                    ajaxtarget.addChildren(findParent(TagPanel.class), TaggingsListPanel.class);
                }
            };
            link.setEnabled(student == null);
            item.add(link);
            link.add(new TagLabel("name", t));
        }
    };
    add(list);
}

From source file:org.dcm4chee.wizard.panel.BasicConfigurationPanel.java

License:LGPL

private AbstractColumn<ConfigTreeNode, String> getDeleteColumn() {
    return new AbstractColumn<ConfigTreeNode, String>(Model.of("Delete")) {

        private static final long serialVersionUID = 1L;

        public void populateItem(Item<ICellPopulator<ConfigTreeNode>> cellItem, String componentId,
                final IModel<ConfigTreeNode> rowModel) {

            final TreeNodeType type = rowModel.getObject().getNodeType();
            if (type == null)
                throw new RuntimeException("Error: Unknown node type, cannot create delete modal window");

            else if (type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_CONNECTIONS)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_APPLICATION_ENTITIES)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_HL7_APPLICATIONS)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_AUDIT_LOGGERS)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_TRANSFER_CAPABILITIES)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_TRANSFER_CAPABILITY_TYPE)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_FORWARD_RULES)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_FORWARD_OPTIONS)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_RETRIES)
                    || type.equals(ConfigTreeNode.TreeNodeType.CONTAINER_COERCIONS)
                    || type.equals(ConfigTreeNode.TreeNodeType.XCAiInitiatingGateway)
                    || type.equals(ConfigTreeNode.TreeNodeType.XCAInitiatingGateway)
                    || type.equals(ConfigTreeNode.TreeNodeType.XCAiRespondingGateway)
                    || type.equals(ConfigTreeNode.TreeNodeType.XCARespondingGateway)
                    || type.equals(ConfigTreeNode.TreeNodeType.XDSRegistry)
                    || type.equals(ConfigTreeNode.TreeNodeType.XDSSource)
                    || type.equals(ConfigTreeNode.TreeNodeType.XDSiSource)
                    || type.equals(TreeNodeType.XDSStorage)
                    || type.equals(ConfigTreeNode.TreeNodeType.XDSRepository)) {
                cellItem.add(new Label(componentId));
                return;
            }/*from w  w w.  jav a 2s . c o m*/

            AjaxLink<Object> ajaxLink = getConfirmDeleteLink(rowModel);
            cellItem.add(new LinkPanel(componentId, ajaxLink, ImageManager.IMAGE_WIZARD_COMMON_REMOVE,
                    removeConfirmation))
                    .add(new AttributeAppender("style", Model.of("width: 50px; text-align: center;")));
            if (type.equals(ConfigTreeNode.TreeNodeType.CONNECTION)) {
                Connection connection = null;
                try {
                    connection = ((ConnectionModel) rowModel.getObject().getModel()).getConnection();
                    for (ApplicationEntity ae : connection.getDevice().getApplicationEntities())
                        if (ae.getConnections().contains(connection))
                            ajaxLink.setEnabled(false).add(new AttributeModifier("title",
                                    new ResourceModel("dicom.delete.connection.notAllowed")));

                    HL7DeviceExtension hl7DeviceExtension = connection.getDevice()
                            .getDeviceExtension(HL7DeviceExtension.class);
                    if (hl7DeviceExtension != null) {
                        for (HL7Application hl7Application : hl7DeviceExtension.getHL7Applications())
                            if (hl7Application.getConnections().contains(connection))
                                ajaxLink.setEnabled(false).add(new AttributeModifier("title",
                                        new ResourceModel("dicom.delete.connection.notAllowed")));
                    }

                    AuditLogger auditLogger = connection.getDevice().getDeviceExtension(AuditLogger.class);
                    if (auditLogger != null && auditLogger.getConnections().contains(connection))
                        ajaxLink.setEnabled(false).add(new AttributeModifier("title",
                                new ResourceModel("dicom.delete.connection.notAllowed")));

                } catch (ConfigurationException ce) {
                    log.error(this.getClass().toString() + ": "
                            + "Error checking used connections of application entities: " + ce.getMessage());
                    log.debug("Exception", ce);
                    throw new RuntimeException(ce);
                }
            }
        }
    };
}

From source file:org.geoserver.backuprestore.web.BackupRestorePage.java

License:Open Source License

void initComponents(final IModel<T> model) {
    add(new Label("id", new PropertyModel(model, "id")));
    add(new Label("clazz", new Model(
            this.clazz.getSimpleName().substring(0, this.clazz.getSimpleName().indexOf("Execution")))));

    BackupRestoreExecutionsProvider provider = new BackupRestoreExecutionsProvider(getType()) {
        @Override/*from  w  w w . ja  v  a2  s .  co m*/
        protected List<Property<AbstractExecutionAdapter>> getProperties() {
            return Arrays.asList(ID, STATE, STARTED, PROGRESS, ARCHIVEFILE, OPTIONS);
        }

        @Override
        protected List<T> getItems() {
            return Collections.singletonList(model.getObject());
        }
    };

    final BackupRestoreExecutionsTable headerTable = new BackupRestoreExecutionsTable("header", provider,
            getType());

    headerTable.setOutputMarkupId(true);
    headerTable.setFilterable(false);
    headerTable.setPageable(false);
    add(headerTable);

    final T bkp = model.getObject();
    boolean selectable = bkp.getStatus() != BatchStatus.COMPLETED;

    add(new Icon("icon", COMPRESS_ICON));
    add(new Label("title", new DataTitleModel(bkp))
            .add(new AttributeModifier("title", new DataTitleModel(bkp, false))));

    @SuppressWarnings("rawtypes")
    Form<?> form = new Form("form");
    add(form);

    try {
        if (params != null && params.getNamedKeys().contains(DETAILS_LEVEL)) {
            if (params.get(DETAILS_LEVEL).toInt() > 0) {
                expand = params.get(DETAILS_LEVEL).toInt();
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error parsing the 'details level' parameter: ",
                params.get(DETAILS_LEVEL).toString());
    }

    form.add(new SubmitLink("refresh") {
        @Override
        public void onSubmit() {
            setResponsePage(BackupRestorePage.class, new PageParameters().add("id", params.get("id").toLong())
                    .add("clazz", getType().getSimpleName()).add(DETAILS_LEVEL, expand));
        }
    });

    NumberTextField<Integer> expand = new NumberTextField<Integer>("expand",
            new PropertyModel<Integer>(this, "expand"));
    expand.add(RangeValidator.minimum(0));
    form.add(expand);

    TextArea<String> details = new TextArea<String>("details", new BKErrorDetailsModel(bkp));
    details.setOutputMarkupId(true);
    details.setMarkupId("details");
    add(details);

    String location = bkp.getArchiveFile().path();
    if (location == null) {
        location = getGeoServerApplication().getGeoServer().getLogging().getLocation();
    }
    backupFile = new File(location);
    if (!backupFile.isAbsolute()) {
        // locate the geoserver.log file
        GeoServerDataDirectory dd = getGeoServerApplication().getBeanOfType(GeoServerDataDirectory.class);
        backupFile = dd.get(Paths.convert(backupFile.getPath())).file();
    }

    if (!backupFile.exists()) {
        error("Could not find the Backup Archive file: " + backupFile.getAbsolutePath());
    }

    /***
     * DOWNLOAD LINK
     */
    final Link<Object> downLoadLink = new Link<Object>("download") {

        @Override
        public void onClick() {
            IResourceStream stream = new FileResourceStream(backupFile) {
                public String getContentType() {
                    return "application/zip";
                }
            };
            ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(stream,
                    backupFile.getName());
            handler.setContentDisposition(ContentDisposition.ATTACHMENT);

            RequestCycle.get().scheduleRequestHandlerAfterCurrent(handler);
        }
    };
    add(downLoadLink);

    /***
     * PAUSE LINK
     */
    final AjaxLink pauseLink = new AjaxLink("pause") {

        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            tag.setName("a");
            tag.addBehavior(AttributeModifier.replace("class", "disabled"));
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            AbstractExecutionAdapter bkp = model.getObject();
            if (bkp.getStatus() == BatchStatus.STOPPED) {
                setLinkEnabled((AjaxLink) downLoadLink.getParent().get("pause"), false, target);
            } else {
                try {
                    backupFacade().stopExecution(bkp.getId());

                    setResponsePage(BackupRestoreDataPage.class);
                } catch (NoSuchJobExecutionException | JobExecutionNotRunningException e) {
                    LOGGER.log(Level.WARNING, "", e);
                    getSession().error(e);
                    setResponsePage(BackupRestoreDataPage.class);
                }
            }
        }

    };
    pauseLink.setEnabled(doSelectReady(bkp) && bkp.getStatus() != BatchStatus.STOPPED);
    add(pauseLink);

    /***
     * RESUME LINK
     */
    final AjaxLink resumeLink = new AjaxLink("resume") {

        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            tag.setName("a");
            tag.addBehavior(AttributeModifier.replace("class", "disabled"));
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            AbstractExecutionAdapter bkp = model.getObject();
            if (bkp.getStatus() != BatchStatus.STOPPED) {
                setLinkEnabled((AjaxLink) downLoadLink.getParent().get("pause"), false, target);
            } else {
                try {
                    Long id = backupFacade().restartExecution(bkp.getId());

                    PageParameters pp = new PageParameters();
                    pp.add("id", id);
                    if (bkp instanceof BackupExecutionAdapter) {
                        pp.add("clazz", BackupExecutionAdapter.class.getSimpleName());
                    } else if (bkp instanceof RestoreExecutionAdapter) {
                        pp.add("clazz", RestoreExecutionAdapter.class.getSimpleName());
                    }

                    setResponsePage(BackupRestorePage.class, pp);
                } catch (NoSuchJobExecutionException | JobInstanceAlreadyCompleteException | NoSuchJobException
                        | JobRestartException | JobParametersInvalidException e) {
                    LOGGER.log(Level.WARNING, "", e);
                    getSession().error(e);
                    setResponsePage(BackupRestoreDataPage.class);
                }
            }
        }

    };
    resumeLink.setEnabled(bkp.getStatus() == BatchStatus.STOPPED);
    add(resumeLink);

    /***
     * ABANDON LINK
     */
    final AjaxLink cancelLink = new AjaxLink("cancel") {

        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            tag.setName("a");
            tag.addBehavior(AttributeModifier.replace("class", "disabled"));
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            AbstractExecutionAdapter bkp = model.getObject();
            if (!doSelectReady(bkp)) {
                setLinkEnabled((AjaxLink) downLoadLink.getParent().get("cancel"), false, target);
            } else {
                try {
                    backupFacade().abandonExecution(bkp.getId());

                    PageParameters pp = new PageParameters();
                    pp.add("id", bkp.getId());
                    if (bkp instanceof BackupExecutionAdapter) {
                        pp.add("clazz", BackupExecutionAdapter.class.getSimpleName());
                    } else if (bkp instanceof RestoreExecutionAdapter) {
                        pp.add("clazz", RestoreExecutionAdapter.class.getSimpleName());
                    }

                    setResponsePage(BackupRestorePage.class, pp);
                } catch (NoSuchJobExecutionException | JobExecutionAlreadyRunningException e) {
                    error(e);
                    LOGGER.log(Level.WARNING, "", e);
                }
            }
        }

    };
    cancelLink.setEnabled(doSelectReady(bkp));
    add(cancelLink);

    /***
     * DONE LINK
     */
    final AjaxLink doneLink = new AjaxLink("done") {

        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            tag.setName("a");
            tag.addBehavior(AttributeModifier.replace("class", "disabled"));
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            setResponsePage(BackupRestoreDataPage.class);
            return;
        }

    };
    add(doneLink);

    /**
     * FINALIZE
     */
    add(dialog = new GeoServerDialog("dialog"));
}

From source file:org.geoserver.backuprestore.web.BackupRestorePage.java

License:Open Source License

void setLinkEnabled(AjaxLink link, boolean enabled, AjaxRequestTarget target) {
    link.setEnabled(enabled);
    target.add(link);
}

From source file:org.geoserver.importer.web.ImportPage.java

License:Open Source License

void initComponents(final IModel<ImportContext> model) {
    add(new Label("id", new PropertyModel(model, "id")));

    ImportContextProvider provider = new ImportContextProvider() {
        @Override/* w  ww.  java2 s  . c  om*/
        protected List<Property<ImportContext>> getProperties() {
            return Arrays.asList(STATE, CREATED, UPDATED);
        }

        @Override
        protected List<ImportContext> getItems() {
            return Collections.singletonList(model.getObject());
        }
    };

    add(new AjaxLink("raw") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            dialog.setInitialHeight(500);
            dialog.setInitialWidth(700);
            dialog.showOkCancel(target, new DialogDelegate() {
                @Override
                protected Component getContents(String id) {
                    XStreamPersister xp = importer().createXStreamPersisterXML();
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    try {
                        xp.save(model.getObject(), bout);
                    } catch (IOException e) {
                        bout = new ByteArrayOutputStream();
                        LOGGER.log(Level.FINER, e.getMessage(), e);
                        e.printStackTrace(new PrintWriter(bout));
                    }

                    return new TextAreaPanel(id, new Model(new String(bout.toByteArray())));
                }

                @Override
                protected boolean onSubmit(AjaxRequestTarget target, Component contents) {
                    return true;
                }
            });
        }
    }.setVisible(ImporterWebUtils.isDevMode()));

    final ImportContextTable headerTable = new ImportContextTable("header", provider);

    headerTable.setOutputMarkupId(true);
    headerTable.setFilterable(false);
    headerTable.setPageable(false);
    add(headerTable);

    final ImportContext imp = model.getObject();
    boolean selectable = imp.getState() != ImportContext.State.COMPLETE;
    final ImportTaskTable taskTable = new ImportTaskTable("tasks", new ImportTaskProvider(model), selectable) {
        @Override
        protected void onSelectionUpdate(AjaxRequestTarget target) {
            updateImportLink((AjaxLink) ImportPage.this.get("import"), this, target);
        }
    }.setFeedbackPanel(feedbackPanel);
    taskTable.setOutputMarkupId(true);
    taskTable.setFilterable(false);
    add(taskTable);

    final AjaxLink<Long> importLink = new AjaxLink<Long>("import", new Model<Long>()) {
        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            ImporterWebUtils.disableLink(tag);
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            ImportContext imp = model.getObject();

            BasicImportFilter filter = new BasicImportFilter();
            for (ImportTask t : taskTable.getSelection()) {
                filter.add(t);
            }

            //set running flag and update cancel link
            running.set(true);
            target.addComponent(cancelLink(this));

            final Long jobid = importer().runAsync(imp, filter, false);
            setDefaultModelObject(jobid);

            final AjaxLink self = this;

            // create a timer to update the table and reload the page when
            // necessary
            taskTable.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(500)) {
                @Override
                protected void onTimer(AjaxRequestTarget target) {
                    Task<ImportContext> job = importer().getTask(jobid);
                    if (job == null || job.isDone()) {
                        // remove the timer
                        stop();

                        self.setEnabled(true);
                        target.addComponent(self);

                        running.set(false);
                        target.addComponent(cancelLink(self));

                        /*ImportContext imp = model.getObject();
                        if (imp.getState() == ImportContext.State.COMPLETE) {
                        // enable cancel, which will not be "done"
                        setLinkEnabled(cancelLink(self), true, target);
                        } else {
                        // disable cancel, import is not longer running, but
                        // also
                        // not complete
                        setLinkEnabled(cancelLink(self), false, target);
                        }*/
                    }

                    // update the table
                    target.addComponent(taskTable);
                    target.addComponent(headerTable);
                }
            });
            target.addComponent(taskTable);

            // disable import button
            setLinkEnabled(this, false, target);
            // enable cancel button
            //setLinkEnabled(cancelLink(this), true, target);
        }
    };
    importLink.setOutputMarkupId(true);
    importLink.setEnabled(doSelectReady(imp, taskTable, null));
    add(importLink);

    final AjaxLink cancelLink = new AjaxLink("cancel") {
        @Override
        protected void disableLink(ComponentTag tag) {
            super.disableLink(tag);
            ImporterWebUtils.disableLink(tag);
        }

        @Override
        public void onClick(AjaxRequestTarget target) {
            ImportContext imp = model.getObject();
            if (!running.get()) {
                //if (imp.getState() == ImportContext.State.COMPLETE) {
                setResponsePage(ImportDataPage.class);
                return;
            }

            Long jobid = importLink.getModelObject();
            if (jobid == null) {
                return;
            }

            Task<ImportContext> task = importer().getTask(jobid);
            if (task == null || task.isDone()) {
                return;
            }

            task.getMonitor().setCanceled(true);
            task.cancel(false);
            try {
                task.get();
            } catch (Exception e) {
            }

            // enable import button
            setLinkEnabled(importLink, true, target);
            // disable cancel button
            //setLinkEnabled(cancelLink(importLink), false, target);
        }

    };
    //cancelLink.setEnabled(imp.getState() == ImportContext.State.COMPLETE);
    cancelLink.add(new Label("text", new CancelTitleModel()));
    add(cancelLink);

    WebMarkupContainer selectPanel = new WebMarkupContainer("select");
    selectPanel.add(new AjaxLink<ImportContext>("select-all", model) {
        @Override
        public void onClick(AjaxRequestTarget target) {
            taskTable.selectAll();
            target.addComponent(taskTable);
            updateImportLink(importLink, taskTable, target);
        }
    });
    selectPanel.add(new AjaxLink<ImportContext>("select-none", model) {
        @Override
        public void onClick(AjaxRequestTarget target) {
            taskTable.clearSelection();
            target.addComponent(taskTable);
            updateImportLink(importLink, taskTable, target);
        }
    });
    selectPanel.add(new AjaxLink<ImportContext>("select-ready", model) {
        @Override
        public void onClick(AjaxRequestTarget target) {
            doSelectReady(getModelObject(), taskTable, target);
            target.addComponent(taskTable);
            updateImportLink(importLink, taskTable, target);
        }
    });
    add(selectPanel);

    add(new Icon("icon", new DataIconModel(imp.getData())));
    add(new Label("title", new DataTitleModel(imp))
            .add(new AttributeModifier("title", new DataTitleModel(imp, false))));

    add(dialog = new GeoServerDialog("dialog"));
}

From source file:org.geoserver.importer.web.ImportPage.java

License:Open Source License

void setLinkEnabled(AjaxLink link, boolean enabled, AjaxRequestTarget target) {
    link.setEnabled(enabled);
    target.addComponent(link);
}

From source file:org.hippoecm.frontend.plugins.standards.browse.BreadcrumbPlugin.java

License:Apache License

private ListView<NodeItem> getListView(JcrNodeModel model) {
    nodeitems = new LinkedList<NodeItem>();
    if (model != null) {
        //add current folder as disabled
        nodeitems.add(new NodeItem(model, false));
        if (!roots.contains(model.getItemModel().getPath())) {
            model = model.getParentModel();
            while (model != null) {
                nodeitems.add(new NodeItem(model, true));
                if (roots.contains(model.getItemModel().getPath())) {
                    model = null;//from  w w  w.  j  av a2s. c  om
                } else {
                    model = model.getParentModel();
                }
            }
        }
    }
    Collections.reverse(nodeitems);
    ListView<NodeItem> listview = new ListView<NodeItem>("crumbs", nodeitems) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<NodeItem> item) {
            AjaxLink<NodeItem> link = new AjaxLink<NodeItem>("link", item.getModel()) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    folderReference.setModel(getModelObject().model);
                }

            };

            link.add(new Label("name", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    NodeItem nodeItem = item.getModelObject();
                    return (nodeItem.name != null ? format.parse(nodeItem.name) : null);
                }

            }));
            link.add(new AttributeAppender("title", true, new LoadableDetachableModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                protected String load() {
                    return item.getModelObject().getName();
                }
            }, " "));

            link.setEnabled(item.getModelObject().enabled);
            item.add(link);

            IModel<String> css = new LoadableDetachableModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                protected String load() {
                    String css = item.getModelObject().enabled ? "enabled" : "disabled";

                    if (nodeitems.size() == 1) {
                        css += " firstlast";
                    } else if (item.getIndex() == 0) {
                        css += " first";
                    } else if (item.getIndex() == (nodeitems.size() - 1)) {
                        css += " last";
                    }
                    return css;
                }
            };
            item.add(new AttributeAppender("class", css, " "));

            //CMS7-8008: Just show the last part of the breadcrumb
            item.setVisible(item.getIndex() >= (nodeitems.size() - maxNumberOfCrumbs));
        }
    };
    return listview;
}