Example usage for org.apache.wicket.extensions.ajax.markup.html.modal ModalWindow getContentId

List of usage examples for org.apache.wicket.extensions.ajax.markup.html.modal ModalWindow getContentId

Introduction

In this page you can find the example usage for org.apache.wicket.extensions.ajax.markup.html.modal ModalWindow getContentId.

Prototype

public String getContentId() 

Source Link

Document

Returns the id of content component.

Usage

From source file:org.xaloon.wicket.plugin.user.admin.panel.RoleDetailPanelTest.java

License:Apache License

/**
 * @throws Exception//from   ww  w.  ja  v  a  2s.  co  m
 */
@Test
public void testAssignAuthority() throws Exception {
    PageParameters params = new PageParameters();
    params.add(Bookmarkable.PARAM_PATH, path);
    tester.startComponentInPage(new RoleDetailPanel("id", params));
    tester.assertRenderedPage(StartComponentInPage.class);

    Assert.assertNotNull(tester.getTagByWicketId("name"));
    Assert.assertNotNull(tester.getTagByWicketId("authority-admin"));
    Assert.assertEquals(2, tester.getTagsByWicketId("name").size());

    // TEST ASSIGN ROLE TO GROUP
    Assert.assertNotNull(tester.getTagByWicketId("link-assign-entities"));
    tester.clickLink("id:authority-admin:choice-management:link-assign-entities");
    tester.assertNoErrorMessage();

    ModalWindow modalWindow = (ModalWindow) tester
            .getComponentFromLastRenderedPage("id:authority-admin:choice-management:modal-assign-entities");
    String modalPath = modalWindow.getPageRelativePath() + ":" + modalWindow.getContentId();
    Assert.assertTrue(modalWindow.isVisible());

    // Submit the form
    String formPath = modalPath + ":form";
    FormTester form = tester.newFormTester(formPath);
    form.selectMultiple("choices", new int[] { 1 });

    Mockito.when(roleService.assignChildren((SecurityRole) Matchers.anyObject(),
            Matchers.anyListOf(Authority.class))).thenAnswer(new Answer<SecurityGroup>() {

                @SuppressWarnings("unchecked")
                @Override
                public SecurityGroup answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    List<Authority> selections = (List<Authority>) args[1];
                    Assert.assertEquals(1, selections.size());
                    Assert.assertEquals(availableAuthorities.get(1), selections.get(0));
                    return null;
                }
            });
    // Submit ajax form
    tester.executeAjaxEvent(formPath + ":submit", "onclick");
}

From source file:org.xaloon.wicket.plugin.user.admin.panel.RolesPanel.java

License:Apache License

