Example usage for org.apache.wicket.markup.repeater.data DataView DataView

List of usage examples for org.apache.wicket.markup.repeater.data DataView DataView

Introduction

In this page you can find the example usage for org.apache.wicket.markup.repeater.data DataView DataView.

Prototype

protected DataView(String id, IDataProvider<T> dataProvider) 

Source Link

Usage

From source file:org.dcm4chee.web.war.tc.TCResultPanel.java

License:LGPL

@SuppressWarnings("serial")
public TCResultPanel(final String id, final TCListModel model, final IModel<Boolean> trainingModeModel) {
    super(id, model != null ? model : new TCListModel());

    setOutputMarkupId(true);//  w  w  w. jav a2  s .c  om

    stPermHelper = StudyPermissionHelper.get();

    initWebviewerLinkProvider();

    add(msgWin);
    final ModalWindow modalWindow = new ModalWindow("modal-window");
    add(modalWindow);

    final ModalWindow forumWindow = new ModalWindow("forum-window");
    add(forumWindow);

    final TCStudyListPage studyPage = new TCStudyListPage();
    final ModalWindow studyWindow = new ModalWindow("study-window");
    studyWindow.setPageCreator(new ModalWindow.PageCreator() {
        private static final long serialVersionUID = 1L;

        public Page createPage() {
            return studyPage;
        }
    });

    add(studyWindow);

    tclistProvider = new SortableTCListProvider((TCListModel) getDefaultModel());

    final TCAttributeVisibilityStrategy attrVisibilityStrategy = new TCAttributeVisibilityStrategy(
            trainingModeModel);

    final DataView<TCModel> dataView = new DataView<TCModel>("row", tclistProvider) {

        private final StudyListLocal dao = (StudyListLocal) JNDIUtils.lookup(StudyListLocal.JNDI_NAME);

        private final Map<String, List<String>> studyActions = new HashMap<String, List<String>>();

        @Override
        protected void populateItem(final Item<TCModel> item) {
            final TCModel tc = item.getModelObject();

            final StringBuilder jsStopEventPropagationInline = new StringBuilder(
                    "var event=arguments[0] || window.event; if (event.stopPropagation) {event.stopPropagation();} else {event.cancelBubble=True;};");

            item.setOutputMarkupId(true);
            item.add(new TCMultiLineLabel("title", new AbstractReadOnlyModel<String>() {
                public String getObject() {
                    if (!attrVisibilityStrategy.isAttributeVisible(TCAttribute.Title)) {
                        return TCUtilities.getLocalizedString("tc.case.text") + " " + tc.getId();
                    }
                    return tc.getTitle();
                }
            }, new AutoClampSettings(40)));
            item.add(new TCMultiLineLabel("abstract", new AbstractReadOnlyModel<String>() {
                public String getObject() {
                    if (!attrVisibilityStrategy.isAttributeVisible(TCAttribute.Abstract)) {
                        return TCUtilities.getLocalizedString("tc.obfuscation.text");
                    }
                    return tc.getAbstract();
                }
            }, new AutoClampSettings(40)));
            item.add(new TCMultiLineLabel("author", new AbstractReadOnlyModel<String>() {
                public String getObject() {
                    if (!attrVisibilityStrategy.isAttributeVisible(TCAttribute.AuthorName)) {
                        return TCUtilities.getLocalizedString("tc.obfuscation.text");
                    }
                    return tc.getAuthor();
                }
            }, new AutoClampSettings(40)));
            item.add(new Label("date", new Model<Date>(tc.getCreationDate())) {

                private static final long serialVersionUID = 1L;

                @Override
                public IConverter getConverter(Class<?> type) {
                    return new DateConverter() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public DateFormat getDateFormat(Locale locale) {
                            if (locale == null) {
                                locale = Locale.getDefault();
                            }

                            return DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
                        }
                    };
                }
            });

            final String stuid = tc.getStudyInstanceUID();
            if (dao != null && !studyActions.containsKey(stuid)) {
                studyActions.put(stuid, dao.findStudyPermissionActions(stuid, stPermHelper.getDicomRoles()));
            }

            item.add(Webviewer.getLink(tc, webviewerLinkProviders, stPermHelper,
                    new TooltipBehaviour("tc.result.table.", "webviewer"), modalWindow,
                    new WebviewerLinkClickedCallback() {
                        public void linkClicked(AjaxRequestTarget target) {
                            TCAuditLog.logTFImagesViewed(tc);
                        }
                    }).add(new SecurityBehavior(TCPanel.getModuleName() + ":webviewerInstanceLink")));

            final Component viewLink = new IndicatingAjaxLink<String>("tc-view") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    selectTC(item, tc, target);
                    openTC(tc, false, target);
                }

                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    tag.put("ondblclick", jsStopEventPropagationInline);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    try {
                        return TCPanel.getMaskingBehaviour().getAjaxCallDecorator();
                    } catch (Exception e) {
                        log.error("Failed to get IAjaxCallDecorator: ", e);
                    }
                    return null;
                }
            }.add(new Image("tcViewImg", ImageManager.IMAGE_COMMON_DICOM_DETAILS)
                    .add(new ImageSizeBehaviour("vertical-align: middle;")))
                    .add(new TooltipBehaviour("tc.result.table.", "view")).setOutputMarkupId(true);

            final Component editLink = new IndicatingAjaxLink<String>("tc-edit") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    selectTC(item, tc, target);
                    openTC(tc, true, target);
                }

                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    tag.put("ondblclick", jsStopEventPropagationInline);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    try {
                        return TCPanel.getMaskingBehaviour().getAjaxCallDecorator();
                    } catch (Exception e) {
                        log.error("Failed to get IAjaxCallDecorator: ", e);
                    }
                    return null;
                }
            }.add(new Image("tcEditImg", ImageManager.IMAGE_COMMON_DICOM_EDIT)
                    .add(new ImageSizeBehaviour("vertical-align: middle;")))
                    .add(new TooltipBehaviour("tc.result.table.", "edit"))
                    .add(new SecurityBehavior(TCPanel.getModuleName() + ":editTC")).setOutputMarkupId(true);

            final Component studyLink = new IndicatingAjaxLink<String>("tc-study") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    selectTC(item, tc, target);
                    try {
                        TCObject tcObject = TCObject.create(tc);
                        List<TCReferencedStudy> refStudies = tcObject.getReferencedStudies();
                        if (refStudies != null && !refStudies.isEmpty()) {
                            if (refStudies.size() == 1) {
                                studyPage.setStudyInstanceUID(refStudies.get(0).getStudyUID());
                            } else {
                                studyPage.setPatientIdAndIssuer(tc.getPatientId(), tc.getIssuerOfPatientId());
                            }
                        }
                        if (studyPage.getStudyInstanceUID() != null || studyPage.getPatientId() != null) {
                            studyPage.getStudyViewPort().clear();
                            studyWindow
                                    .setTitle(new StringResourceModel("tc.result.studywindow.title", this, null,
                                            new Object[] { maskNull(cutAtISOControl(tc.getTitle(), 40), "?"),
                                                    maskNull(cutAtISOControl(tc.getAbstract(), 25), "?"),
                                                    maskNull(cutAtISOControl(tc.getAuthor(), 20), "?"),
                                                    maskNull(tc.getCreationDate(), tc.getCreatedTime()) }));
                            studyWindow.setInitialWidth(1200);
                            studyWindow.setInitialHeight(600);
                            studyWindow.setMinimalWidth(800);
                            studyWindow.setMinimalHeight(400);
                            if (studyWindow.isShown()) {
                                log.warn("###### StudyView is already shown ???!!!");
                                try {
                                    Field showField = ModalWindow.class.getDeclaredField("shown");
                                    showField.setAccessible(true);
                                    showField.set(studyWindow, false);
                                } catch (Exception e) {
                                    log.error("Failed to reset shown Field from ModalWindow!");
                                }
                                log.info("###### studyWindow.isShown():" + studyWindow.isShown());
                            }
                            studyWindow.show(target);
                        } else {
                            log.warn("Showing TC referenced studies discarded: No referened study found!");
                            msgWin.setInfoMessage(getString("tc.result.studywindow.noStudies"));
                            msgWin.show(target);
                        }
                    } catch (Exception e) {
                        msgWin.setErrorMessage(getString("tc.result.studywindow.failed"));
                        msgWin.show(target);
                        log.error("Unable to show TC referenced studies!", e);
                    }
                }

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    tag.put("ondblclick", jsStopEventPropagationInline);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    try {
                        return TCPanel.getMaskingBehaviour().getAjaxCallDecorator();
                    } catch (Exception e) {
                        log.error("Failed to get IAjaxCallDecorator: ", e);
                    }
                    return null;
                }
            }.add(new Image("tcStudyImg", ImageManager.IMAGE_COMMON_SEARCH)
                    .add(new ImageSizeBehaviour("vertical-align: middle;")))
                    .add(new TooltipBehaviour("tc.result.table.", "showStudy"))
                    .add(new SecurityBehavior(TCPanel.getModuleName() + ":showTCStudy"))
                    .setOutputMarkupId(true);

            final Component forumLink = new IndicatingAjaxLink<String>("tc-forum") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        TCForumPostsPanel content = new TCForumPostsPanel(forumWindow.getContentId(),
                                new Model<String>(TCForumIntegration
                                        .get(WebCfgDelegate.getInstance().getTCForumIntegrationType())
                                        .getPostsPageURL(tc)));
                        forumWindow.setInitialHeight(820);
                        forumWindow.setInitialWidth(1024);
                        forumWindow.setContent(content);
                        forumWindow.show(target);
                    } catch (Exception e) {
                        log.error("Unable to open case forum page!", e);
                    }
                }

                @Override
                public boolean isVisible() {
                    return TCForumIntegration
                            .get(WebCfgDelegate.getInstance().getTCForumIntegrationType()) != null;
                }

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    tag.put("ondblclick", jsStopEventPropagationInline);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    try {
                        return TCPanel.getMaskingBehaviour().getAjaxCallDecorator();
                    } catch (Exception e) {
                        log.error("Failed to get IAjaxCallDecorator: ", e);
                    }
                    return null;
                }
            }.add(new Image("tcForumImg", ImageManager.IMAGE_TC_FORUM)
                    .add(new ImageSizeBehaviour("vertical-align: middle;")))
                    .add(new TooltipBehaviour("tc.result.table.", "showForum")).setOutputMarkupId(true);

            item.add(viewLink);
            item.add(editLink);
            item.add(studyLink);
            item.add(forumLink);

            item.add(new AttributeModifier("class", true, new AbstractReadOnlyModel<String>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (selected != null && selected.equals(tc)) {
                        return "mouse-out-selected";
                    } else {
                        return item.getIndex() % 2 == 1 ? "even-mouse-out" : "odd-mouse-out";
                    }
                }
            }));

            item.add(new AttributeModifier("selected", true, new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (selected != null && selected.equals(tc)) {
                        return "selected";
                    } else {
                        return null;
                    }
                }
            }));

            item.add(new AttributeModifier("onmouseover", true, new AbstractReadOnlyModel<String>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    StringBuffer sbuf = new StringBuffer();
                    sbuf.append("if ($(this).attr('selected')==null) {");
                    sbuf.append("   $(this).removeClass();");
                    sbuf.append("   if (").append(item.getIndex())
                            .append("%2==1) $(this).addClass('even-mouse-over');");
                    sbuf.append("   else $(this).addClass('odd-mouse-over');");
                    sbuf.append("}");
                    return sbuf.toString();
                }
            }));

            item.add(new AttributeModifier("onmouseout", true, new AbstractReadOnlyModel<String>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    StringBuffer sbuf = new StringBuffer();
                    sbuf.append("if ($(this).attr('selected')==null) {");
                    sbuf.append("   $(this).removeClass();");
                    sbuf.append("   if (").append(item.getIndex())
                            .append("%2==1) $(this).addClass('even-mouse-out');");
                    sbuf.append("   else $(this).addClass('odd-mouse-out');");
                    sbuf.append("}");
                    return sbuf.toString();
                }
            }));

            item.add(new AjaxEventBehavior("onclick") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onEvent(AjaxRequestTarget target) {
                    selectTC(item, tc, target);
                }
            });

            item.add(new AjaxEventBehavior("ondblclick") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onEvent(AjaxRequestTarget target) {
                    boolean edit = WebCfgDelegate.getInstance().getTCEditOnDoubleClick();
                    if (edit) {
                        edit = SecureComponentHelper.isActionAuthorized(editLink, "render");
                    }

                    openTC(selected, edit, target);
                }

                @Override
                protected IAjaxCallDecorator getAjaxCallDecorator() {
                    try {
                        return new IAjaxCallDecorator() {
                            private static final long serialVersionUID = 1L;

                            public final CharSequence decorateScript(CharSequence script) {
                                return "if(typeof showMask == 'function') { showMask(); $('body').css('cursor','wait'); };"
                                        + script;
                            }

                            public final CharSequence decorateOnSuccessScript(CharSequence script) {
                                return "hideMask();$('body').css('cursor','');" + script;
                            }

                            public final CharSequence decorateOnFailureScript(CharSequence script) {
                                return "hideMask();$('body').css('cursor','');" + script;
                            }
                        };
                    } catch (Exception e) {
                        log.error("Failed to get IAjaxCallDecorator: ", e);
                    }
                    return null;
                }
            });
        }
    };
    dataView.setItemReuseStrategy(new ReuseIfModelsEqualStrategy());
    dataView.setItemsPerPage(WebCfgDelegate.getInstance().getDefaultFolderPagesize());
    dataView.setOutputMarkupId(true);

    SortLinkGroup sortGroup = new SortLinkGroup(dataView);
    add(new SortLink("sortTitle", sortGroup, TCModel.Sorter.Title));
    add(new SortLink("sortAbstract", sortGroup, TCModel.Sorter.Abstract));
    add(new SortLink("sortDate", sortGroup, TCModel.Sorter.Date));
    add(new SortLink("sortAuthor", sortGroup, TCModel.Sorter.Author));

    add(dataView);

    add(new Label("numberOfMatchingInstances", new StringResourceModel("tc.list.numberOfMatchingInstances",
            this, null, new Object[] { new Model<Integer>() {

                private static final long serialVersionUID = 1L;

                @Override
                public Integer getObject() {
                    return ((TCListModel) TCResultPanel.this.getDefaultModel()).getObject().size();
                }
            } })));

    add(new PagingNavigator("navigator", dataView));
}

