Example usage for org.apache.wicket.ajax AjaxRequestTarget focusComponent

List of usage examples for org.apache.wicket.ajax AjaxRequestTarget focusComponent

Introduction

In this page you can find the example usage for org.apache.wicket.ajax AjaxRequestTarget focusComponent.

Prototype

void focusComponent(Component component);

Source Link

Document

Sets the focus in the browser to the given component.

Usage

From source file:com.pushinginertia.wicket.core.form.behavior.FormInputSaveDraftBehavior.java

License:Open Source License

@Override
protected void respond(final AjaxRequestTarget target) {
    // prevent focus change
    target.focusComponent(null);

    // fire callback for any changes sent from the client
    final IRequestParameters parameters = RequestCycle.get().getRequest().getRequestParameters();
    final Set<String> parameterNames = parameters.getParameterNames();
    for (final FormComponent<String> component : components) {
        final String id = component.getMarkupId();
        if (parameterNames.contains(id)) {
            final StringValue value = parameters.getParameterValue(id);
            callback.saveDraft(component, value.toString());
        }//  ww w .  j a v  a2s. com
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor.java

License:Open Source License

@SuppressWarnings("nls")
public static void generateResponse(final AjaxRequestTarget target, Page page) {
    WebClientSession webClientSession = WebClientSession.get();
    if (target != null && page instanceof MainPage && webClientSession != null
            && webClientSession.getWebClient() != null
            && webClientSession.getWebClient().getSolution() != null) {
        if (target instanceof CloseableAjaxRequestTarget && ((CloseableAjaxRequestTarget) target).isClosed()) {
            return;
        }//  www  . j  a  va2  s.co m
        // do executed the events for before generating the response.
        webClientSession.getWebClient().executeEvents();

        if (webClientSession.getWebClient() == null || webClientSession.getWebClient().getSolution() == null) {
            // how can web client be null here ?
            return;
        }
        final MainPage mainPage = ((MainPage) page);

        if (mainPage.getPageMap() instanceof ModifiedAccessStackPageMap) {
            // at every request mark the pagemap as dirty so lru eviction really works
            ((ModifiedAccessStackPageMap) mainPage.getPageMap()).flagDirty();
        }

        // If the main form is switched then do a normal redirect.
        if (mainPage.isMainFormSwitched()) {
            mainPage.versionPush();
            RequestCycle.get().setResponsePage(page);
        }

        else {
            page.visitChildren(WebTabPanel.class, new Component.IVisitor<WebTabPanel>() {
                public Object component(WebTabPanel component) {
                    component.initalizeFirstTab();
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });

            mainPage.addWebAnchoringInfoIfNeeded();

            final Set<WebCellBasedView> tableViewsToRender = new HashSet<WebCellBasedView>();
            final List<String> valueChangedIds = new ArrayList<String>();
            final List<String> invalidValueIds = new ArrayList<String>();
            final Map<WebCellBasedView, List<Integer>> tableViewsWithChangedRowIds = new HashMap<WebCellBasedView, List<Integer>>();

            // first, get all invalidValue & valueChanged components
            page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    if (component instanceof IDisplayData && !((IDisplayData) component).isValueValid()) {
                        invalidValueIds.add(component.getMarkupId());
                    }
                    if (((IProviderStylePropertyChanges) component).getStylePropertyChanges()
                            .isValueChanged()) {
                        if (component.getParent().isVisibleInHierarchy()) {
                            // the component will get added to the target & rendered only if it's parent is visible in hierarchy because changed flag is also set (see the visitor below)
                            // so we will only list these components if they are visible otherwise ajax timer could end up sending hundreds of id's that don't actually render every 5 seconds
                            // because the valueChanged flag is cleared only by onRender
                            valueChangedIds.add(component.getMarkupId());
                            if (component instanceof MarkupContainer) {
                                ((MarkupContainer) component).visitChildren(IDisplayData.class,
                                        new IVisitor<Component>() {
                                            public Object component(Component comp) {
                                                // labels/buttons that don't display data are not changed
                                                if (!(comp instanceof ILabel)) {
                                                    valueChangedIds.add(comp.getMarkupId());
                                                }
                                                return CONTINUE_TRAVERSAL;
                                            }
                                        });
                            }
                        }
                    }
                    return CONTINUE_TRAVERSAL;
                }
            });

            // add changed components to target; if a component is changed, the change check won't go deeper in hierarchy
            page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    if (((IProviderStylePropertyChanges) component).getStylePropertyChanges().isChanged()) {
                        if (component.getParent().isVisibleInHierarchy()) {
                            target.addComponent(component);
                            generateDragAttach(component, target.getHeaderResponse());

                            WebForm parentForm = component.findParent(WebForm.class);
                            boolean isDesignMode = parentForm != null && parentForm.isDesignMode();

                            if (!component.isVisible() || (component instanceof WrapperContainer
                                    && !((WrapperContainer) component).getDelegate().isVisible())) {
                                ((IProviderStylePropertyChanges) component).getStylePropertyChanges()
                                        .setRendered();
                                if (isDesignMode) {
                                    target.appendJavascript("Servoy.ClientDesign.hideSelected('"
                                            + component.getMarkupId() + "')");
                                }
                            } else {
                                if (isDesignMode) {
                                    target.appendJavascript("Servoy.ClientDesign.refreshSelected('"
                                            + component.getMarkupId() + "')");
                                }
                                // some components need to perform js layout tasks when their markup is replaced when using anchored layout
                                mainPage.getPageContributor().markComponentForAnchorLayoutIfNeeded(component);
                            }

                            ListItem<IRecordInternal> row = component.findParent(ListItem.class);
                            if (row != null) {
                                WebCellBasedView wcbv = row.findParent(WebCellBasedView.class);
                                if (wcbv != null) {
                                    if (tableViewsWithChangedRowIds.get(wcbv) == null) {
                                        tableViewsWithChangedRowIds.put(wcbv, new ArrayList<Integer>());
                                    }
                                    List<Integer> ids = tableViewsWithChangedRowIds.get(wcbv);
                                    int changedRowIdx = wcbv.indexOf(row);
                                    if (changedRowIdx >= 0 && !ids.contains(changedRowIdx)) {
                                        ids.add(changedRowIdx);
                                    }
                                }
                            }
                        }
                        return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
                    } else if (component instanceof WebCellBasedView)
                        tableViewsToRender.add((WebCellBasedView) component);
                    return component.isVisible() ? IVisitor.CONTINUE_TRAVERSAL
                            : IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
                }
            });

            page.visitChildren(IComponentToRequestAttacher.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    ((IComponentToRequestAttacher) component).attachComponents(target);
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });

            final List<String> visibleEditors = new ArrayList<String>();
            page.visitChildren(WebDataHtmlArea.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    visibleEditors.add(((WebDataHtmlArea) component).getEditorID());
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });
            StringBuffer argument = new StringBuffer();
            for (String id : visibleEditors) {
                argument.append("\"");
                argument.append(id);
                argument.append("\"");
                if (visibleEditors.indexOf(id) != visibleEditors.size() - 1) {
                    argument.append(",");
                }
            }
            target.prependJavascript("Servoy.HTMLEdit.removeInvalidEditors(" + argument + ");");

            String rowSelectionScript, columnResizeScript;
            for (final WebCellBasedView wcbv : tableViewsToRender) {
                if (wcbv.isScrollMode())
                    wcbv.scrollViewPort(target, true);
                wcbv.updateRowSelection(target);
                List<Integer> changedIds = tableViewsWithChangedRowIds.get(wcbv);
                List<Integer> selectedIndexesChanged = wcbv.getIndexToUpdate(false);
                List<Integer> mergedIds = selectedIndexesChanged != null ? selectedIndexesChanged
                        : new ArrayList<Integer>();
                if (changedIds != null) {
                    for (Integer id : changedIds) {
                        if (!mergedIds.contains(id)) {
                            mergedIds.add(id);
                        }
                    }
                }
                rowSelectionScript = wcbv.getRowSelectionScript(mergedIds);
                wcbv.clearSelectionByCellActionFlag();
                if (rowSelectionScript != null)
                    target.appendJavascript(rowSelectionScript);
                columnResizeScript = wcbv.getColumnResizeScript();
                if (columnResizeScript != null)
                    target.appendJavascript(columnResizeScript);
            }

            // double check if the page contributor is changed, because the above IStylePropertyChanges ischanged could have altered it.
            if (mainPage.getPageContributor().getStylePropertyChanges().isChanged()) {
                target.addComponent((Component) mainPage.getPageContributor());
            }
            if (invalidValueIds.size() == 0) {
                target.appendJavascript("setValidationFailed(null);"); //$NON-NLS-1$
            } else {
                target.appendJavascript("setValidationFailed('" + invalidValueIds.get(0) + "');"); //$NON-NLS-1$
            }
            Component comp = mainPage.getAndResetToFocusComponent();
            if (comp != null) {
                if (comp instanceof WebDataHtmlArea) {
                    target.appendJavascript("tinyMCE.activeEditor.focus()");
                } else {
                    target.focusComponent(comp);
                }
            } else if (mainPage.getAndResetMustFocusNull()) {
                // This is needed for example when showing a non-modal dialog in IE7 (or otherwise
                // the new window would be displayed in the background).
                target.focusComponent(null);
            }
            if (valueChangedIds.size() > 0) {
                argument = new StringBuffer();
                for (String id : valueChangedIds) {
                    argument.append("\"");
                    argument.append(id);
                    argument.append("\"");
                    if (valueChangedIds.indexOf(id) != valueChangedIds.size() - 1) {
                        argument.append(",");
                    }
                }
                target.prependJavascript("storeValueAndCursorBeforeUpdate(" + argument + ");");
                target.appendJavascript("restoreValueAndCursorAfterUpdate();");
            }

            //if we have admin info, show it
            String adminInfo = mainPage.getAdminInfo();
            if (adminInfo != null) {
                adminInfo = Utils.stringReplace(adminInfo, "\r", "");
                adminInfo = Utils.stringReplace(adminInfo, "\n", "\\n");
                target.appendJavascript("alert('Servoy admin info : " + adminInfo + "');");
            }

            // If we have a status text, set it.
            String statusText = mainPage.getStatusText();
            if (statusText != null) {
                target.appendJavascript("setStatusText('" + statusText + "');");
            }

            String show = mainPage.getShowUrlScript();
            if (show != null) {
                target.appendJavascript(show);
            }

            mainPage.renderJavascriptChanges(target);

            if (((WebClientInfo) webClientSession.getClientInfo()).getProperties().isBrowserInternetExplorer()
                    && ((WebClientInfo) webClientSession.getClientInfo()).getProperties()
                            .getBrowserVersionMajor() < 9) {
                target.appendJavascript("Servoy.Utils.checkWebFormHeights();");
            }
            try {
                if (isStyleSheetLimitForIE(page.getSession())) {
                    target.appendJavascript("testStyleSheets();");
                }
            } catch (Exception e) {
                Debug.error(e);//cannot retrieve session/clientinfo/properties?
                target.appendJavascript("testStyleSheets();");
            }
        }
    }
}