@Override
protected void onBeforeRender() {
    super.onBeforeRender();
    removeAll();//ww w . ja va  2 s.c om

    // Add paging navigation container with navigation toolbar
    final DecoratedPagingNavigatorContainer<SecurityRole> dataContainer = new DecoratedPagingNavigatorContainer<SecurityRole>(
            "container", getCurrentRedirectLink());
    addOrReplace(dataContainer);
    dataContainer.setOutputMarkupId(true);

    // Add blog list data view
    final DataView<SecurityRole> securityGroupDataView = new DataView<SecurityRole>("security-roles",
            new JpaSecurityRoleDataProvider()) {
        private static final long serialVersionUID = 1L;

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

            PageParameters pageParams = new PageParameters();
            pageParams.add(Bookmarkable.PARAM_PATH, role.getPath());
            BookmarkablePageLink<Void> roleLink = new BookmarkablePageLink<Void>("roleDetails",
                    RoleDetailPage.class, pageParams);
            item.add(roleLink);
            roleLink.add(new Label("name", new Model<String>(role.getName())));

            // Add delete role link
            item.add(new ConfirmationAjaxLink<Void>("delete") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    roleService.delete(role);
                    target.add(dataContainer);
                }

            });
        }
    };
    dataContainer.addAbstractPageableView(securityGroupDataView);

    // Add the modal window to create new group
    final ModalWindow addNewGroupModalWindow = new CustomModalWindow("modal-new-role", "New role") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void addComponentsToRefresh(java.util.List<Component> components) {
            components.add(RolesPanel.this);
        };
    };
    addNewGroupModalWindow.setContent(new CreateNewEntityPanel<SecurityRole>(
            addNewGroupModalWindow.getContentId(), new Model<SecurityRole>(roleService.newAuthority())) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onNewEntitySubmit(AjaxRequestTarget target, SecurityRole entity) {
            roleService.save(entity);
            addNewGroupModalWindow.close(target);
        }
    });
    add(addNewGroupModalWindow);

    // add new group link
    add(new AjaxLink<Void>("add-new-role") {
        private static final long serialVersionUID = 1L;

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

From source file:org.xaloon.wicket.plugin.user.admin.panel.RolesPanelTest.java

License:Apache License

/**
 * @throws Exception//  ww  w .j  a v  a  2  s.  c  om
 */
@Test
public void testPanelAuthorized() throws Exception {
    MockedApplication app = createMockedApplication();
    WicketTester tester = new WicketTester(app);

    // Set security to True by default
    when(app.getSecurityFacade().hasAny(SecurityAuthorities.SYSTEM_ADMINISTRATOR)).thenReturn(true);

    // Return at least one role
    when(roleService.getCount()).thenReturn(1L);

    SecurityRole role = mock(SecurityRole.class);
    when(role.getPath()).thenReturn("role-name");

    List<SecurityRole> roles = new ArrayList<SecurityRole>();
    roles.add(role);
    when(roleService.getAuthorities(0, 1)).thenReturn(roles);

    SecurityRole securityRole = new JpaRole();
    when(roleService.newAuthority()).thenReturn(securityRole);

    tester.startComponentInPage(new RolesPanel("id", new PageParameters()));
    assertNotNull(tester.getTagByWicketId("container"));
    assertNotNull(tester.getTagByWicketId("security-roles"));
    assertEquals(1, tester.getTagsByWicketId("name").size());

    // Test creating new role
    tester.clickLink("id:add-new-role");
    tester.assertNoErrorMessage();

    // Get the modal window and submit the form
    ModalWindow modal = (ModalWindow) tester.getComponentFromLastRenderedPage("id:modal-new-role");
    tester.isVisible(modal.getPageRelativePath());

    // Close and re-open modal window
    closeModalWindow(modal, tester);
    tester.clickLink("id:add-new-role");
    tester.assertNoErrorMessage();
    modal = (ModalWindow) tester.getComponentFromLastRenderedPage("id:modal-new-role");

    // Take the form
    String modalPath = modal.getPageRelativePath() + ":" + modal.getContentId();
    String formPath = modalPath + ":new-entity";
    FormTester form = tester.newFormTester(formPath);
    form.setValue("name", "testValue");

    // Submit ajax form
    tester.executeAjaxEvent(formPath + ":submit", "onclick");

    // Validate result
    tester.assertNoErrorMessage();

    Assert.assertEquals("testValue", securityRole.getName());
}

From source file:org.xaloon.wicket.plugin.user.admin.panel.UserSecurityPanelTest.java

License:Apache License

/**
 * @throws Exception/*from   w  w  w  .j  a va 2s .c o  m*/
 */
@Test
public void testPanelAuthoritiesAssign() throws Exception {
    // Add mocked invocations

    // return available authorities
    Mockito.when(authorityService.getAuthorities(0, -1)).thenReturn(availableAuthorities);

    // return given authorities to user
    final List<Authority> givenAuthorities = new ArrayList<Authority>();
    givenAuthorities.add(newAuthority(777L, "fake-authority"));
    Mockito.when(details.getAuthorities()).thenReturn(givenAuthorities);

    Mockito.when(authorityService.assignAuthorities((UserDetails) Matchers.anyObject(),
            Matchers.anyListOf(Authority.class))).thenAnswer(new Answer<SecurityGroup>() {

                @SuppressWarnings("unchecked")
                @Override
                public SecurityGroup answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    List<Authority> selections = (List<Authority>) args[1];
                    Assert.assertEquals(1, selections.size());
                    Assert.assertEquals(availableAuthorities.get(2), selections.get(0));
                    return null;
                }
            });

    // Start the test

    // Start the panel before each test
    PageParameters params = new PageParameters();
    params.add(UsersPage.PARAM_USER_ID, "demo");
    tester.startComponentInPage(new UserSecurityPanel("id", params));
    tester.assertNoErrorMessage();
    tester.assertRenderedPage(BaseWicketTester.StartComponentInPage.class);

    Assert.assertNotNull(tester.getTagByWicketId("authority-admin"));
    Assert.assertNotNull(tester.getTagByWicketId("link-assign-entities"));

    // Open the modal window
    tester.clickLink("id:authority-container:authority-admin:choice-management:link-assign-entities");
    tester.assertNoErrorMessage();

    ModalWindow modalWindow = (ModalWindow) tester.getComponentFromLastRenderedPage(
            "id:authority-container:authority-admin:choice-management:modal-assign-entities");
    String modalPath = modalWindow.getPageRelativePath() + ":" + modalWindow.getContentId();
    Assert.assertTrue(modalWindow.isVisible());

    // Submit the form
    String formPath = modalPath + ":form";
    FormTester form = tester.newFormTester(formPath);
    form.selectMultiple("choices", new int[] { 2 });

    // Submit ajax form
    tester.executeAjaxEvent(formPath + ":submit", "onclick");
}

From source file:org.xaloon.wicket.plugin.user.admin.panel.UserSecurityPanelTest.java

License:Apache License

/**
 * @throws Exception// ww w  . jav  a2 s .c  o m
 */
@Test
public void testPanelRolesAssign() throws Exception {
    // Add mocked invocations

    // return available roles
    Mockito.when(roleService.getAuthorities(0, -1)).thenReturn(availableRoles);

    // return given roles to user
    final List<SecurityRole> givenRoles = new ArrayList<SecurityRole>();
    givenRoles.add(newRole(777L, "fake-role"));
    Mockito.when(details.getRoles()).thenReturn(givenRoles);

    Mockito.when(roleService.assignAuthorities((UserDetails) Matchers.anyObject(),
            Matchers.anyListOf(SecurityRole.class))).thenAnswer(new Answer<SecurityGroup>() {

                @SuppressWarnings("unchecked")
                @Override
                public SecurityGroup answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    List<SecurityRole> selections = (List<SecurityRole>) args[1];
                    Assert.assertEquals(1, selections.size());
                    Assert.assertEquals(availableRoles.get(2), selections.get(0));
                    return null;
                }
            });

    // Start the test

    // Start the panel before each test
    PageParameters params = new PageParameters();
    params.add(UsersPage.PARAM_USER_ID, "demo");
    tester.startComponentInPage(new UserSecurityPanel("id", params));
    tester.assertNoErrorMessage();
    tester.assertRenderedPage(BaseWicketTester.StartComponentInPage.class);

    Assert.assertNotNull(tester.getTagByWicketId("role-admin"));
    Assert.assertNotNull(tester.getTagByWicketId("link-assign-entities"));

    // Open the modal window
    tester.clickLink("id:role-container:role-admin:choice-management:link-assign-entities");
    tester.assertNoErrorMessage();

    ModalWindow modalWindow = (ModalWindow) tester.getComponentFromLastRenderedPage(
            "id:role-container:role-admin:choice-management:modal-assign-entities");
    String modalPath = modalWindow.getPageRelativePath() + ":" + modalWindow.getContentId();
    Assert.assertTrue(modalWindow.isVisible());

    // Submit the form
    String formPath = modalPath + ":form";
    FormTester form = tester.newFormTester(formPath);
    form.selectMultiple("choices", new int[] { 2 });

    // Submit ajax form
    tester.executeAjaxEvent(formPath + ":submit", "onclick");
}