From source file:org.geoserver.web.wicket.browser.FileDataView.java

License:Open Source License

public FileDataView(String id, FileProvider fileProvider) {
    super(id);/* w  ww .j  a v a  2 s  .c  om*/

    this.provider = fileProvider;
    //        provider.setDirectory(currentPosition);
    //        provider.setSort(new SortParam(NAME, true));

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

    DataView fileTable = new DataView("files", fileProvider) {

        @Override
        protected void populateItem(final Item item) {
            File file = (File) item.getModelObject();

            // odd/even alternate style
            item.add(new SimpleAttributeModifier("class", item.getIndex() % 2 == 0 ? "even" : "odd"));

            // navigation/selection links
            AjaxFallbackLink link = new IndicatingAjaxFallbackLink("nameLink") {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    linkNameClicked((File) item.getModelObject(), target);
                }

            };
            link.add(new Label("name", item.getModel()) {
                @Override
                public IConverter getConverter(Class type) {
                    return FILE_NAME_CONVERTER;
                }
            });
            item.add(link);

            // last modified and size labels
            item.add(new Label("lastModified", item.getModel()) {
                @Override
                public IConverter getConverter(Class type) {
                    return FILE_LASTMODIFIED_CONVERTER;
                }
            });
            item.add(new Label("size", item.getModel()) {
                @Override
                public IConverter getConverter(Class type) {
                    return FILE_SIZE_CONVERTER;
                }
            });
        }

    };

    fileContent = new WebMarkupContainer("fileContent") {
        @Override
        protected void onComponentTag(ComponentTag tag) {
            if (tableHeight != null) {
                tag.getAttributes().put("style", "overflow:auto; height:" + tableHeight);
            }
        }
    };

    fileContent.add(fileTable);

    table.add(fileContent);
    table.add(new OrderByBorder("nameHeader", FileProvider.NAME, fileProvider));
    table.add(new OrderByBorder("lastModifiedHeader", FileProvider.LAST_MODIFIED, fileProvider));
    table.add(new OrderByBorder("sizeHeader", FileProvider.SIZE, fileProvider));
}

