org.apache.wicket.behavior.Behavior Java Examples

The following examples show how to use org.apache.wicket.behavior.Behavior. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FormComponent.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Adds a validator to this form component
 * 
 * @param validator
 *            validator to be added
 * @return <code>this</code> for chaining
 * @throws IllegalArgumentException
 *             if validator is null
 * @see IValidator
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public final FormComponent<T> add(final IValidator<? super T> validator)
{
	Args.notNull(validator, "validator");

	if (validator instanceof Behavior)
	{
		add((Behavior)validator);
	}
	else
	{
		add((Behavior)new ValidatorAdapter(validator));
	}
	return this;
}
 
Example #2
Source File: FormComponent.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Gets an unmodifiable list of validators for this FormComponent.
 * 
 * @return List of validators
 */
@SuppressWarnings("unchecked")
public final List<IValidator<? super T>> getValidators()
{
	final List<IValidator<? super T>> list = new ArrayList<>();

	for (Behavior behavior : getBehaviors())
	{
		if (behavior instanceof IValidator)
		{
			list.add((IValidator<? super T>)behavior);
		}
	}

	return Collections.unmodifiableList(list);
}
 
Example #3
Source File: BuildSpecEditPanel.java    From onedev with MIT License 6 votes vote down vote up
private Component newJobContent(Job job) {
	BeanEditor content = new JobEditor(jobContents.newChildId(), job);
	content.add(new Behavior() {

		@Override
		public void renderHead(Component component, IHeaderResponse response) {
			super.renderHead(component, response);
			int index = WicketUtils.getChildIndex(jobContents, content);
			String script = String.format("onedev.server.buildSpec.trackJobNameChange(%d);", index);
			response.render(OnDomReadyHeaderItem.forScript(script));
		}
		
	});
	jobContents.add(content.setOutputMarkupId(true));
	return content;
}
 
Example #4
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 6 votes vote down vote up
public static <T> Behavior onEvent(Class<T> aEventClass,
        SerializableBiConsumer<Component, T> aAction)
{
    return new Behavior()
    {
        private static final long serialVersionUID = -1956074724077271777L;

        @Override
        public void onEvent(Component aComponent, IEvent<?> aEvent)
        {
            if (aEventClass.isAssignableFrom(aEvent.getPayload().getClass())) {
                aAction.accept(aComponent, (T) aEvent.getPayload());
            }
        }
    };
}
 
Example #5
Source File: BootstrapDatePickerTest.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testDatepickerInvokeSpecialDates() {
	final List<SpecialDate> list = Arrays.asList(new SpecialDate(christmas, "holiday", "Christmas"));

	BootstrapDatePicker picker = new BootstrapDatePicker("picker") {
		private static final long serialVersionUID = 1L;

		@Override
		public Collection<SpecialDate> getSpecialDates() {
			return list;
		}
	};

	List<? extends Behavior> behaviors = picker.getBehaviors();
	assertEquals(1, behaviors.size());
	assertTrue(behaviors.get(0) instanceof BootstrapDatePickerBehaviour);
	assertEquals(list, ((BootstrapDatePickerBehaviour)behaviors.get(0)).getSpecialDates());
}
 
Example #6
Source File: InfiniteScrollListView.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Behavior getScrollBehaviour(){
	return new AttributeModifier("scroll", Model.of(this.getMarkupId())){
		private static final long serialVersionUID = 3523727356782417598L;

		@Override
		public void renderHead(Component component, IHeaderResponse response) {
			super.renderHead(component, response);

			response.render(OnDomReadyHeaderItem.forScript("InfiniteScroll.getFromContainer('"+getMarkupId()+"').setUrls('"+upBehavior.getCallbackUrl()+"', '"+downBehavior.getCallbackUrl()+"')"));
		}
		
		@Override
		protected String newValue(String currentValue, String replacementValue) {
			return "InfiniteScroll.handleScroll('"+InfiniteScrollListView.this.getMarkupId()+"')"; 
		}
	};
}
 
Example #7
Source File: FormComponent.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Removes a validator from the form component.
 * 
 * @param validator
 *            validator
 * @throws IllegalArgumentException
 *             if validator is null or not found
 * @see IValidator
 * @see #add(IValidator)
 * @return form component for chaining
 */
public final FormComponent<T> remove(final IValidator<? super T> validator)
{
	Args.notNull(validator, "validator");
	Behavior match = null;
	for (Behavior behavior : getBehaviors())
	{
		if (behavior.equals(validator))
		{
			match = behavior;
			break;
		}
		else if (behavior instanceof ValidatorAdapter)
		{
			if (((ValidatorAdapter<?>)behavior).getValidator().equals(validator))
			{
				match = behavior;
				break;
			}
		}
	}

	if (match != null)
	{
		remove(match);
	}
	else
	{
		throw new IllegalStateException(
			"Tried to remove validator that was not previously added. "
				+ "Make sure your validator's equals() implementation is sufficient");
	}
	return this;
}
 