From source file:org.xaloon.wicket.plugin.user.admin.panel.UserSecurityPanelTest.java

License:Apache License

/**
 * @throws Exception/*  ww  w . ja  v a 2  s  .c o  m*/
 */
@Test
public void testPanelGroupsAssign() throws Exception {
    // Add mocked invocations

    // return available groups
    Mockito.when(groupService.getAuthorities(0, -1)).thenReturn(availableGroups);

    // return given groups to user
    final List<SecurityGroup> givenGroups = new ArrayList<SecurityGroup>();
    givenGroups.add(newGroup(777L, "fake-group"));
    Mockito.when(details.getGroups()).thenReturn(givenGroups);

    Mockito.when(groupService.assignAuthorities((UserDetails) Matchers.anyObject(),
            Matchers.anyListOf(SecurityGroup.class))).thenAnswer(new Answer<SecurityGroup>() {

                @SuppressWarnings("unchecked")
                @Override
                public SecurityGroup answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    List<SecurityGroup> selections = (List<SecurityGroup>) args[1];
                    Assert.assertEquals(1, selections.size());
                    Assert.assertEquals(availableGroups.get(2), selections.get(0));
                    return null;
                }
            });

    // Start the test

    // Start the panel before each test
    PageParameters params = new PageParameters();
    params.add(UsersPage.PARAM_USER_ID, "demo");
    tester.startComponentInPage(new UserSecurityPanel("id", params));
    tester.assertNoErrorMessage();
    tester.assertRenderedPage(BaseWicketTester.StartComponentInPage.class);

    Assert.assertNotNull(tester.getTagByWicketId("group-admin"));
    Assert.assertNotNull(tester.getTagByWicketId("link-assign-entities"));

    // Open the modal window
    tester.clickLink("id:group-container:group-admin:choice-management:link-assign-entities");
    tester.assertNoErrorMessage();

    ModalWindow modalWindow = (ModalWindow) tester.getComponentFromLastRenderedPage(
            "id:group-container:group-admin:choice-management:modal-assign-entities");
    String modalPath = modalWindow.getPageRelativePath() + ":" + modalWindow.getContentId();
    Assert.assertTrue(modalWindow.isVisible());

    // Submit the form
    String formPath = modalPath + ":form";
    FormTester form = tester.newFormTester(formPath);
    form.selectMultiple("choices", new int[] { 2 });

    // Submit ajax form
    tester.executeAjaxEvent(formPath + ":submit", "onclick");
}