From source file:org.geoserver.web.wicket.GeoServerTablePanel.java

License:Open Source License

/**
 * Builds a new table panel//w  w  w.j a  va2  s.  c  o m
 */
public GeoServerTablePanel(final String id, final GeoServerDataProvider<T> dataProvider,
        final boolean selectable) {
    super(id);
    this.dataProvider = dataProvider;

    // prepare the selection array
    selection = new boolean[DEFAULT_ITEMS_PER_PAGE];

    // layer container used for ajax-y udpates of the table
    listContainer = new WebMarkupContainer("listContainer");

    // build the filter form
    filterForm = new Form("filterForm");
    filterForm.setOutputMarkupId(true);
    add(filterForm);
    filter = new TextField<String>("filter", new Model<String>()) {
        @Override
        protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            tag.put("onkeypress", "if(event.keyCode == 13) {document.getElementById('"
                    + hiddenSubmit.getMarkupId() + "').click();return false;}");

        }
    };
    filterForm.add(filter);
    filter.add(new SimpleAttributeModifier("title",
            String.valueOf(new ResourceModel("GeoServerTablePanel.search", "Search").getObject())));
    filterForm.add(hiddenSubmit = hiddenSubmit());
    filterForm.setDefaultButton(hiddenSubmit);

    // setup the table
    listContainer.setOutputMarkupId(true);
    add(listContainer);
    dataView = new DataView("items", dataProvider) {

        @Override
        protected Item newItem(String id, int index, IModel model) {
            // TODO Auto-generated method stub
            return new OddEvenItem<T>(id, index, model);
        }

        @Override
        protected void populateItem(Item item) {
            final IModel itemModel = item.getModel();

            // add row selector (visible only if selection is active)
            WebMarkupContainer cnt = new WebMarkupContainer("selectItemContainer");
            cnt.add(selectOneCheckbox(item));
            cnt.setVisible(selectable);
            item.add(cnt);

            buildRowListView(dataProvider, item, itemModel);
        }

    };
    dataView.setItemReuseStrategy(ReuseIfModelsEqualStrategy.getInstance());
    listContainer.add(dataView);

    // add select all checkbox
    WebMarkupContainer cnt = new WebMarkupContainer("selectAllContainer");
    cnt.add(selectAll = selectAllCheckbox());
    cnt.setVisible(selectable);
    listContainer.add(cnt);

    // add the sorting links
    listContainer.add(buildLinksListView(dataProvider));

    // add the paging navigator and set the items per page
    dataView.setItemsPerPage(DEFAULT_ITEMS_PER_PAGE);
    pagerDelegate = new PagerDelegate();

    filterForm.add(navigatorTop = new Pager("navigatorTop"));
    navigatorTop.setOutputMarkupId(true);
    add(navigatorBottom = new Pager("navigatorBottom"));
    navigatorBottom.setOutputMarkupId(true);
}