From source file:name.martingeisse.trading_game.gui.util.AjaxRequestUtil.java

License:Open Source License

/**
 * Focuses a component via Javascript. Does nothing visible
 * but logs an error in non-AJAX requests.
 *
 * @param component the component to focus
 */// w w w.j  a v a2 s .c  om
public static void focus(Component component) {
    AjaxRequestTarget target = getAjaxRequestTarget();
    if (checkTarget(target)) {
        target.focusComponent(component);
    }
}

From source file:org.apache.isis.viewer.wicket.ui.components.widgets.cssmenu.ActionLinkFactoryAbstract.java

License:Apache License

/**
 * Either creates a link for the action be rendered in a {@link ModalWindow}, or (if none can be
 * {@link ActionPromptProvider#getActionPrompt() provided}, or creates a link to 
 * the {@link ActionPromptPage} (ie the {@link PageClassRegistry registered page} for 
 * {@link PageType#ACTION_PROMPT action}s).
 * /*w  w w  .  j av  a2 s.  c o  m*/
 * <p>
 * If the action's {@link ObjectAction#getSemantics() semantics} are {@link ActionSemantics.Of#SAFE safe}, then
 * concurrency checking is disabled; otherwise it is enforced.
 */
protected AbstractLink newLink(final String linkId, final ObjectAdapter objectAdapter,
        final ObjectAction action, final ActionPromptProvider actionPromptProvider) {

    final ActionPrompt actionPrompt = actionPromptProvider.getActionPrompt();
    if (actionPrompt != null) {
        final ActionModel actionModel = ActionModel.create(objectAdapter, action);
        actionModel.setActionPrompt(actionPrompt);
        AjaxLink<Object> link = new AjaxLink<Object>(linkId) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {

                final ActionPanel actionPromptPanel = (ActionPanel) getComponentFactoryRegistry()
                        .createComponent(ComponentType.ACTION_PROMPT, actionPrompt.getContentId(), actionModel);

                actionPrompt.setPanel(actionPromptPanel, target);
                actionPrompt.show(target);

                target.focusComponent(actionPromptPanel);

            }
        };
        link.add(new CssClassAppender("noVeil"));
        return link;

    } else {

        // use the action semantics to determine whether invoking this action will require a concurrency check or not
        // if it's "safe", then we'll just continue without any checking. 
        final ConcurrencyChecking concurrencyChecking = ConcurrencyChecking
                .concurrencyCheckingFor(action.getSemantics());
        final PageParameters pageParameters = ActionModel.createPageParameters(objectAdapter, action,
                concurrencyChecking);
        final Class<? extends Page> pageClass = getPageClassRegistry().getPageClass(PageType.ACTION_PROMPT);
        AbstractLink link = Links.newBookmarkablePageLink(linkId, pageParameters, pageClass);

        // special case handling if this a no-arg action is returning a URL
        if (action.getParameterCount() == 0) {
            addTargetBlankIfActionReturnsUrl(link, action);
        }

        return link;
    }
}