From source file:ro.nextreports.server.web.core.HeaderPanel.java

License:Apache License

public HeaderPanel(String id) {
    super(id);//from w w  w  . j  a  v  a2 s .com

    final WebMarkupContainer imageContainer = new WebMarkupContainer("imageContainer");
    imageContainer.setOutputMarkupPlaceholderTag(true);
    imageContainer.add(new Image("logoImage", new LogoResource()));
    add(imageContainer);

    add(new Label("currentUser", NextServerSession.get().getUsername()));
    add(new Label("realName", NextServerSession.get().getRealName()));

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

    Link<String> logoutLink = new Link<String>("logout") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            NextServerSession.get().signOut();

            if (CasUtil.isCasUsed()) {
                setResponsePage(new RedirectPage(CasUtil.getLogoutUrl()));
            } else {
                setResponsePage(getApplication().getHomePage());
            }
        }

    };
    add(logoutLink);

    AjaxLink<String> changePassword = new AjaxLink<String>("changePassord") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            dialog.setTitle(getString("ChangePassword.change"));
            dialog.setInitialWidth(350);
            dialog.setUseInitialHeight(false);
            dialog.setContent(new ChangePasswordPanel(dialog.getContentId()) {

                private static final long serialVersionUID = 1L;

                @Override
                public void onChange(AjaxRequestTarget target) {
                    ModalWindow.closeCurrent(target);
                    try {
                        User loggedUser = securityService.getUserByName(NextServerSession.get().getUsername());
                        loggedUser.setPassword(passwordEncoder.encodePassword(confirmPassword, null));
                        storageService.modifyEntity(loggedUser);
                    } catch (Exception e) {
                        e.printStackTrace();
                        add(new AlertBehavior(e.getMessage()));
                        target.add(this);
                    }
                }

                @Override
                public void onCancel(AjaxRequestTarget target) {
                    ModalWindow.closeCurrent(target);
                }

            });
            dialog.show(target);
        }
    };
    add(changePassword);
    if (NextServerSession.get().isDemo()) {
        changePassword.setEnabled(false);
    }
}

From source file:ro.nextreports.server.web.core.migration.ExportPanel.java

License:Apache License