From source file:org.hippoecm.addon.workflow.MenuDrop.java

License:Apache License

MenuDrop(String id, ActionDescription wf, MenuHierarchy menu) {
    super(id);//from w w  w. ja v  a 2 s  .  c  om

    WebMarkupContainer headerItem;
    add(headerItem = new WebMarkupContainer("headerItem"));
    headerItem.add(new Label("header", new StringResourceModel("empty-menu", this, null)));

    List<Component> components = menu.list(this);
    add(new DataView("list", new ListDataProvider(components)) {
        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(final Item item) {
            MenuItem menuItem = (MenuItem) item.getModelObject();
            item.add(menuItem);
        }
    });

    if (components.size() > 0) {
        headerItem.setVisible(false);
    }
}

From source file:org.hippoecm.addon.workflow.MenuList.java

License:Apache License

MenuList(String id, MenuHierarchy menu, IPluginConfig config) {
    super(id);//w ww. ja  v  a  2s . c om
    this.menu = menu;
    this.list = menu.list(this);
    if (config != null) {
        this.twoColThreshold = config.getInt("menu.twoColThreshold", TWO_COL_THRESHOLD);
        this.threeColThreshold = config.getInt("menu.threeColThreshold", THREE_COL_THRESHOLD);
    } else {
        this.twoColThreshold = TWO_COL_THRESHOLD;
        this.threeColThreshold = THREE_COL_THRESHOLD;
    }
    threeColAttribute = new AttributeAppender("class", Model.of("hippo-toolbar-three-col"));
    twoColAttribute = new AttributeAppender("class", Model.of("hippo-toolbar-two-col"));

    add(new DataView<Component>("list", new ListDataProvider<Component>(list)) {

        public void populateItem(final Item<Component> item) {
            Component menuItem = item.getModelObject();
            item.add(menuItem);
        }
    });
}