From source file:org.apache.isis.viewer.wicket.ui.components.widgets.zclip.ZeroClipboardPanel.java

License:Apache License

private AjaxLink<ObjectAdapter> newSimpleClipboardLink(String linkId) {
    return new AjaxLink<ObjectAdapter>(linkId) {
        private static final long serialVersionUID = 1L;

        @Override//from   ww  w.  j a v  a  2  s.c o m
        public void onClick(AjaxRequestTarget target) {

            String contentId = simpleClipboardModalWindow.getContentId();
            SimpleClipboardModalWindowPanel panel = new SimpleClipboardModalWindowPanel(contentId);
            SimpleClipboardModalWindowForm form = new SimpleClipboardModalWindowForm("form");

            final TextField<String> textField = new TextField<String>("textField",
                    new LoadableDetachableModel<String>() {
                        private static final long serialVersionUID = 1L;

                        @SuppressWarnings({ "rawtypes", "unchecked" })
                        @Override
                        protected String load() {

                            final Class pageClass = ZeroClipboardPanel.this.getPage().getPageClass();

                            final EntityModel entityModel = ZeroClipboardPanel.this.getModel();
                            final PageParameters pageParameters = entityModel.getPageParameters();

                            final CharSequence urlFor = getRequestCycle().urlFor(pageClass, pageParameters);
                            return getRequestCycle().getUrlRenderer().renderFullUrl(Url.parse(urlFor));
                        }
                    });
            panel.add(form);
            form.add(textField);

            textField.setOutputMarkupId(true);

            CharSequence modalId = Strings2.escapeMarkupId(simpleClipboardModalWindow.getMarkupId());
            CharSequence textFieldId = Strings2.escapeMarkupId(textField.getMarkupId());
            target.appendJavaScript(
                    String.format("$('#%s').one('shown.bs.modal', function(){Wicket.$('%s').select();});",
                            modalId, textFieldId));

            simpleClipboardModalWindow.setPanel(panel, target);
            simpleClipboardModalWindow.showPrompt(target);

            target.focusComponent(textField);
        }
    };
}

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