Example #8
Source File: WicketUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Searchs the attribute behavior (SimpleAttributeModifier or AttibuteApendModifier) with the given attribute name and returns it if
 * found, otherwise null.
 * @param comp
 * @param name Name of attribute.
 */
public static AttributeModifier getAttributeModifier(final Component comp, final String name)
{
  for (final Behavior behavior : comp.getBehaviors()) {
    if (behavior instanceof AttributeAppender && name.equals(((AttributeAppender) behavior).getAttribute()) == true) {
      return (AttributeAppender) behavior;
    } else if (behavior instanceof AttributeModifier && name.equals(((AttributeModifier) behavior).getAttribute()) == true) {
      return (AttributeModifier) behavior;
    }
  }
  return null;
}
 
Example #9
Source File: TextPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
private void init(final Behavior... behaviors)
{
  if (behaviors != null && behaviors.length > 0) {
    label.add(behaviors);
  } else {
    label.setRenderBodyOnly(true);
  }
  add(label);
}
 
Example #10
Source File: DivTextPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public DivTextPanel(final String id, final IModel<String> text, final Behavior... behaviors)
{
  super(id);
  add(div = new WebMarkupContainer("div"));
  label = new Label(WICKET_ID, text);
  init(behaviors);
}
 
Example #11
Source File: DivTextPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public DivTextPanel(final String id, final String text, final Behavior... behaviors)
{
  super(id);
  add(div = new WebMarkupContainer("div"));
  this.text = text;
  label = new Label(WICKET_ID, new PropertyModel<String>(this, "text"));
  init(behaviors);
}
 
Example #12
Source File: DiffTextPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("serial")
public DiffTextPanel(final String id, final IModel<String> newText, final IModel<String> oldText, final Behavior... behaviors)
{
  super(id);
  this.newText = newText;
  this.oldText = oldText;
  label = new Label(WICKET_ID, new Model<String>() {
    @Override
    public String getObject()
    {
      if (prettyHtml == null) {
        final DiffMatchPatch diffMatchPatch = new DiffMatchPatch();
        String newValue = newText.getObject();
        if (newValue == null || "null".equals(newValue) == true) {
          newValue = getString("label.null");
        }
        String oldValue = oldText.getObject();
        if (oldValue == null || "null".equals(oldValue) == true) {
          oldValue = getString("label.null");
        }
        final LinkedList<Diff> diffs = diffMatchPatch.diff_main(oldValue, newValue);
        diffMatchPatch.diff_cleanupSemantic(diffs);
        prettyHtml = getPrettyHtml(diffs);
      }
      return prettyHtml;
    }
  });
  label.add(behaviors).setEscapeModelStrings(false);
  add(label);
}
 
Example #13
Source File: AbstractOMethod.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
protected Command<?> applyBehaviors(Command<?> commandComponent){
	for ( Class<? extends Behavior> behavior : getDefinition().getBehaviors()) {
		try {
			commandComponent.add(behavior.newInstance());
		} catch (InstantiationException | IllegalAccessException e) {
			LOG.error("Can't apply behaviors", e);
		}
	}
	return commandComponent;
}
 
Example #14
Source File: BpmnProcessesAjaxPanel.java    From syncope with Apache License 2.0 5 votes vote down vote up
public BpmnProcessesAjaxPanel(
        final String id, final String name, final IModel<String> model, final Behavior behavior) {
    super(id, name, model, false);
    if (behavior != null) {
        field.add(behavior);
    }
}
 
Example #15
Source File: Navbar.java    From syncope with Apache License 2.0 5 votes vote down vote up
public void setActiveNavItem(final String id) {
    navbarItems.stream().
            filter(containingLI -> containingLI.getMarkupId().equals(id)).findFirst().
            ifPresent(found -> found.add(new Behavior() {

        private static final long serialVersionUID = -5775607340182293596L;

        @Override
        public void onComponentTag(final Component component, final ComponentTag tag) {
            tag.put("class", "active");
        }
    }));
}
 
Example #16
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior enabledWhen(SerializableBooleanSupplier aPredicate)
{
    return new Behavior()
    {
        private static final long serialVersionUID = -1435780281900876366L;

        @Override
        public void onConfigure(Component aComponent)
        {
            aComponent.setEnabled(aPredicate.getAsBoolean());
        }
    };
}
 