From source file:org.hippoecm.frontend.editor.plugins.linkpicker.FacetSelectTemplatePlugin.java

License:Apache License

public FacetSelectTemplatePlugin(final IPluginContext context, IPluginConfig config) {
    super(context, config);

    Node node = getModelObject();
    try {//from  www  .j  av a2s .  co  m
        if (!node.hasProperty("hippo:docbase")) {
            node.setProperty("hippo:docbase", node.getSession().getRootNode().getUUID());
        }
        if (!node.hasProperty("hippo:facets")) {
            node.setProperty("hippo:facets", new String[0]);
        }
        if (!node.hasProperty("hippo:values")) {
            node.setProperty("hippo:values", new String[0]);
        }
        if (!node.hasProperty("hippo:modes")) {
            node.setProperty("hippo:modes", new String[0]);
        }
    } catch (ValueFormatException e) {
        log.error(e.getMessage());
    } catch (PathNotFoundException e) {
        log.error(e.getMessage());
    } catch (RepositoryException e) {
        log.error(e.getMessage());
    }

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

        @Override
        protected String load() {
            Node node = FacetSelectTemplatePlugin.this.getModelObject();
            try {
                if (node != null && node.hasProperty("hippo:docbase")) {
                    String docbaseUUID = node.getProperty("hippo:docbase").getString();
                    if (docbaseUUID == null || docbaseUUID.equals("") || docbaseUUID.startsWith("cafebabe-")) {
                        return EMPTY_LINK_TEXT;
                    }
                    return node.getSession().getNodeByUUID(docbaseUUID).getPath();
                }
            } catch (ValueFormatException e) {
                log.warn("Invalid value format for docbase " + e.getMessage());
                log.debug("Invalid value format for docbase ", e);
            } catch (PathNotFoundException e) {
                log.warn("Docbase not found " + e.getMessage());
                log.debug("Docbase not found ", e);
            } catch (RepositoryException e) {
                log.error("Invalid docbase" + e.getMessage(), e);
            }
            return EMPTY_LINK_TEXT;
        }
    };

    mode = IEditor.Mode.fromString(config.getString("mode"), IEditor.Mode.VIEW);
    try {
        IDataProvider<Integer> provider = new IDataProvider<Integer>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Iterator<Integer> iterator(long first, long count) {
                return new Iterator<Integer>() {
                    int current = 0;

                    public boolean hasNext() {
                        try {
                            Node node = ((JcrNodeModel) FacetSelectTemplatePlugin.this.getDefaultModel())
                                    .getNode();
                            return current < node.getProperty("hippo:facets").getValues().length;
                        } catch (RepositoryException ex) {
                            return false;
                        }
                    }

                    public Integer next() {
                        if (hasNext()) {
                            return Integer.valueOf(current++);
                        } else {
                            throw new NoSuchElementException();
                        }
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }

            @Override
            public long size() {
                try {
                    Node node = ((JcrNodeModel) FacetSelectTemplatePlugin.this.getDefaultModel()).getNode();
                    return node.getProperty("hippo:facets").getValues().length;
                } catch (RepositoryException ex) {
                    return 0;
                }
            }

            @Override
            public IModel<Integer> model(Integer object) {
                return new Model<Integer>(object);
            }

            @Override
            public void detach() {
            }
        };
        if (IEditor.Mode.EDIT == mode) {
            final JcrPropertyValueModel<String> docbaseModel = new JcrPropertyValueModel<String>(
                    new JcrPropertyModel<String>(node.getProperty("hippo:docbase")));

            IDialogFactory dialogFactory = new IDialogFactory() {
                private static final long serialVersionUID = 1L;

                public AbstractDialog<String> createDialog() {
                    final IPluginConfig dialogConfig = LinkPickerDialogConfig
                            .fromPluginConfig(getPluginConfig(), docbaseModel);
                    return new LinkPickerDialog(context, dialogConfig, new IChainingModel<String>() {
                        private static final long serialVersionUID = 1L;

                        public String getObject() {
                            return docbaseModel.getObject();
                        }

                        public void setObject(String object) {
                            docbaseModel.setObject(object);
                            redraw();
                        }

                        public IModel<String> getChainedModel() {
                            return docbaseModel;
                        }

                        public void setChainedModel(IModel<?> model) {
                            throw new UnsupportedOperationException("Value model cannot be changed");
                        }

                        public void detach() {
                            docbaseModel.detach();
                        }
                    });
                }
            };

            add(new ClearableDialogLink("docbase", displayModel, dialogFactory, getDialogService()) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClear() {
                    Node node = ((JcrNodeModel) FacetSelectTemplatePlugin.this.getDefaultModel()).getNode();
                    try {
                        node.setProperty("hippo:docbase", node.getSession().getRootNode().getUUID());
                    } catch (RepositoryException e) {
                        log.error("Unable to reset docbase to rootnode uuid", e);
                    }
                    redraw();
                }

                @Override
                public boolean isClearVisible() {
                    // Checking for string literals ain't pretty. It's probably better to create a better display model.
                    return !EMPTY_LINK_TEXT.equals((String) displayModel.getObject());
                }
            });

            add(new DataView<Integer>("arguments", provider) {
                private static final long serialVersionUID = 1L;

                @Override
                public void populateItem(final Item<Integer> item) {
                    Node node = FacetSelectTemplatePlugin.this.getModelObject();
                    final int index = item.getModelObject().intValue();
                    try {
                        item.add(new TextFieldWidget("facet", new JcrPropertyValueModel<String>(index,
                                new JcrPropertyModel<String>(node.getProperty("hippo:facets")))));
                        item.add(new TextFieldWidget("mode", new JcrPropertyValueModel<String>(index,
                                new JcrPropertyModel<String>(node.getProperty("hippo:modes")))));
                        item.add(new TextFieldWidget("value", new JcrPropertyValueModel<String>(index,
                                new JcrPropertyModel<String>(node.getProperty("hippo:values")))));
                        AjaxLink<Void> removeButton;
                        item.add(removeButton = new AjaxLink<Void>("remove") {
                            private static final long serialVersionUID = 1L;

                            @Override
                            public void onClick(AjaxRequestTarget target) {
                                Node node = ((JcrNodeModel) FacetSelectTemplatePlugin.this.getDefaultModel())
                                        .getNode();
                                for (String property : new String[] { "hippo:facets", "hippo:modes",
                                        "hippo:values" }) {
                                    try {
                                        Value[] oldValues = node.getProperty(property).getValues();
                                        Value[] newValues = new Value[oldValues.length - 1];
                                        System.arraycopy(oldValues, 0, newValues, 0, index);
                                        System.arraycopy(oldValues, index + 1, newValues, 0,
                                                oldValues.length - index - 1);
                                        node.setProperty(property, newValues);
                                    } catch (RepositoryException ex) {
                                        log.error("cannot add new facet select line", ex);
                                    }
                                }
                                FacetSelectTemplatePlugin.this.redraw();
                            }
                        });
                        removeButton.setOutputMarkupId(true);
                    } catch (RepositoryException ex) {
                        log.error("cannot read facet select line", ex);
                    }
                }
            });
            AjaxLink<Void> addButton;
            add(addButton = new AjaxLink<Void>("add") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    Node node = ((JcrNodeModel) FacetSelectTemplatePlugin.this.getDefaultModel()).getNode();
                    for (String property : new String[] { "hippo:facets", "hippo:modes", "hippo:values" }) {
                        try {
                            Value[] oldValues = node.getProperty(property).getValues();
                            Value[] newValues = new Value[oldValues.length + 1];
                            System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
                            newValues[newValues.length - 1] = node.getSession().getValueFactory()
                                    .createValue("");
                            node.setProperty(property, newValues);
                        } catch (RepositoryException ex) {
                            log.error("cannot add new facet select line", ex);
                        }
                    }
                    FacetSelectTemplatePlugin.this.redraw();
                }
            });
            addButton.setOutputMarkupId(true);
        } else {
            add(new Label("docbase", displayModel));
            add(new DataView<Integer>("arguments", provider) {
                private static final long serialVersionUID = 1L;

                @Override
                public void populateItem(final Item<Integer> item) {
                    try {
                        Node node = FacetSelectTemplatePlugin.this.getModelObject();
                        int index = item.getModelObject().intValue();
                        item.add(new Label("facet",
                                node.getProperty("hippo:facets").getValues()[index].getString()));
                        item.add(new Label("mode",
                                node.getProperty("hippo:modes").getValues()[index].getString()));
                        item.add(new Label("value",
                                node.getProperty("hippo:values").getValues()[index].getString()));
                        Label removeButton;
                        item.add(removeButton = new Label("remove"));
                        removeButton.setVisible(false);
                    } catch (RepositoryException ex) {
                        log.error("cannot read facet select line", ex);
                    }
                }
            });
            Label addButton;
            add(addButton = new Label("add"));
            addButton.setVisible(false);
        }
    } catch (PathNotFoundException ex) {
        log.error("failed to read existing facet select", ex);
    } catch (ValueFormatException ex) {
        log.error("failed to read existing facet select", ex);
    } catch (RepositoryException ex) {
        log.error("failed to read existing facet select", ex);
    }

    setOutputMarkupId(true);
}