@SuppressWarnings("unchecked")
public ExportPanel(String id) {
    super(id);//w  ww  . j  a v a 2s. c om

    final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    feedbackPanel.setOutputMarkupId(true);
    add(feedbackPanel);

    Form<Void> exportForm = new Form<Void>("exportForm");
    add(exportForm);

    final Model<ArrayList<String>> choiceModel = new Model<ArrayList<String>>();
    final ListMultipleChoice listChoice = new ListMultipleChoice("listChoice", choiceModel,
            new PropertyModel<String>(this, "list"));
    listChoice.setMaxRows(10);
    listChoice.setOutputMarkupId(true);
    exportForm.add(listChoice);

    AjaxLink addLink = new AjaxLink<Void>("addElement") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            ModalWindow dialog = findParent(BasePage.class).getDialog();
            dialog.setTitle(getString("Settings.migration.export.entity.add"));
            dialog.setInitialWidth(350);
            dialog.setUseInitialHeight(false);

            AddEntityPanel addEntityPanel = new AddEntityPanel() {

                private static final long serialVersionUID = 1L;

                @Override
                public void onOk(AjaxRequestTarget target) {
                    Iterator<Entity> entities = getEntities();
                    if (!entities.hasNext()) {
                        error(getString("Settings.migration.export.entity.select"));
                        target.add(getFeedbackPanel());
                        return;
                    }
                    while (entities.hasNext()) {
                        Entity entity = entities.next();
                        String path = entity.getPath();
                        path = path.substring(StorageConstants.NEXT_SERVER_ROOT.length() + 1);
                        if (!list.contains(path)) {
                            list.add(path);
                        }
                    }
                    ModalWindow.closeCurrent(target);
                    target.add(listChoice);
                }

            };
            dialog.setContent(new FormPanel<Void>(dialog.getContentId(), addEntityPanel, true) {

                private static final long serialVersionUID = 1L;

                @Override
                protected void onConfigure() {
                    super.onConfigure();
                    setOkButtonValue(getString("add"));
                }

            });
            dialog.show(target);
        }

    };
    addLink.add(new SimpleTooltipBehavior(getString("Settings.migration.export.entity.add")));
    exportForm.add(addLink);

    AjaxSubmitLink removeLink = new AjaxSubmitLink("removeElement", exportForm) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            for (String sel : choiceModel.getObject()) {
                for (Iterator<?> it = list.iterator(); it.hasNext();) {
                    if (sel.equals(it.next())) {
                        it.remove();
                    }
                }
            }
            if (target != null) {
                target.add(listChoice);
            }
        }

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

    };
    removeLink.add(new SimpleTooltipBehavior(getString("Settings.migration.export.entity.remove")));
    exportForm.add(removeLink);

    TextField<String> exportField = new TextField<String>("exportPath",
            new PropertyModel<String>(this, "exportPath"));
    exportField.setLabel(new Model<String>(getString("Settings.migration.export.path")));
    exportForm.add(exportField);

    exportForm.add(new AjaxSubmitLink("export") {

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

            // we do not use TextField validation with setRequired because we have a submit button (remove entity)
            // which must work without validation
            if ((exportPath == null) || "".endsWith(exportPath.trim())) {
                error(getString("Settings.migration.export.path.select"));
                target.add(feedbackPanel);
                return;
            }

            NextServerApplication.setMaintenance(true);

            MigrationObject mo = new MigrationObject();
            List<DataSource> dsList = new ArrayList<DataSource>();
            List<Report> reportList = new ArrayList<Report>();
            List<Chart> chartList = new ArrayList<Chart>();
            List<DashboardState> dashboards = new ArrayList<DashboardState>();
            mo.setDataSources(dsList);
            mo.setReports(reportList);
            mo.setCharts(chartList);
            mo.setDashboards(dashboards);

            FileOutputStream fos = null;
            try {

                if (list.size() == 0) {
                    error(getString("Settings.migration.export.entity.select"));
                } else {

                    for (String pathM : list) {
                        populateLists(pathM, mo);
                    }

                    XStream xstream = new XStream(new DomDriver());
                    SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy_hh_mm");
                    fos = new FileOutputStream(
                            exportPath + File.separator + "migration-" + sdf.format(new Date()) + ".xml");
                    xstream.toXML(mo, fos);

                    info(getString("Settings.migration.export.info"));
                }
            } catch (Throwable t) {
                error(t.getMessage());
            } finally {
                NextServerApplication.setMaintenance(false);
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            target.add(feedbackPanel);

        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }

    });
}

From source file:ro.nextreports.server.web.dashboard.DashboardNavigationPanel.java

License:Apache License