License:Apache License

@Override
public FieldPanel<SearchClause> settingsDependingComponents() {
    final SearchClause searchClause = this.clause.getObject();

    final WebMarkupContainer operatorContainer = new WebMarkupContainer("operatorContainer");
    operatorContainer.setOutputMarkupId(true);
    field.add(operatorContainer);//from  w w w. ja v  a 2s.c  o  m

    final BootstrapToggleConfig config = new BootstrapToggleConfig()
            .withOnStyle(BootstrapToggleConfig.Style.info).withOffStyle(BootstrapToggleConfig.Style.warning)
            .withSize(BootstrapToggleConfig.Size.mini);

    operatorFragment.add(new BootstrapToggle("operator", new Model<Boolean>() {

        private static final long serialVersionUID = -7157802546272668001L;

        @Override
        public Boolean getObject() {
            return searchClause.getOperator() == Operator.AND;
        }

        @Override
        public void setObject(final Boolean object) {
            searchClause.setOperator(object ? Operator.AND : Operator.OR);
        }
    }, config) {

        private static final long serialVersionUID = 2969634208049189343L;

        @Override
        protected IModel<String> getOffLabel() {
            return Model.of("OR");
        }

        @Override
        protected IModel<String> getOnLabel() {
            return Model.of("AND");
        }

        @Override
        protected CheckBox newCheckBox(final String id, final IModel<Boolean> model) {
            final CheckBox checkBox = super.newCheckBox(id, model);
            checkBox.add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

                private static final long serialVersionUID = 1L;

                @Override
                protected void onUpdate(final AjaxRequestTarget target) {
                }
            });
            return checkBox;
        }
    }.setOutputMarkupPlaceholderTag(true));

    if (getIndex() > 0) {
        operatorContainer.add(operatorFragment);
    } else {
        operatorContainer.add(searchButtonFragment);
    }

    final AjaxDropDownChoicePanel<String> property = new AjaxDropDownChoicePanel<>("property", "property",
            new PropertyModel<String>(searchClause, "property"));
    property.hideLabel().setRequired(required).setOutputMarkupId(true);
    property.setChoices(properties);
    property.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
        }
    });
    field.add(property);

    final AjaxDropDownChoicePanel<SearchClause.Comparator> comparator = new AjaxDropDownChoicePanel<>(
            "comparator", "comparator", new PropertyModel<SearchClause.Comparator>(searchClause, "comparator"));
    comparator.setChoices(comparators);
    comparator.setNullValid(false).hideLabel().setOutputMarkupId(true);
    comparator.setRequired(required);
    comparator.setChoiceRenderer(getComparatorRender(field.getModel()));
    field.add(comparator);

    final AjaxTextFieldPanel value = new AjaxTextFieldPanel("value", "value",
            new PropertyModel<String>(searchClause, "value"), false);
    value.hideLabel().setOutputMarkupId(true);
    field.add(value);

    value.getField().add(AttributeModifier.replace("onkeydown",
            Model.of("if(event.keyCode == 13) {event.preventDefault();}")));

    value.getField().add(new IndicatorAjaxEventBehavior("onkeydown") {

        private static final long serialVersionUID = -7133385027739964990L;

        @Override
        protected void onEvent(final AjaxRequestTarget target) {
            target.focusComponent(null);
            value.getField().inputChanged();
            value.getField().validate();
            if (value.getField().isValid()) {
                value.getField().valid();
                value.getField().updateModel();
            }
        }

        @Override
        protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
            super.updateAjaxAttributes(attributes);

            attributes.getAjaxCallListeners().add(new AjaxCallListener() {

                private static final long serialVersionUID = 7160235486520935153L;

                @Override
                public CharSequence getPrecondition(final Component component) {
                    return "if (Wicket.Event.keyCode(attrs.event)  == 13) { return true; } else { return false; }";
                }
            });
        }
    });

    final AjaxDropDownChoicePanel<SearchClause.Type> type = new AjaxDropDownChoicePanel<>("type", "type",
            new PropertyModel<SearchClause.Type>(searchClause, "type"));
    type.setChoices(types).hideLabel().setRequired(required).setOutputMarkupId(true);
    type.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            final SearchClause searchClause = new SearchClause();
            searchClause.setType(Type.valueOf(type.getDefaultModelObjectAsString()));
            SearchClausePanel.this.clause.setObject(searchClause);

            setFieldAccess(searchClause.getType(), property, comparator, value);
            target.add(property);
            target.add(comparator);
            target.add(value);
        }
    });
    field.add(type);

    comparator.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            if (type.getModelObject() == SearchClause.Type.ATTRIBUTE
                    || type.getModelObject() == SearchClause.Type.RELATIONSHIP) {
                if (comparator.getModelObject() == SearchClause.Comparator.IS_NULL
                        || comparator.getModelObject() == SearchClause.Comparator.IS_NOT_NULL) {
                    value.setModelObject(StringUtils.EMPTY);
                    value.setEnabled(false);
                } else {
                    value.setEnabled(true);
                }
                target.add(value);
            }

            if (type.getModelObject() == SearchClause.Type.RELATIONSHIP) {
                if (comparator.getModelObject() == SearchClause.Comparator.EQUALS
                        || comparator.getModelObject() == SearchClause.Comparator.NOT_EQUALS) {
                    property.setEnabled(false);
                } else {
                    property.setEnabled(true);
                }

                final SearchClause searchClause = new SearchClause();
                searchClause.setType(Type.valueOf(type.getDefaultModelObjectAsString()));
                searchClause.setComparator(comparator.getModelObject());
                SearchClausePanel.this.clause.setObject(searchClause);

                target.add(property);
            }
        }
    });

    setFieldAccess(searchClause.getType(), property, comparator, value);

    return this;
}