From source file:org.hippoecm.frontend.translation.workflow.TranslationWorkflowPlugin.java

License:Apache License

public TranslationWorkflowPlugin(IPluginContext context, IPluginConfig config) {
    super(context, config);

    final IModel<String> languageModel = new LanguageModel();
    final ILocaleProvider localeProvider = getLocaleProvider();

    DocumentTranslationProvider docTranslationProvider = null;
    try {//  w  ww .  j  ava 2  s.  c  o m
        docTranslationProvider = new DocumentTranslationProvider(new JcrNodeModel(getDocumentNode()),
                localeProvider);
    } catch (RepositoryException e) {
        log.warn("Unable to find document node");
    }
    translationProvider = docTranslationProvider;

    // lazily determine whether the document can be translated
    canTranslateModel = new LoadableDetachableModel<Boolean>() {
        @Override
        protected Boolean load() {
            WorkflowDescriptor descriptor = getModelObject();
            if (descriptor != null) {
                try {
                    Map<String, Serializable> hints = descriptor.hints();
                    if (hints.containsKey("addTranslation")
                            && hints.get("addTranslation").equals(Boolean.FALSE)) {
                        return false;
                    }

                } catch (RepositoryException e) {
                    log.error("Failed to analyze hints for translations workflow", e);
                }
            }
            return true;
        }
    };

    add(new EmptyPanel("content"));

    add(new MenuDescription() {
        private static final long serialVersionUID = 1L;

        @Override
        public Component getLabel() {
            Fragment fragment = new Fragment("label", "label", TranslationWorkflowPlugin.this);
            HippoLocale locale = localeProvider.getLocale(languageModel.getObject());
            ResourceReference resourceRef = locale.getIcon(IconSize.M, LocaleState.EXISTS);
            fragment.add(new CachingImage("img", resourceRef));
            fragment.add(new Label("current-language", locale.getDisplayName(getLocale())));
            return fragment;
        }

        @Override
        public MarkupContainer getContent() {
            Fragment fragment = new Fragment("content", "languages", TranslationWorkflowPlugin.this);
            fragment.add(new DataView<HippoLocale>("languages", new AvailableLocaleProvider(localeProvider)) {
                private static final long serialVersionUID = 1L;

                {
                    onPopulate();
                }

                @Override
                protected void populateItem(Item<HippoLocale> item) {
                    final HippoLocale locale = item.getModelObject();
                    final String language = locale.getName();

                    item.add(new TranslationAction("language", new LoadableDetachableModel<String>() {

                        @Override
                        protected String load() {
                            String base = locale.getDisplayName(getLocale());
                            if (!hasLocale(language)) {
                                return base + "...";
                            }
                            return base;
                        }
                    }, item.getModel(), language, languageModel));
                }

                @Override
                protected void onDetach() {
                    languageModel.detach();
                    super.onDetach();
                }
            });
            TranslationWorkflowPlugin.this.addOrReplace(fragment);
            return fragment;
        }
    });

}