private void addToolbar() {

    ContextImage dashboardImage = new ContextImage("dashboardImage", "images/dashboard_add.png");
    dashboardImage.add(new WiQueryAjaxEventBehavior(MouseEvent.CLICK) {

        private static final long serialVersionUID = 1L;

        @Override//  w w  w .j  a va  2  s. c  o  m
        protected void onEvent(AjaxRequestTarget target) {
            ModalWindow dialog = findParent(BasePage.class).getDialog();
            dialog.setTitle(getString("DashboardStatistics.title"));
            dialog.setInitialWidth(300);
            dialog.setUseInitialHeight(false);
            dialog.setContent(new DashboardStatisticsPanel(dialog.getContentId()));
            dialog.show(target);
        }

        @Override
        public JsStatement statement() {
            return null;
        }

    });
    dashboardImage.add(new SimpleTooltipBehavior(getString("DashboardStatistics.title")));
    add(dashboardImage);

    add(new AjaxLink<Void>("addDashboard") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            ModalWindow dialog = findParent(BasePage.class).getDialog();
            dialog.setTitle(getString("DashboardNavigationPanel.add"));
            dialog.setInitialWidth(350);
            dialog.setUseInitialHeight(false);

            final AddDashboardPanel addDashboardPanel = new AddDashboardPanel(dialog.getContentId()) {

                private static final long serialVersionUID = 1L;

                @Override
                public void onAdd(AjaxRequestTarget target) {
                    ModalWindow.closeCurrent(target);
                    String id;
                    String title = getTitle();
                    Dashboard dashboard = new DefaultDashboard(title, getColumnCount());
                    id = dashboardService.addDashboard(dashboard);

                    SectionContext sectionContext = NextServerSession.get()
                            .getSectionContext(DashboardSection.ID);
                    sectionContext.getData().put(SectionContextConstants.SELECTED_DASHBOARD_ID, id);

                    target.add(DashboardNavigationPanel.this.findParent(DashboardBrowserPanel.class));
                }

                @Override
                public void onCancel(AjaxRequestTarget target) {
                    ModalWindow.closeCurrent(target);
                }

            };
            dialog.setContent(addDashboardPanel);
            dialog.show(target);
        }

    });
}

From source file:ro.nextreports.server.web.dashboard.DashboardPanel.java

License:Apache License