Example #17
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior visibleWhen(SerializableBooleanSupplier aPredicate)
{
    return new Behavior()
    {
        private static final long serialVersionUID = -7550330528381560032L;

        @Override
        public void onConfigure(Component aComponent)
        {
            aComponent.setVisible(aPredicate.getAsBoolean());
        }
    };
}
 
Example #18
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior onComponentTag(SerializableBiConsumer<Component, ComponentTag> aAction)
{
    return new Behavior()
    {
        private static final long serialVersionUID = 1191220285070986757L;

        @Override
        public void onComponentTag(Component aComponent, ComponentTag aTag)
        {
            aAction.accept(aComponent, aTag);
        }
    };
}
 
Example #19
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior onConfigure(SerializableConsumer<Component> aAction)
{
    return new Behavior()
    {
        private static final long serialVersionUID = 4955142510510102959L;

        @Override
        public void onConfigure(Component aComponent)
        {
            aAction.accept(aComponent);
        }
    };
}
 
Example #20
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior onException(SerializableBiConsumer<Component, RuntimeException> aAction)
{
    return new Behavior()
    {
        private static final long serialVersionUID = 1927758103651261506L;

        @Override
        public void onException(Component aComponent, RuntimeException aException)
        {
            aAction.accept(aComponent, aException);
        }
    };
}
 
Example #21
Source File: LambdaBehavior.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Behavior onRemove(SerializableConsumer<Component> aAction)
{
    return new Behavior()
    {
        private static final long serialVersionUID = -8323963975999230350L;

        @Override
        public void onRemove(Component aComponent)
        {
            aAction.accept(aComponent);
        }
    };
}
 
Example #22
Source File: DashboardPanel.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
private void changeGlobalSettings(WidgetRuntimeModel runtimeModel, AjaxRequestTarget target) {
	ModalWindow.closeCurrent(target);
			
	WidgetPanelVisitor visitor = new WidgetPanelVisitor();
	visitChildren(WidgetPanel.class, visitor);				
	
	for (WidgetPanel widgetPanel : visitor.getWidgetPanels()) {			
		Widget widget = widgetPanel.getWidget();
		if (widget == null) {
			continue;
		}
		int oldRefreshTime = widget.getRefreshTime();
		WidgetRuntimeModel storedRuntimeModel = ChartUtil.getRuntimeModel(storageService.getSettings(), (EntityWidget)widget, reportService, dataSourceService, true);
		ChartUtil.updateGlobalWidget(widget, storedRuntimeModel, runtimeModel);
		try {				
			dashboardService.modifyWidget(getDashboard().getId(), widget);
		} catch (NotFoundException e) {
			// never happening
			throw new RuntimeException(e);
		}
		int refreshTime = widget.getRefreshTime();
		if (oldRefreshTime != refreshTime) {
			for (Behavior behavior : widgetPanel.getBehaviors()) {
				if (behavior instanceof AjaxSelfUpdatingTimerBehavior) {
					((AjaxSelfUpdatingTimerBehavior) behavior).stop(target);
					// do not remove the behavior : after changing , the
					// event is called one more
					// time on the client so it has to be present ...
				}
			}
			if (refreshTime > 0) {
				widgetPanel.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(refreshTime)));
			}
		}
	}
       
	/*
       for (int i = 0; i < getDashboard().getColumnCount(); i++) {
       	target.add(getColumnPanel(i));
       }
       */
	target.add(this);
}
 