From source file:org.jabylon.rest.ui.wicket.panels.ProjectResourcePanel.java

License:Open Source License

@Override
protected void onBeforeRenderPanel() {
    ComplexEObjectListDataProvider<Resolvable<?, ?>> provider = new ComplexEObjectListDataProvider<Resolvable<?, ?>>(
            getModel(), PropertiesPackage.Literals.RESOLVABLE__CHILDREN);
    final boolean endsOnSlash = urlEndsOnSlash();
    final DataView<Resolvable<?, ?>> dataView = new DataView<Resolvable<?, ?>>("children", provider) {

        private static final long serialVersionUID = -3530355534807668227L;

        @Override//from w  w w. j av  a2s . c  o m
        protected void populateItem(Item<Resolvable<?, ?>> item) {
            Resolvable<?, ?> resolvable = item.getModelObject();

            item.setVisible(canView(resolvable));
            if (resolvable instanceof ProjectLocale) {
                // hide the template language by default
                ProjectLocale locale = (ProjectLocale) resolvable;
                if (locale.isMaster())
                    item.setVisible(false);

            }

            LinkTarget target = buildLinkTarget(resolvable, endsOnSlash);

            ExternalLink link = new ExternalLink("link", Model.of(target.getHref()), target.getLabel());
            item.add(link);

            Triplet widths = computeProgressBars(target.getEndPoint());
            Label progress = new Label("progress", String.valueOf(widths.getSuccess()) + "%");
            progress.add(new AttributeModifier("style", "width: " + widths.getSuccess() + "%"));
            Label warning = new Label("warning", "");
            warning.add(new AttributeModifier("style", "width: " + widths.getWarning() + "%"));
            Label danger = new Label("danger", "");
            danger.add(new AttributeModifier("style", "width: " + widths.getDanger() + "%"));
            item.add(progress);
            item.add(warning);
            item.add(danger);

            new ImageSwitch(item).doSwitch(target.getEndPoint());
            item.add(new Label("summary", new Summary(item).doSwitch(target.getEndPoint())));
        }

    };
    // dataView.setItemsPerPage(10);
    add(dataView);
}

From source file:org.jaulp.wicket.data.provider.examples.dataview.SortableDataViewPanel.java

License:Apache License

/**
 * Instantiates a new sortable data view panel.
 * /* w w w. ja v a  2s .com*/
 * @param id
 *            the id
 */