private void addToolbar() {

    toolbarContainer = new WebMarkupContainer("toolbar");
    add(toolbarContainer);/*from   w ww.  j av  a2s  .  c  o  m*/

    IModel<String> toggleImageModel = new LoadableDetachableModel<String>() {

        private static final long serialVersionUID = 1L;

        @Override
        protected String load() {
            String imagePath = "images/left-gray.png";
            Map<String, String> preferences = NextServerSession.get().getPreferences();
            boolean isHidden = !PreferencesHelper.getBoolean("dashboard.navigationToggle", preferences);
            if (isHidden) {
                imagePath = "images/right-gray.png";
            }

            return imagePath;
        }

    };
    final ContextImage toggle = new ContextImage("toggle", toggleImageModel);
    toggle.add(new WiQueryAjaxEventBehavior(MouseEvent.CLICK) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            Map<String, String> preferences = NextServerSession.get().getPreferences();
            boolean toogle = false;
            if (preferences.containsKey("dashboard.navigationToggle")) {
                toogle = Boolean.parseBoolean(preferences.get("dashboard.navigationToggle"));
                toogle = !toogle;
            }

            preferences.put("dashboard.navigationToggle", String.valueOf(toogle));
            NextServerSession.get().setPreferences(preferences);

            DashboardBrowserPanel browserPanel = findParent(DashboardBrowserPanel.class);
            target.add(browserPanel.getDashboardNavigationPanel());
            target.add(toggle);
            target.add(DashboardPanel.this);
        }

        public JsStatement statement() {
            return null;
        }

    });
    IModel<String> toggleTooltipModel = new LoadableDetachableModel<String>() {

        private static final long serialVersionUID = 1L;

        @Override
        protected String load() {
            String tooltip = getString("DashboardPanel.hide");
            Map<String, String> preferences = NextServerSession.get().getPreferences();
            boolean isHidden = !PreferencesHelper.getBoolean("dashboard.navigationToggle", preferences);
            if (isHidden) {
                tooltip = getString("DashboardPanel.show");
            }

            return tooltip;
        }

    };
    toggle.add(new AttributeModifier("title", toggleTooltipModel));
    toolbarContainer.add(toggle);

    //      add(new AjaxLink<Void>("addDashboard") {
    //
    //         private static final long serialVersionUID = 1L;
    //
    //         @Override
    //         public void onClick(AjaxRequestTarget target) {
    //                ModalWindow dialog = findParent(BasePage.class).getDialog();
    //                dialog.setTitle("Add dashboard");
    //                dialog.setInitialWidth(350);
    //                dialog.setUseInitialHeight(false);
    //                
    //                final AddDashboardPanel addDashboardPanel = new AddDashboardPanel(dialog.getContentId()) {
    //
    //               private static final long serialVersionUID = 1L;
    //
    //               @Override
    //                    public void onAdd(AjaxRequestTarget target) {
    //                        ModalWindow.closeCurrent(target);
    //                        String id;
    //                        String title = getTitle();                        
    //                        Dashboard dashboard = new DefaultDashboard(title, getColumnCount());
    //                        id = dashboardService.addOrModifyDashboard(dashboard);
    //
    //                        SectionContext sectionContext = NextServerSession.get().getSectionContext(DashboardSection.ID);
    //                        sectionContext.getData().put(SectionContextConstants.SELECTED_DASHBOARD_ID, id);
    //                        
    //                        target.add(DashboardPanel.this.findParent(DashboardBrowserPanel.class));
    //                    }
    //
    //                    @Override
    //                    public void onCancel(AjaxRequestTarget target) {
    //                        ModalWindow.closeCurrent(target);
    //                    }
    //
    //                };
    //                dialog.setContent(addDashboardPanel);
    //                dialog.show(target);
    //         }
    //         
    //      });

    AjaxLink<Void> refreshLink = new AjaxLink<Void>("refresh") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.add(DashboardPanel.this);
        }

    };
    toolbarContainer.add(refreshLink);

    AjaxLink<Void> addWidgetLink = new AjaxLink<Void>("addWidget") {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(AjaxRequestTarget target) {
            ModalWindow dialog = findParent(BasePage.class).getDialog();
            dialog.setTitle(getString("DashboardPanel.add"));
            dialog.setInitialWidth(350);
            dialog.setUseInitialHeight(false);

            AddWidgetPanel addWidgetPanel = new AddWidgetPanel() {

                private static final long serialVersionUID = 1L;

                @Override
                public void onOk(AjaxRequestTarget target) {
                    if (getEntity() == null) {
                        error(getString("DashboardPanel.select"));
                        target.add(getFeedbackPanel());
                        return;
                    }

                    ModalWindow.closeCurrent(target);

                    Widget widget = null;
                    //!important: first we test for pivot and then for drill-downable
                    if (isPivot()) {
                        PivotWidget pivotWidget = (PivotWidget) widgetFactory
                                .createWidget(new PivotWidgetDescriptor());
                        pivotWidget.setEntity(getEntity());
                        widget = pivotWidget;
                    } else if (isDrillDownable()) {
                        DrillDownWidget drillWidget = (DrillDownWidget) widgetFactory
                                .createWidget(new DrillDownWidgetDescriptor());
                        drillWidget.setEntity(getEntity());
                        widget = drillWidget;
                    } else if (isChart()) {
                        ChartWidget chartWidget = (ChartWidget) widgetFactory
                                .createWidget(new ChartWidgetDescriptor());
                        chartWidget.setEntity(getEntity());
                        widget = chartWidget;
                    } else if (isTable()) {
                        TableWidget tableWidget = (TableWidget) widgetFactory
                                .createWidget(new TableWidgetDescriptor());
                        tableWidget.setEntity(getEntity());
                        widget = tableWidget;
                    } else if (isAlarm()) {
                        AlarmWidget alarmWidget = (AlarmWidget) widgetFactory
                                .createWidget(new AlarmWidgetDescriptor());
                        alarmWidget.setEntity(getEntity());
                        widget = alarmWidget;
                    } else if (isIndicator()) {
                        IndicatorWidget indicatorWidget = (IndicatorWidget) widgetFactory
                                .createWidget(new IndicatorWidgetDescriptor());
                        indicatorWidget.setEntity(getEntity());
                        widget = indicatorWidget;
                    } else if (isDisplay()) {
                        DisplayWidget displayWidget = (DisplayWidget) widgetFactory
                                .createWidget(new DisplayWidgetDescriptor());
                        displayWidget.setEntity(getEntity());
                        widget = displayWidget;
                    }
                    widget.setTitle(getUniqueWidgetTitle(widget.getTitle()));
                    widget.afterCreate(storageService);
                    Dashboard dashboard = getDashboard();
                    try {
                        dashboardService.addWidget(dashboard.getId(), widget);
                    } catch (NotFoundException e) {
                        // never happening
                        throw new RuntimeException(e);
                    }

                    // TODO
                    /*
                    target.add(getLeftColumnPanel());
                    // @todo
                    // if we do not refresh right panel we have a strange bug :                       
                    // move a W widget from left to right, add a widget (to left), move W from right to left (will look like the added widget) 
                    target.add(getRightColumnPanel());
                    */
                    /*
                    for (int i = 0; i < getDashboard().getColumnCount(); i++) {
                       System.out.println(">>> " + i);
                       System.out.println(getColumnPanel(i));
                       target.add(getColumnPanel(i));
                    }
                    */

                    // globalSettingsLink may be disabled
                    //                       target.add(globalSettingsLink);         

                    // need to to do detach (otherwise after we add a widget to current dashboard, added widget does not appear)!
                    // see also DashboardColumnModel
                    DashboardPanel.this.getModel().detach();
                    target.add(DashboardPanel.this);
                }

            };
            dialog.setContent(new FormPanel<Void>(dialog.getContentId(), addWidgetPanel, true) {

                private static final long serialVersionUID = 1L;

                @Override
                protected void onConfigure() {
                    super.onConfigure();
                    setOkButtonValue(getString("add"));
                }

            });
            dialog.show(target);
        }

        @Override
        public boolean isVisible() {
            return hasWritePermission();
        }

    };
    toolbarContainer.add(addWidgetLink);

    globalSettingsLink = new AjaxLink<Void>("globalSettings") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            ModalWindow dialog = findParent(BasePage.class).getDialog();
            dialog.setTitle(getString("DashboardPanel.global"));

            final WidgetRuntimeModel runtimeModel = ChartUtil.getGlobalRuntimeModel(
                    storageService.getSettings(), getDashboard().getId(), reportService, dataSourceService,
                    dashboardService);
            Entity entity = null;
            if (runtimeModel.getParameters().size() > 0) {
                entity = ((EntityWidget) getDashboard().getWidgets().get(0)).getEntity();
            }
            if (getDashboard().getWidgets().size() > 0) {
                final ParameterRuntimePanel paramRuntimePanel = new GeneralWidgetRuntimePanel(
                        "chartRuntimePanel", entity, runtimeModel, true);

                boolean isDynamic = false;
                if (paramRuntimePanel instanceof DynamicParameterRuntimePanel) {
                    if (((DynamicParameterRuntimePanel) paramRuntimePanel).hasDynamicParameter()) {
                        isDynamic = true;
                    }
                }

                if (paramRuntimePanel.hasPalette()) {
                    if (isDynamic) {
                        dialog.setInitialWidth(720);
                    } else {
                        dialog.setInitialWidth(685);
                    }
                } else {
                    if (isDynamic) {
                        dialog.setInitialWidth(445);
                    } else {
                        dialog.setInitialWidth(435);
                    }
                }
                dialog.setUseInitialHeight(false);
                dialog.setContent(new WidgetSettingsPanel(dialog.getContentId(), paramRuntimePanel) {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public void onChange(AjaxRequestTarget target) {
                        changeGlobalSettings(runtimeModel, target);
                    }

                    @Override
                    public void onCancel(AjaxRequestTarget target) {
                        ModalWindow.closeCurrent(target);
                    }

                    @Override
                    public void onReset(AjaxRequestTarget target) {
                        // resetSettings(widget, target);
                    }

                });
            } else {
                dialog.setContent(new Label(dialog.getContentId(), getString("DashboardPanel.empty")));
                dialog.setInitialWidth(300);
                dialog.setInitialHeight(40);
            }
            dialog.show(target);
        }

        @Override
        public boolean isVisible() {
            return hasWritePermission()
                    && (DashboardUtil.getDashboard(DashboardUtil.getSelectedDashboardId(), dashboardService)
                            .getWidgets().size() > 0);
        }

    };
    globalSettingsLink.setOutputMarkupId(true);
    globalSettingsLink.setOutputMarkupPlaceholderTag(true);
    toolbarContainer.add(globalSettingsLink);

    toolbarContainer.add(new AjaxLink<Void>("pdf") {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            target.appendJavaScript(getPdfJavascriptCall());
        }

        // a landscape pdf with the entire visible part of dashboard
        private String getPdfJavascriptCall() {
            StringBuilder sb = new StringBuilder();
            sb.append("var doc = new jsPDF('l', 'mm');");
            //sb.append("var list = $('li[id^=\"widget\"]');");
            //sb.append("pdfSettings.position = 1;");
            sb.append("var list = $('div[class=\"dashboardCapture\"]');");
            sb.append("var pdfSettings = new Object();");
            sb.append("pdfSettings.doc = doc;");
            sb.append("pdfSettings.elements = list;");
            sb.append("pdfSettings.title = \"" + getDashboard().getTitle() + "\";");
            sb.append("pdfSettings.showFooter = true;");
            sb.append("pdfSettings.footerText = \"Generated by NextReports "
                    + new SimpleDateFormat().format(new Date()) + "\";");
            sb.append("capturePdf(pdfSettings);");
            return sb.toString();
        }

    });

}