Example #23
Source File: EtcdNodePanel.java    From etcd-viewer with Apache License 2.0 4 votes vote down vote up
public EtcdNodePanel(String id, IModel<String> etcdRegistry, IModel<String> keyModel) {
    super(id);

    this.registry = etcdRegistry;

    this.key = keyModel;

    setModel(new LoadableDetachableModel<EtcdNode>() {
        private static final long serialVersionUID = 1L;
        @Override
        protected EtcdNode load() {
            if (registry.getObject() == null) {
                return null;
            }
            try (EtcdProxy p = proxyFactory.getEtcdProxy(registry.getObject())) {

                return p.getNode(key.getObject());
            } catch (Exception e) {
                log.warn(e.getLocalizedMessage(), e);
                // TODO: handle this exception and show some alert on page
                error("Could not retrieve key " + key.getObject() + ": " + e.toString());
                EtcdNodePanel.this.setEnabled(false);
                return null;
            }
        }
    });

    parentKey = new ParentKeyModel();

    setOutputMarkupId(true);

    createModalPanels();

    add(breadcrumbAndActions = new WebMarkupContainer("breadcrumbAndActions"));
    breadcrumbAndActions.setOutputMarkupId(true);

    createBreadcrumb();

    createNodeActions();

    add(new WebMarkupContainer("icon").add(new AttributeModifier("class", new StringResourceModel("icon.node.dir.${dir}", getModel(), ""))));

    add(new Label("key", new PropertyModel<>(getModel(), "key")));

    add(contents = new WebMarkupContainer("contents"));
    contents.setOutputMarkupId(true);

    WebMarkupContainer currentNode;
    contents.add(currentNode = new WebMarkupContainer("currentNode"));

    currentNode.add(new AttributeAppender("class", new StringResourceModel("nodeClass", getModel(), "") , " "));

    currentNode.add(new Label("createdIndex", new PropertyModel<>(getModel(), "createdIndex")));
    currentNode.add(new Label("modifiedIndex", new PropertyModel<>(getModel(), "modifiedIndex")));
    currentNode.add(new Label("ttl", new PropertyModel<>(getModel(), "ttl")));
    currentNode.add(new Label("expiration", new PropertyModel<>(getModel(), "expiration")));

    contents.add(new TriggerModalLink<EtcdNode>("editValue", getModel(), editNodeModal) {
        private static final long serialVersionUID = 1L;
        @Override
        protected void onConfigure() {
            super.onConfigure();
            if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) {
                add(AttributeAppender.append("disabled", "disabled"));
            } else {
                add(AttributeModifier.remove("disabled"));
            }

            // hide value for directory entries
            setVisible(EtcdNodePanel.this.getModelObject() != null && !EtcdNodePanel.this.getModelObject().isDir());
        }
        @Override
        protected void onModalTriggerClick(AjaxRequestTarget target) {
            updating.setObject(true);
            actionModel.setObject(getModelObject());
        }
    } .add(new MultiLineLabel("value", new PropertyModel<>(getModel(), "value"))));


    AbstractLink goUp;
    contents.add(goUp = createNavigationLink("goUp", parentKey));
    goUp.add(new Behavior() {
        private static final long serialVersionUID = 1L;
        @Override
        public void onConfigure(Component component) {
            super.onConfigure(component);
            component.setEnabled(key.getObject() != null && !"".equals(key.getObject()) && !"/".equals(key.getObject()));
        }
    });

    contents.add(createNodesView("nodes"));
}
 
Example #24
Source File: GridPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Calls div.add(...);
 * @see org.apache.wicket.Component#add(org.apache.wicket.behavior.Behavior[])
 */
@Override
public Component add(final Behavior... behaviors)
{
  return div.add(behaviors);
}
 
Example #25
Source File: FormComponent.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Validates this component using the component's validators.
 */
@SuppressWarnings("unchecked")
protected final void validateValidators()
{
	final IValidatable<T> validatable = newValidatable();

	boolean isNull = getConvertedInput() == null;

	IValidator<T> validator;

	for (Behavior behavior : getBehaviors())
	{
		if (isBehaviorAccepted(behavior) == false)
		{
			continue;
		}

		validator = null;
		if (behavior instanceof ValidatorAdapter)
		{
			validator = ((ValidatorAdapter<T>)behavior).getValidator();
		}
		else if (behavior instanceof IValidator)
		{
			validator = (IValidator<T>)behavior;
		}
		if (validator != null)
		{
			if (isNull == false || validator instanceof INullAcceptingValidator<?>)
			{
				try
				{
					validator.validate(validatable);
				}
				catch (Exception e)
				{
					throw new WicketRuntimeException("Exception '" + e.getMessage() +
							"' occurred during validation " + validator.getClass().getName() +
							" on component " + getPath(), e);
				}
			}
			if (!isValid())
			{
				break;
			}
		}
	}
}
 
Example #26
Source File: WicketUtils.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Same as {@link #setFocus(FormComponent)}
 * @return AttributeAppender
 */
public static Behavior setFocus()
{
  return new FocusOnLoadBehavior();
}
 
Example #27
Source File: ToggleContainerPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Calls div.add(...);
 * @see org.apache.wicket.Component#add(org.apache.wicket.behavior.Behavior[])
 */
@Override
public Component add(final Behavior... behaviors)
{
  return toggleContainer.add(behaviors);
}
 
Example #28
Source File: DivPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Calls div.add(...);
 * @see org.apache.wicket.Component#add(org.apache.wicket.behavior.Behavior[])
 */
@Override
public Component add(final Behavior... behaviors)
{
  return div.add(behaviors);
}
 
Example #29
Source File: TextPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public TextPanel(final String id, final Model<String> text, final Behavior... behaviors)
{
  super(id);
  label = new Label("text", text);
  init(behaviors);
}
 
Example #30
Source File: TextPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public TextPanel(final String id, final String text, final Behavior... behaviors)
{
  super(id);
  label = new Label("text", text);
  init(behaviors);
}