public SortableDataViewPanel(String id) {
    super(id);
    List<Person> persons = getPersons();

    SortableFilterPersonDataProvider dataProvider = new SortableFilterPersonDataProvider(persons) {

        private static final long serialVersionUID = 1L;

        @Override
        public List<Person> getData() {
            return getPersons();
        }
    };

    dataProvider.setSort("firstname", SortOrder.ASCENDING);

    final DataView<Person> dataView = new DataView<Person>("dataView", dataProvider) {
        /**
         * The serialVersionUID.
         */
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(Item<Person> item) {
            item.setDefaultModel(new CompoundPropertyModel<Person>(item.getModel()));
            item.add(new Label("firstname"));
            item.add(new Label("lastname"));
            item.add(new Label("dateOfBirth"));
        }
    };

    dataView.setItemsPerPage(10);
    add(dataView);

    add(new OrderByBorder<String>("orderByFirstname", "firstname", dataProvider));
    add(new OrderByBorder<String>("orderByLastname", "lastname", dataProvider));
    add(new OrderByBorder<String>("orderByDateOfBirth", "dateOfBirth", dataProvider));
    add(new NavigatorLabel("label", dataView));
    add(new PagingNavigator("topNavigator", dataView));
    add(new PagingNavigator("footernavigator", dataView));
}

From source file:org.jboss.seam.example.wicket.Main.java

License:Apache License

public Main(final PageParameters parameters) {
    Template body = new Template("body");
    add(body);//from  w  w w . j  ava  2s .  c  o  m
    hotelSearchForm = new HotelSearchForm("searchCriteria");
    body.add(hotelSearchForm);

    messages = new FeedbackPanel("messages", new ContainerFeedbackMessageFilter(this)).setOutputMarkupId(true);
    body.add(messages);

    /*
     * Hotel Search results
     */
    noHotelsFound = new Label("noResults", "No Hotels Found") {
        /**
         * Only display the message if no hotels are found
         * 
         */
        @Override
        public boolean isVisible() {
            return Identity.instance().isLoggedIn() && hotelSearch.getHotels().size() == 0;
        }
    };
    body.add(noHotelsFound.setOutputMarkupId(true));
    hotelDataView = new DataView("hotel", new SimpleDataProvider() // A DataProvider adapts between your data and Wicket's internal representation
    {
        public Iterator iterator(int from, int count) {
            return hotelSearch.getHotels().subList(from, from + count).iterator();
        }

        public int size() {
            return hotelSearch.getHotels().size();
        }

    }) {
        /**
         * You specify the tr in the html, and populate each one here
         */
        @Override
        protected void populateItem(Item item) {
            final Hotel hotel = (Hotel) item.getModelObject();
            item.add(new Label("hotelName", hotel.getName()));
            item.add(new Label("hotelAddress", hotel.getAddress()));
            item.add(new Label("hotelCityStateCountry",
                    hotel.getCity() + ", " + hotel.getState() + ", " + hotel.getCountry()));
            item.add(new Label("hotelZip", hotel.getZip()));
            //item.add(new BookmarkablePageLink("viewHotel", org.jboss.seam.example.wicket.Hotel.class).setParameter("hotelId", hotel.getId()));
            item.add(new Link("viewHotel") {

                @Override
                @Begin
                public void onClick() {
                    hotelBooking.selectHotel(hotel);
                    setResponsePage(org.jboss.seam.example.wicket.Hotel.class);
                }

            });
        }

    };

    // Set the maximum items per page
    hotelDataView.setItemsPerPage(hotelSearchForm.getPageSize());
    hotelDataView.setOutputMarkupId(true);
    hotels = new WebMarkupContainer("hotels");
    hotels.add(hotelDataView).setOutputMarkupId(true);

    // Add a pager
    hotels.add(new AjaxPagingNavigator("hotelPager", hotelDataView) {
        @Override
        public boolean isVisible() {
            return hotelDataView.isVisible();
        }

    });

    body.add(hotels);

    /*
     * Existing hotel booking
     */
    bookedHotelDataView = new DataView("bookedHotel", new SimpleDataProvider() {
        public Iterator iterator(int from, int count) {
            return bookings.subList(from, from + count).iterator();
        }

        public int size() {
            return bookings.size();
        }

    }) {

        @Override
        protected void populateItem(Item item) {
            final Booking booking = (Booking) item.getModelObject();
            item.add(new Label("hotelName", booking.getHotel().getName()));
            item.add(new Label("hotelAddress", booking.getHotel().getAddress()));
            item.add(new Label("hotelCityStateCountry", booking.getHotel().getCity() + ", "
                    + booking.getHotel().getState() + ", " + booking.getHotel().getState()));
            item.add(new Label("hotelCheckInDate", booking.getCheckinDate().toString()));
            item.add(new Label("hotelCheckOutDate", booking.getCheckoutDate().toString()));
            item.add(new Label("hotelConfirmationNumber", booking.getId().toString()));
            item.add(new Link("cancel") {

                @Override
                public void onClick() {
                    bookingList.cancel(booking);
                }

            });
        }

        @Override
        public boolean isVisible() {
            return Identity.instance().isLoggedIn() && bookings.size() > 0;
        }

    };
    body.add(bookedHotelDataView);
    body.add(new Label("noHotelsBooked", "No Bookings Found") {
        @Override
        public boolean isVisible() {
            return Identity.instance().isLoggedIn() && bookings.size() == 0;
        }
    });
}