@Override protected void onConfigure() { super.onConfigure(); // set all components visible Components.show(help, label, feedback); // clear feedback message and current state stateClassName.setObject(""); feedback.setDefaultModelObject(""); final List<FormComponent<?>> formComponents = findFormComponents(); for (final FormComponent<?> fc : formComponents) { final FeedbackMessages messages = fc.getFeedbackMessages(); if (!messages.isEmpty()) { final FeedbackMessage worstMessage = getWorstMessage(messages); worstMessage.markRendered(); stateClassName.setObject(toClassName(worstMessage)); feedback.setDefaultModelObject(worstMessage.getMessage()); break; // render worst message of first found child component with feedback message } } Components.hideIfModelIsEmpty(help); Components.hideIfModelIsEmpty(label); Components.hideIfModelIsEmpty(feedback); }
public static void show(Component... components) { if (components != null) { for (Component component : components) { component.setVisible(true); } } }
/** * Search the child's markup in the header section of the markup * * @param container * @param child * @return Null, if not found */ public IMarkupFragment findMarkupInAssociatedFileHeader( final MarkupContainer container, final Component child) { // Get the associated markup IMarkupFragment markup = container.getAssociatedMarkup(); IMarkupFragment childMarkup = null; // MarkupStream is good at searching markup MarkupStream stream = new MarkupStream(markup); while (stream.skipUntil(ComponentTag.class) && (childMarkup == null)) { ComponentTag tag = stream.getTag(); if (TagUtils.isWicketHeadTag(tag)) { if (tag.getMarkupClass() == null) { // find() can still fail an return null => continue the search childMarkup = stream.getMarkupFragment().find(child.getId()); } } else if (TagUtils.isHeadTag(tag)) { // find() can still fail an return null => continue the search childMarkup = stream.getMarkupFragment().find(child.getId()); } // Must be a direct child. We are not interested in grand children if (tag.isOpen() && !tag.hasNoCloseTag()) { stream.skipToMatchingCloseTag(tag); } stream.next(); } return childMarkup; }
/** * Calls {@link Component#setResponsePage(Page)}. If the responseItem is an instance of a Page * then setResponse for this Page is called otherwise setResponse is called via {@link * Component#getPage()}. * * @param component * @param responseItem Page or Component. */ public static void setResponsePage(final Component component, final Component responseItem) { if (responseItem instanceof Page) { component.setResponsePage((Page) responseItem); } else { component.setResponsePage(responseItem.getPage()); } }
@Override public void onComponentTag(final Component component, final ComponentTag tag) { String expr = tag.getAttributes().getString(wicketMessageAttrName); if (!Strings.isEmpty(expr)) { expr = expr.trim(); String[] attrsAndKeys = Strings.split(expr, ','); for (String attrAndKey : attrsAndKeys) { int colon = attrAndKey.lastIndexOf(":"); // make sure the attribute-key pair is valid if (attrAndKey.length() < 3 || colon < 1 || colon > attrAndKey.length() - 2) { throw new WicketRuntimeException( "wicket:message attribute contains an invalid value [[" + expr + "]], must be of form (attr:key)+"); } String attr = attrAndKey.substring(0, colon); String key = attrAndKey.substring(colon + 1); // we need to call the proper getString() method based on // whether or not we have a default value final String value; if (tag.getAttributes().containsKey(attr)) { value = component.getString(key, null, tag.getAttributes().getString(attr)); } else { value = component.getString(key); } tag.put(attr, value); } } }
/** @see org.apache.wicket.behavior.AbstractBehavior#onRendered(org.apache.wicket.Component) */ public void onRendered(Component component) { super.onRendered(component); // Append the span and img icon right after the rendering of the // component. Not as pretty as working with a panel etc, but works // for behaviors and is more efficient Response response = component.getResponse(); response.write("\n<span> <img style=\""); response.write(getIconStyle()); response.write("\" id=\""); response.write(getIconId()); response.write("\" src=\""); CharSequence iconUrl = getIconUrl(); // displayCalendar(document.forms[0].theDate,'yyyy/mm/dd',this) response.write(Strings.escapeMarkup(iconUrl != null ? iconUrl.toString() : "")); response.write("\" onclick=\"displayCalendar(document.getElementById('"); response.write(component.getMarkupId()); response.write("'),'"); String datePattern = getDatePattern().replaceAll("mm", "ii").toLowerCase(); datePattern = datePattern.replace('s', '0'); // (mili)seconds are not supported response.write(datePattern); if (datePattern.indexOf("h") == -1) { response.write("',this)\""); } else { response.write("',this,true)\""); } response.write(" /></span>"); }
private MarkupContainer findLowestSecureContainer(Component component) { final MarkupContainer[] lowestSecureParent = new MarkupContainer[1]; component.visitParents( MarkupContainer.class, new IVisitor<Component>() { public Object component(Component component) { if (component instanceof ISecureComponent) { lowestSecureParent[0] = (MarkupContainer) component; return IVisitor.STOP_TRAVERSAL; } return null; } }); if (null == lowestSecureParent[0]) { try { lowestSecureParent[0] = component.getPage(); } catch (IllegalStateException e) { throw new SecurityException( this.getClass() + ": Unable to create alias for component: " + component, e); } } MarkupContainer markupContainer = lowestSecureParent[0]; return markupContainer; }
/** * Renders head for embedded component, i.e. those who are not added directly to this container * but have the markup inside it. * * @param container The HtmlHeaderContainer */ private void renderHeadForInnerSiblings(HtmlHeaderContainer container) { MarkupStream stream = new MarkupStream(getMarkup()); while (stream.hasMore()) { MarkupElement childOpenTag = stream.nextOpenTag(); if ((childOpenTag instanceof ComponentTag) && !stream.atCloseTag()) { // Get element as tag final ComponentTag tag = (ComponentTag) childOpenTag; // Get component id final String id = tag.getId(); Component component = null; if (get(id) == null) { component = ComponentResolvers.resolveByComponentHierarchy(this, stream, tag); } if (component != null) { component.internalRenderHead(container); } // consider just direct children stream.skipToMatchingCloseTag(tag); } } }
public static void hideIfModelIsEmpty(Component component) { if (component != null && (component.getDefaultModel() == null || component.getDefaultModelObject() == null || Strings.isNullOrEmpty(component.getDefaultModelObjectAsString()))) { component.setVisible(false); } }
private static void replace(AjaxRequestTarget target, Component component) { component.add(new DisplayNoneBehavior()); target.prependJavaScript( "notify|jQuery('#" + component.getMarkupId() + "').slideUp(1000, notify);"); target.add(component); target.appendJavaScript("jQuery('#" + component.getMarkupId() + "').slideDown(1000);"); }
@Override public void onComponentTag(Component component, ComponentTag tag) { super.onComponentTag(component, tag); IValueMap attributes = tag.getAttributes(); attributes.put("data-header-selector", "#" + header.getMarkupId()); attributes.put("data-footer-selector", "#" + footer.getMarkupId()); }
@Override public void bind(final Component component) { super.bind(component); component.setOutputMarkupId(true); component.add(AttributeModifier.replace("rel", createRelAttribute())); component.add(AttributeModifier.replace("title", label)); }
@Test public void selectNewClassInDropDown_shouldRenderNewEditorPanelThroughAjax() { selectEventType(1); fieldList = (RepeatingView) tester.getComponentFromLastRenderedPage("form:fieldContainer:fields"); assertThat(fieldList.size(), is(2)); Component attributeName = fieldList.get("1:row:name"); assertThat(attributeName.getDefaultModelObjectAsString(), is("name")); }
private static void applyCssVisibility(final Component component, final boolean visible) { final AttributeModifier modifier = visible ? new AttributeModifier( "class", String.valueOf(component.getMarkupAttributes().get("class")) .replaceFirst(INVISIBLE_CLASS, "")) : new AttributeAppender("class", " " + INVISIBLE_CLASS); component.add(modifier); }
@Override protected final void respond(AjaxRequestTarget target) { Request request = RequestCycle.get().getRequest(); String newContent = request.getRequestParameters().getParameterValue(PARAM_HTMLCONT).toString(); newContent = onSave(target, newContent); Component component = getComponent(); IModel defaultModel = component.getDefaultModel(); defaultModel.setObject(newContent); target.add(component); }
@Override public final void focusComponent(Component component) { if (component != null && component.getOutputMarkupId() == false) { throw new IllegalArgumentException( "cannot update component that does not have setOutputMarkupId property set to true. Component: " + component.toString()); } final String id = component != null ? ("'" + component.getMarkupId() + "'") : "null"; appendJavaScript("Wicket.Focus.setFocusOnId(" + id + ");"); }
@Test public void testTimestamp() { login("sysadmin", "sysadmin"); Date now = new Date(); tester.startPage(HomePage.class); tester.assertComponent("timestamp", Label.class); Component timestampLabel = tester.getComponentFromLastRenderedPage("timestamp"); String timestamp = (String) timestampLabel.getDefaultModelObject(); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); assertEquals(timestamp, dateFormat.format(now)); }
/** {@inheritDoc} */ @Override public void selectAllVisibleItems() { WebMarkupContainer body = (WebMarkupContainer) get("form:bodyContainer:body:row"); if (body != null) { for (Component component : body) { IModel<T> model = (IModel<T>) component.getDefaultModel(); selectItem(model, true); } } markAllItemsDirty(); }
private static MarkupException createMarkupException( Component component, ComponentTag tag, Set<? extends String> tagNames) { String msg = String.format( "Component [%s] (path = [%s]) must be applied to a tag of type [%s], not: %s", component.getId(), component.getPath(), Joiner.on(',').join(tagNames), tag.toUserDebugString()); throw new MarkupException(component.getMarkup().getMarkupResourceStream(), msg); }
/** * Constructor that is invoked when page is invoked without a session. * * @param parameters Page parameters */ public TestHomePage() { Component component = componentFactory.createComponent("component"); if (component instanceof Page) setResponsePage((Page) component); else { if (!"component".equals(component.getId())) throw new IllegalArgumentException( "Component factory was asked to produce a componet with " + "id 'component' but returned one with id '" + component.getId()); add(component); } }
/** * Uses "jiraSupportTooltipImage" as component id. * * @param parent only needed for localization * @param id * @return IconPanel which is invisible if JIRA isn't configured. */ public static IconPanel getJIRASupportTooltipIcon(final Component parent, final String id) { final IconPanel icon = new IconPanel( id, IconType.JIRA_SUPPORT, Model.of(parent.getString("tooltip.jiraSupport.field.title")), Model.of(parent.getString("tooltip.jiraSupport.field.content"))); if (isJIRAConfigured() == false) { icon.setVisible(false); } return icon; }
private void addElements(Collection<Component> components, StringBuffer buffer) { if (components.size() > 0) { buffer.append(",\n\telements : \""); Iterator<Component> iterator = components.iterator(); while (iterator.hasNext()) { Component component = iterator.next(); buffer.append(component.getMarkupId()); if (iterator.hasNext()) buffer.append(", "); } buffer.append("\""); } else LOG.warn("tinymce is set to \"exact\" mode but there are no components attached"); }
@Override protected void onPostProcessTarget(AjaxRequestTarget target) { super.onPostProcessTarget(target); Component component = getComponent(); status.refresh(); if (status.getState() != State.RUNNING) { stop(target); getComponent().remove(this); } switch (status.getState()) { case RUNNING: component.info( String.format( "A workflow is being transformed (resources generated: %d)...", status.getAdded().size())); break; case DONE: component.success(String.format("The workflow has been transformed.")); component.send( component.getPage(), Broadcast.BREADTH, new WorkflowTransformedEvent(target)); break; default: component.error(String.format("%s: %s", status.getState(), status.getReason())); } component.send(component.getPage(), Broadcast.BREADTH, new FeedbackEvent(target)); }
/** * Gets the date pattern to use for putting selected values in the coupled component. If you * override this method to support components that would otherwise not be supported, you should * override {@link #checkComponentProvidesDateFormat(Component)} and let it return normally. * * @return The date pattern */ protected String getDatePattern() { if (component instanceof ITextFormatProvider) { return ((ITextFormatProvider) component).getTextFormat(); } else { // cast from hell, but we checked before whether we could IConverter converter = component.getConverter(DateTime.class); if (converter == null) { converter = component.getConverter(Date.class); } return ((SimpleDateFormat) ((DateConverter) converter).getDateFormat(component.getLocale())) .toPattern(); } }
public EditableSettingsModalPanel(final DownloadModalSettings settings) { contentTextArea = new TextArea<String>("content", Model.<String>of(settings.getContent())); contentTextArea.setOutputMarkupId(true); FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager.addonByType(FilteredResourcesWebAddon.class); String saveToFileName = settings.getSaveToFileName(); form.add( filteredResourcesWebAddon.getSettingsProvisioningBorder( "settingsProvisioning", form, contentTextArea, saveToFileName)); final AjaxSettingsDownloadBehavior ajaxSettingsDownloadBehavior = new AjaxSettingsDownloadBehavior(saveToFileName) { @Override protected StringResourceStream getResourceStream() { FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager.addonByType(FilteredResourcesWebAddon.class); try { String filtered = filteredResourcesWebAddon.filterResource( null, (Properties) InfoFactoryHolder.get().createProperties(), new StringReader(contentTextArea.getModelObject())); return new StringResourceStream(filtered, settings.getSettingsMimeType()); } catch (Exception e) { log.error("Unable to filter settings: " + e.getMessage()); return new StringResourceStream( contentTextArea.getModelObject(), settings.getSettingsMimeType()); } } }; form.add(ajaxSettingsDownloadBehavior); Component exportLink = new TitledAjaxSubmitLink("export", settings.getDownloadButtonTitle(), form) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { ajaxSettingsDownloadBehavior.initiate(target); } }; exportLink.add(new CssClass(new DefaultButtonStyleModel(exportLink))); add(exportLink); setWidth(700); add(new ModalCloseLink("cancel", "Cancel")); addContentToBorder(); }
/** * @see * org.apache.wicket.markup.resolver.IComponentResolver#resolve(org.apache.wicket.MarkupContainer, * org.apache.wicket.markup.MarkupStream, org.apache.wicket.markup.ComponentTag) */ @Override public Component resolve(MarkupContainer container, MarkupStream markupStream, ComponentTag tag) { Component resolvedComponent = getParent().get(tag.getId()); if (resolvedComponent != null && (getPage().wasRendered(resolvedComponent) || resolvedComponent.isAuto())) { /* * Means that parent container has an associated homonymous tag to this grandchildren * tag in markup. The parent container wants render it and it should be not resolved to * their grandchildren. */ return null; } return resolvedComponent; }
public FormSignIn( final String id, final IModel<LoginToken> userLoginModel, final Component dedicatedLoginPanelComponent) { super(id, userLoginModel); final Subject subject = SecurityUtils.getSubject(); if (subject.isRemembered()) { userLoginModel.getObject().setUsername((String) subject.getPrincipal()); userLoginModel.getObject().setRememberMe(true); } setOutputMarkupId(true); add(new TextField<String>("userName", new PropertyModel<>(userLoginModel, "username"))); add(new PasswordTextField("password", new PropertyModel<>(userLoginModel, "password"))); add(new CheckBox("rememberMe", new PropertyModel<>(userLoginModel, "rememberMe"))); final LoginButton ldapLoginBtn = new LoginButton("login", userLoginModel, tenant.getTenantId()) { @Override protected void onLoginSuccess(AjaxRequestTarget target, String personId) { log.debug( "LoginButton has logged in '{}', redirecting to original page...", personId); ((SoluvasWebSession) getSession()).postLoginSuccess(); } }; add(ldapLoginBtn); final FacebookLoginLink facebookLoginLink = new FacebookLoginLink("btnLoginWithFb", facebookRecipientPage); add(facebookLoginLink); final TwitterLoginLink twitterLoginLink = new TwitterLoginLink("btnLoginWithTwitter", twitterRecipientPage); add(twitterLoginLink); // TODO: enable Google when it's actually working with Google accounts, not Google+ // final GoogleLoginLink googleLoginLink = new GoogleLoginLink("btnLoginWithGoogle"); // add(googleLoginLink); final Component googleLoginLink = new WebMarkupContainer("btnLoginWithGoogle").setVisible(false); add(googleLoginLink); final WebMarkupContainer socialLoginLabel = new WebMarkupContainer("socialLoginLabel"); socialLoginLabel.setVisible( facebookLoginLink.isVisible() || twitterLoginLink.isVisible() || googleLoginLink.isVisible()); add(socialLoginLabel); setDefaultButton(ldapLoginBtn); }
@Override public void onBeforeRender(Component component) { if (component instanceof FormComponent) { FormComponent<?> formComponent = (FormComponent<?>) component; if (hasError(formComponent)) { formComponent.setMetaData(HAS_ERROR, null); for (Component componentToMarkWithError : getComponentsToDecorateWithCSS(formComponent)) { if (!componentToMarkWithError.getBehaviors().contains(HAS_ERROR_BEHAVIOR)) { componentToMarkWithError.add(HAS_ERROR_BEHAVIOR); } } } } }
public Object component(Component c) { if (!visited.contains(c)) { visited.add(c); // * hinter das Eingabeelement setzen c.setComponentBorder(new RequiredBorder(allowRenderOnAjaxRequest)); // Disabled bis man weiß, wie vermieden werden kann, das die Message // zusätzlich auch im Feedbackpanel angezeigt wird. Ansosten wäre es // cool. // Fehler unter dem Element anzeigen // c.add(new ValidationMsgBehavior()); // * Css des Eingabeelementes um error im Fehlerfall erweitern c.add(new ValidationStyleBehavior()); } return IVisitor.CONTINUE_TRAVERSAL; }
protected CharSequence createScript(Component component) { CharSequence script = "$('#" + component.getMarkupId() + "').infinitescroll({" + " navSelector : \"#" + navSelector + "\"," // selector for the paged navigation (it will be hidden) + " nextSelector : \"#" + nextSelector + "\"," // selector for the NEXT link (to page 2) + " itemSelector : \"" + itemSelector + "," // selector for all items you'll retrieve + " localMode : true," + " debug : false," // enable debug messaging ( to console.log ) + " animate : true," // boolean, if the page will do an animated scroll when new // content loads + " errorCallback: function(){}," // called when a requested page 404's or when there // is no more content + "},function(arrayOfNewElems){});"; // optional callback when new content is // successfully loaded in. if (!autoScroll) { script = script + "$(window).unbind('.infscr');"; script = script + "$('a#next').click(function() {" + " $(document).trigger('retrieve.infscr');" + " return false;" + " });"; } return script; }