From source file:org.apache.syncope.client.console.wizards.resources.ResourceProvisionPanel.java

License:Apache License

public ResourceProvisionPanel(final BaseModal<Serializable> modal, final ResourceTO resourceTO,
        final PageReference pageRef) {

    super(modal, pageRef);
    this.resourceTO = resourceTO;

    baseModel = Model.of(resourceTO.getOrgUnit() == null ? new OrgUnitTO() : resourceTO.getOrgUnit());

    setOutputMarkupId(true);/*from  www.j  a v  a2  s. c  o  m*/

    // ----------------------------------------------------------------------
    // Realms provisioning
    // ----------------------------------------------------------------------
    aboutRealmProvison = new WebMarkupContainer("aboutRealmProvison");
    aboutRealmProvison.setOutputMarkupPlaceholderTag(true);
    add(aboutRealmProvison);

    boolean realmProvisionEnabled = resourceTO.getOrgUnit() != null;

    final AjaxCheckBoxPanel enableRealmsProvision = new AjaxCheckBoxPanel("enableRealmsProvision",
            "enableRealmsProvision", Model.of(realmProvisionEnabled), false);
    aboutRealmProvison.add(enableRealmsProvision);
    enableRealmsProvision.setIndex(1).setTitle(getString("enableRealmsProvision.title"));

    final WebMarkupContainer realmsProvisionContainer = new WebMarkupContainer("realmsProvisionContainer");
    realmsProvisionContainer.setOutputMarkupPlaceholderTag(true);
    realmsProvisionContainer.setEnabled(realmProvisionEnabled).setVisible(realmProvisionEnabled);
    aboutRealmProvison.add(realmsProvisionContainer);

    final AjaxTextFieldPanel objectClass = new AjaxTextFieldPanel("objectClass", getString("objectClass"),
            new PropertyModel<String>(baseModel.getObject(), "objectClass"), false);
    realmsProvisionContainer.add(objectClass.addRequiredLabel());

    final AjaxTextFieldPanel extAttrName = new AjaxTextFieldPanel("extAttrName", getString("extAttrName"),
            new PropertyModel<String>(baseModel.getObject(), "extAttrName"), false);
    if (resourceTO.getOrgUnit() != null) {
        extAttrName.setChoices(connectorRestClient.getExtAttrNames(resourceTO.getOrgUnit().getObjectClass(),
                resourceTO.getConnector(), resourceTO.getConfOverride()));
    }
    realmsProvisionContainer.add(extAttrName.addRequiredLabel());

    objectClass.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_BLUR) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            extAttrName.setChoices(connectorRestClient.getExtAttrNames(objectClass.getModelObject(),
                    resourceTO.getConnector(), resourceTO.getConfOverride()));
            target.focusComponent(extAttrName);
        }
    });

    final AjaxTextFieldPanel connObjectLink = new AjaxTextFieldPanel("connObjectLink",
            new ResourceModel("connObjectLink", "connObjectLink").getObject(),
            new PropertyModel<String>(baseModel.getObject(), "connObjectLink"), false);
    realmsProvisionContainer.add(connObjectLink.addRequiredLabel());

    enableRealmsProvision.getField().add(new IndicatorAjaxFormComponentUpdatingBehavior(Constants.ON_CHANGE) {

        private static final long serialVersionUID = -1107858522700306810L;

        @Override
        protected void onUpdate(final AjaxRequestTarget target) {
            boolean realmProvisionEnabled = enableRealmsProvision.getModelObject();
            realmsProvisionContainer.setEnabled(realmProvisionEnabled).setVisible(realmProvisionEnabled);
            target.add(realmsProvisionContainer);

            if (realmProvisionEnabled) {
                resourceTO.setOrgUnit(baseModel.getObject());
            } else {
                resourceTO.setOrgUnit(null);
            }

        }
    });
    // ----------------------------------------------------------------------

    final ProvisionWizardBuilder wizard = new ProvisionWizardBuilder(resourceTO, pageRef);

    final ListViewPanel.Builder<ProvisionTO> builder = new ListViewPanel.Builder<ProvisionTO>(ProvisionTO.class,
            pageRef) {

        private static final long serialVersionUID = 4907732721283972943L;

        @Override
        protected ProvisionTO getActualItem(final ProvisionTO item, final List<ProvisionTO> list) {
            return item == null ? null : IteratorUtils.find(list.iterator(), new Predicate<ProvisionTO>() {

                @Override
                public boolean evaluate(final ProvisionTO in) {
                    return ((item.getKey() == null && in.getKey() == null)
                            || (in.getKey() != null && in.getKey().equals(item.getKey())))
                            && ((item.getAnyType() == null && in.getAnyType() == null)
                                    || (in.getAnyType() != null && in.getAnyType().equals(item.getAnyType())));
                }
            });
        }

        @Override
        protected void customActionOnCancelCallback(final AjaxRequestTarget target) {
            ResourceProvisionPanel.this.aboutRealmProvison.setVisible(true);
            target.add(ResourceProvisionPanel.this.aboutRealmProvison);
        }

        @Override
        protected void customActionOnFinishCallback(final AjaxRequestTarget target) {
            ResourceProvisionPanel.this.aboutRealmProvison.setVisible(true);
            target.add(ResourceProvisionPanel.this.aboutRealmProvison);
        }
    };

    builder.setItems(resourceTO.getProvisions());
    builder.includes("anyType", "objectClass", "auxClasses");
    builder.setReuseItem(false);

    builder.addAction(new ActionLink<ProvisionTO>() {

        private static final long serialVersionUID = -3722207913631435504L;

        @Override
        public void onClick(final AjaxRequestTarget target, final ProvisionTO provisionTO) {
            send(ResourceProvisionPanel.this, Broadcast.DEPTH,
                    new AjaxWizard.NewItemActionEvent<>(provisionTO, 2, target)
                            .setResourceModel(new StringResourceModel("inner.provision.mapping",
                                    ResourceProvisionPanel.this, Model.of(provisionTO))));
        }
    }, ActionLink.ActionType.MAPPING, StandardEntitlement.RESOURCE_UPDATE)
            .addAction(new ActionLink<ProvisionTO>() {

                private static final long serialVersionUID = -7780999687733432439L;

                @Override
                public void onClick(final AjaxRequestTarget target, final ProvisionTO provisionTO) {
                    try {
                        SyncopeConsoleSession.get().getService(ResourceService.class)
                                .setLatestSyncToken(resourceTO.getKey(), provisionTO.getAnyType());
                        SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
                    } catch (Exception e) {
                        LOG.error("While setting latest sync token for {}/{}", resourceTO.getKey(),
                                provisionTO.getAnyType(), e);
                        SyncopeConsoleSession.get().error(
                                StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage());
                    }
                    ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
                }
            }, ActionLink.ActionType.SET_LATEST_SYNC_TOKEN, StandardEntitlement.RESOURCE_UPDATE)
            .addAction(new ActionLink<ProvisionTO>() {

                private static final long serialVersionUID = -7780999687733432439L;

                @Override
                public void onClick(final AjaxRequestTarget target, final ProvisionTO provisionTO) {
                    try {
                        SyncopeConsoleSession.get().getService(ResourceService.class)
                                .removeSyncToken(resourceTO.getKey(), provisionTO.getAnyType());
                        SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
                    } catch (Exception e) {
                        LOG.error("While removing sync token for {}/{}", resourceTO.getKey(),
                                provisionTO.getAnyType(), e);
                        SyncopeConsoleSession.get().error(
                                StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage());
                    }
                    ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
                }
            }, ActionLink.ActionType.REMOVE_SYNC_TOKEN, StandardEntitlement.RESOURCE_UPDATE)
            .addAction(new ActionLink<ProvisionTO>() {

                private static final long serialVersionUID = -3722207913631435534L;

                @Override
                public void onClick(final AjaxRequestTarget target, final ProvisionTO provisionTO) {
                    final ProvisionTO clone = SerializationUtils.clone(provisionTO);
                    clone.setKey(null);
                    clone.setAnyType(null);
                    clone.setObjectClass(null);
                    send(ResourceProvisionPanel.this, Broadcast.DEPTH,
                            new AjaxWizard.NewItemActionEvent<>(clone, target)
                                    .setResourceModel(new StringResourceModel("inner.provision.clone",
                                            ResourceProvisionPanel.this, Model.of(provisionTO))));
                }
            }, ActionLink.ActionType.CLONE, StandardEntitlement.RESOURCE_CREATE)
            .addAction(new ActionLink<ProvisionTO>() {

                private static final long serialVersionUID = -3722207913631435544L;

                @Override
                public void onClick(final AjaxRequestTarget target, final ProvisionTO provisionTO) {
                    resourceTO.getProvisions().remove(provisionTO);
                    send(ResourceProvisionPanel.this, Broadcast.DEPTH, new ListViewReload<>(target));
                }
            }, ActionLink.ActionType.DELETE, StandardEntitlement.RESOURCE_DELETE);

    builder.addNewItemPanelBuilder(wizard);

    final WizardMgtPanel<ProvisionTO> list = builder.build("provision");
    add(list);
}

From source file:org.artifactory.common.wicket.panel.editor.TextEditorPanel.java

License:Open Source License

/**
 * Put the focus on the {@link TextArea} and place the caret inside
 *///from   w  ww  .j  a v  a2  s .co  m
public void focus() {
    AjaxRequestTarget target = AjaxRequestTarget.get();
    if (target != null) {
        target.focusComponent(editorTextArea);
    }
}

From source file:org.bosik.diacomp.web.frontend.wicket.components.mealeditor.picker.food.FoodPicker.java

License:Open Source License

public void focus(AjaxRequestTarget target) {
    target.focusComponent(field);
}

From source file:org.bosik.diacomp.web.frontend.wicket.components.mealeditor.picker.foodMassed.inserter.FoodMassedInserter.java

License:Open Source License

@Override
protected void onInitialize() {
    super.onInitialize();

    FoodMassedPicker picker = new FoodMassedPicker("picker") {
        private static final long serialVersionUID = -5896695927537265374L;

        @Override/*from   w w w  .ja v a2s .  com*/
        public void onFoodChanged(AjaxRequestTarget target, IModel<Food> food) {
            target.focusComponent(fieldMass);
            target.add(fieldMass);
        }

        @Override
        public void onMassChanged(AjaxRequestTarget target, IModel<Double> mass) {
            // call the event

            onSelected(target, getModel());

            // proceed the focus and stuff

            setModelObject(new FoodMassed());

            fieldFood.clear();
            fieldMass.clearInput();
            fieldFood.focus(target);
            target.add(fieldFood, fieldMass);
        }
    };
    add(picker);
}