Example usage for org.apache.wicket.ajax.markup.html AjaxFallbackLink AjaxFallbackLink

List of usage examples for org.apache.wicket.ajax.markup.html AjaxFallbackLink AjaxFallbackLink

Introduction

In this page you can find the example usage for org.apache.wicket.ajax.markup.html AjaxFallbackLink AjaxFallbackLink.

Prototype

public AjaxFallbackLink(final String id, final IModel<T> model) 

Source Link

Document

Construct.

Usage

From source file:com.lyndir.lhunath.snaplog.webapp.view.MediaView.java

License:Apache License

/**
 * @param id        The wicket ID of this component.
 * @param model     The model that will provide the {@link Media} to show in this view.
 * @param quality   The quality at which to show the {@link Media}.
 * @param clickable <code>true</code>: The media will be clickable. When clicked, the {@link #onClick(AjaxRequestTarget)} will be
 *                  fired.<br> <code>false</code>: The media will not be clickable. There is no need to implement {@link
 *                  #onClick(AjaxRequestTarget)}.
 *//*w  ww.j  ava2 s .co  m*/
public MediaView(final String id, final IModel<Media> model, final Quality quality, final boolean clickable) {

    super(id, model);

    // The media container.
    WebMarkupContainer media = new WebMarkupContainer("media");
    add(media.add(new AttributeAppender("class", new Model<String>(quality.getName()), " ")));

    // The media image link/container.
    WebMarkupContainer image;
    if (clickable) {
        image = new AjaxFallbackLink<Media>("image", getModel()) {

            @Override
            public void onClick(final AjaxRequestTarget target) {

                MediaView.this.onClick(target);
            }

            @Override
            public boolean isVisible() {

                return getModelObject() != null;
            }
        };
        media.add(new CSSClassAttributeAppender("link"));
    } else
        image = new WebMarkupContainer("image") {

            @Override
            public boolean isVisible() {

                return getModelObject() != null;
            }
        };
    media.add(image);
    media.add(new WebMarkupContainer("tools") {

        {
            add(new ExternalLink("original", new LoadableDetachableModel<String>() {

                @Override
                protected String load() {

                    try {
                        URL resourceURL = sourceDelegate.findResourceURL(SnaplogSession.get().newToken(),
                                getModelObject(), Quality.ORIGINAL);
                        if (resourceURL == null)
                            // TODO: May want to display something useful to the user like a specific "not-found" thumbnail.
                            return null;

                        return resourceURL.toExternalForm();
                    } catch (PermissionDeniedException ignored) {
                        // TODO: May want to display something useful to the user like a specific "denied" thumbnail.
                        return null;
                    }
                }
            }) {
                @Override
                protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {

                    if (!renderAsMini(markupStream, openTag))
                        super.onComponentTagBody(markupStream, openTag);
                }
            });
            add(new AjaxLink<Media>("share", getModel()) {
                @Override
                public void onClick(final AjaxRequestTarget target) {

                    try {
                        Tab.SHARED.activateWithState(new SharedTabPanel.SharedTabState(getModelObject()));
                    } catch (PermissionDeniedException e) {
                        error(e.getLocalizedMessage());
                    }
                }

                @Override
                protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {

                    if (!renderAsMini(markupStream, openTag))
                        super.onComponentTagBody(markupStream, openTag);
                }

                @Override
                public boolean isVisible() {

                    return securityService.hasAccess(Permission.ADMINISTER, SnaplogSession.get().newToken(),
                            getModelObject());
                }
            });
            add(new WebMarkupContainer("permissions") {
                @Override
                protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {

                    if (!renderAsMini(markupStream, openTag))
                        super.onComponentTagBody(markupStream, openTag);
                }

                @Override
                public boolean isVisible() {

                    return securityService.hasAccess(Permission.ADMINISTER, SnaplogSession.get().newToken(),
                            getModelObject());
                }
            });
            add(new Link<Media>("delete", getModel()) {
                @Override
                public void onClick() {

                    try {
                        sourceDelegate.delete(SnaplogSession.get().newToken(), getModelObject());
                    } catch (PermissionDeniedException e) {
                        error(e.getLocalizedMessage());
                    }
                }

                @Override
                protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {

                    if (!renderAsMini(markupStream, openTag))
                        super.onComponentTagBody(markupStream, openTag);
                }

                @Override
                public boolean isVisible() {

                    return securityService.hasAccess(Permission.ADMINISTER, SnaplogSession.get().newToken(),
                            getModelObject());
                }
            });

            add(CSSClassAttributeAppender.of(new LoadableDetachableModel<String>() {
                @Override
                protected String load() {

                    return isMini(quality) ? "mini" : null;
                }
            }));
        }

        @Override
        public boolean isVisible() {

            return getModelObject() != null;
        }

        private boolean renderAsMini(final MarkupStream markupStream, final ComponentTag openTag) {

            if (isMini(quality)) {
                // Discard all elements from the markup stream until our close tag.
                while (markupStream.hasMore())
                    if (markupStream.next().closes(openTag))
                        break;

                replaceComponentTagBody(markupStream, openTag, "");
                return true;
            }

            return false;
        }
    });

    image.add(new AttributeModifier("style", true, new LoadableDetachableModel<String>() {

        @Override
        protected String load() {

            try {
                URL resourceURL = sourceDelegate.findResourceURL(SnaplogSession.get().newToken(),
                        getModelObject(), quality);
                if (resourceURL == null)
                    // TODO: May want to display something useful to the user like a specific "not-found" thumbnail.
                    return null;

                return String.format("background-image: url('%s')", resourceURL.toExternalForm());
            } catch (PermissionDeniedException ignored) {
                // TODO: May want to display something useful to the user like a specific "denied" thumbnail.
                return null;
            }
        }
    }));
    image.add(new ContextImage("thumb", new LoadableDetachableModel<String>() {

        @Override
        protected String load() {

            logger.dbg("Loading Media: %s, Quality: %s", getModelObject(), quality);

            try {
                URL resourceURL = sourceDelegate.findResourceURL(SnaplogSession.get().newToken(),
                        getModelObject(), Quality.THUMBNAIL);
                if (resourceURL == null)
                    // TODO: May want to display something useful to the user like a specific "not-found" thumbnail.
                    return null;

                return resourceURL.toExternalForm();
            } catch (PermissionDeniedException ignored) {
                // TODO: May want to display something useful to the user like a specific "denied" thumbnail.
                return null;
            }
        }
    }));
    image.add(new ContextImage("full", new LoadableDetachableModel<String>() {

        @Override
        protected String load() {

            try {
                URL resourceURL = sourceDelegate.findResourceURL(SnaplogSession.get().newToken(),
                        getModelObject(), quality);
                if (resourceURL == null)
                    // TODO: May want to display something useful to the user like a specific "not-found" thumbnail.
                    return null;

                return resourceURL.toExternalForm();
            } catch (PermissionDeniedException ignored) {
                // TODO: May want to display something useful to the user like a specific "denied" thumbnail.
                return null;
            }
        }
    }) {
        @Override
        public boolean isVisible() {

            return quality == Quality.FULLSCREEN;
        }
    });
    image.add(new Label("caption", new LoadableDetachableModel<String>() {

        @Override
        protected String load() {

            return getCaptionString();
        }
    }) {

        @Override
        public boolean isVisible() {

            return getModelObject() != null;
        }
    });
}

From source file:it.av.eatt.web.page.RistoranteAddNewPage.java

License:Apache License

/**
 * Constructor that is invoked when page is invoked without a session.
 * /*from   w w  w .j  a v  a2  s. com*/
 * @throws JackWicketException
 */
public RistoranteAddNewPage() throws JackWicketException {
    ristorante = new Ristorante();
    ristorante.addDescriptions(getDescriptionI18n());
    form = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante));
    add(getFeedbackPanel());
    AjaxFormComponentUpdatingBehavior updatingBehavior = new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onUpdate(AjaxRequestTarget arg0) {
            try {
                String ristoName = form.get(Ristorante.NAME).getDefaultModelObjectAsString();
                Country ristoCountry = ((DropDownChoice<Country>) form.get(Ristorante.COUNTRY))
                        .getModelObject();
                List<DataRistorante> ristosFound = new ArrayList<DataRistorante>(
                        dataRistoranteService.getBy(ristoName, cityName, ristoCountry));
                if (!(ristosFound.isEmpty())) {
                    DataRistorante dataRistorante = ristosFound.get(0);
                    form.get(Ristorante.ADDRESS).setDefaultModelObject(dataRistorante.getAddress());
                    form.get(Ristorante.FAX_NUMBER).setDefaultModelObject(dataRistorante.getFaxNumber());
                    form.get(Ristorante.PHONE_NUMBER).setDefaultModelObject(dataRistorante.getPhoneNumber());
                    form.get(Ristorante.POSTALCODE).setDefaultModelObject(dataRistorante.getPostalCode());
                    form.get(Ristorante.PROVINCE).setDefaultModelObject(dataRistorante.getProvince());
                    form.get(Ristorante.WWW).setDefaultModelObject(dataRistorante.getWww());
                    info(new StringResourceModel("info.autocompletedRistoSucces", form, null).getString());
                    arg0.addComponent(getFeedbackPanel());
                    arg0.addComponent(form);
                }
            } catch (Exception e) {
                error(new StringResourceModel("genericErrorMessage", form, null).getString());
                new JackWicketRunTimeException(e);
                arg0.addComponent(getFeedbackPanel());
            }
        }
    };
    form.setOutputMarkupId(true);
    final RistoranteAutocompleteBox ristoName = new RistoranteAutocompleteBox(Ristorante.NAME,
            AutocompleteUtils.getAutoCompleteSettings());
    ristoName.setRequired(true);
    ristoName.add(updatingBehavior);
    form.add(ristoName);
    form.add(new RequiredTextField<String>(Ristorante.ADDRESS));
    CityAutocompleteBox city = new CityAutocompleteBox("city-autocomplete",
            AutocompleteUtils.getAutoCompleteSettings(), new Model<String>(cityName) {
                @Override
                public String getObject() {
                    return cityName;
                }

                @Override
                public void setObject(String object) {
                    cityName = (String) object;
                }
            });
    // With this component the city model is updated correctly after every change
    city.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // TODO Auto-generated method stub
        }
    });
    city.add(new CityValidator());
    form.add(city);
    form.add(new RequiredTextField<String>(Ristorante.PROVINCE));
    form.add(new RequiredTextField<String>(Ristorante.POSTALCODE));
    DropDownChoice<Country> country = new DropDownChoice<Country>(Ristorante.COUNTRY, countryService.getAll(),
            new CountryChoiceRenderer());
    country.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
        }
    });
    country.setRequired(true);
    form.add(country);
    form.add(new TextField<String>(Ristorante.PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.FAX_NUMBER));
    form.add(new TextField<String>(Ristorante.MOBILE_PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.WWW));
    form.add(new CheckBox("types.ristorante"));
    form.add(new CheckBox("types.pizzeria"));
    form.add(new CheckBox("types.bar"));

    ListView<RistoranteDescriptionI18n> descriptions = new ListView<RistoranteDescriptionI18n>("descriptions") {
        @Override
        protected void populateItem(ListItem<RistoranteDescriptionI18n> item) {
            item.add(new Label(RistoranteDescriptionI18n.LANGUAGE,
                    getString(item.getModelObject().getLanguage().getCountry())));
            item.add(new TextArea<String>(RistoranteDescriptionI18n.DESCRIPTION,
                    new PropertyModel<String>(item.getModelObject(), RistoranteDescriptionI18n.DESCRIPTION)));
        }
    };
    descriptions.setReuseItems(true);
    form.add(descriptions);

    buttonClearForm = new AjaxFallbackLink<Ristorante>("buttonClearForm", new Model<Ristorante>(ristorante)) {
        @Override
        public void onClick(AjaxRequestTarget target) {
            form.setModelObject(new Ristorante());
            target.addComponent(form);
        }
    };

    form.add(buttonClearForm);

    form.add(new SubmitButton("submitRestaurant", form));
    submitRestaurantRight = new SubmitButton("submitRestaurantRight", form);
    submitRestaurantRight.setOutputMarkupId(true);
    add(submitRestaurantRight);

    // OnChangeAjaxBehavior onChangeAjaxBehavior = new OnChangeAjaxBehavior() {
    // @Override
    // protected void onUpdate(AjaxRequestTarget target) {
    // // label.setModelObject(getValue(city.getModelObjectAsString()));
    // // target.addComponent(label);
    // }
    // };
    // city.add(onChangeAjaxBehavior);

    add(form);
}

From source file:it.av.eatt.web.page.RistoranteEditAddressPage.java

License:Apache License

/**
 * /*from   w ww.j av  a2s. c  o  m*/
 * @param parameters
 * @throws JackWicketException
 */
public RistoranteEditAddressPage(PageParameters parameters) throws JackWicketException {

    String ristoranteId = parameters.getString("ristoranteId", "");
    if (StringUtils.isNotBlank(ristoranteId)) {
        this.ristorante = ristoranteService.getByID(ristoranteId);
    } else {
        setRedirect(true);
        setResponsePage(getApplication().getHomePage());
    }

    form = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante));
    form.setOutputMarkupId(true);
    form.add(new RequiredTextField<String>(Ristorante.NAME));
    form.add(new RequiredTextField<String>(Ristorante.ADDRESS));
    cityName = ristorante.getCity().getName();
    CityAutocompleteBox city = new CityAutocompleteBox("city-autocomplete",
            AutocompleteUtils.getAutoCompleteSettings(), new Model<String>(cityName) {
                @Override
                public String getObject() {
                    return cityName;
                }

                @Override
                public void setObject(String object) {
                    cityName = (String) object;
                }
            });
    // With this component the city model is updated correctly after every change
    city.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // TODO Auto-generated method stub
        }
    });
    city.add(new CityValidator());
    form.add(city);
    form.add(new RequiredTextField<String>(Ristorante.PROVINCE));
    form.add(new RequiredTextField<String>(Ristorante.POSTALCODE));
    DropDownChoice<Country> country = new DropDownChoice<Country>(Ristorante.COUNTRY, countryService.getAll(),
            new CountryChoiceRenderer());
    country.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
        }
    });
    country.setRequired(true);
    form.add(country);
    form.add(new RequiredTextField<String>(Ristorante.PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.MOBILE_PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.FAX_NUMBER));

    form.add(new AjaxFallbackLink<Ristorante>("buttonClearForm", new Model<Ristorante>(ristorante)) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            form.setModelObject(new Ristorante());
            if (target != null) {
                target.addComponent(form);
            }
        }
    });
    form.add(new SubmitButton("submitRestaurant", form));
    add(form);
    add(new SubmitButton("submitRestaurantRight", form));
}

From source file:it.av.youeat.web.page.FriendsPage.java

License:Apache License

/**
 * Constructor that is invoked when page is invoked without a session.
 * /*  w w w. j a v a2 s  . c o m*/
 */
public FriendsPage() {
    super();
    add(getFeedbackPanel());
    final Label noYetFriends = new Label("noYetFriends", getString("noYetFriends")) {
        @Override
        protected void onBeforeRender() {
            super.onBeforeRender();
            setVisible(eaterRelationService.getAllRelations(getLoggedInUser()).size() == 0);
        }
    };
    noYetFriends.setOutputMarkupId(true);
    noYetFriends.setOutputMarkupPlaceholderTag(true);
    add(noYetFriends);
    final ModalWindow sendMessageMW = SendMessageModalWindow.getNewModalWindow("sendMessagePanel");
    add(sendMessageMW);
    final WebMarkupContainer friendsListContainer = new WebMarkupContainer("friendsListContainer");
    friendsListContainer.setOutputMarkupId(true);
    add(friendsListContainer);
    friendsList = new PropertyListView<EaterRelation>("friendsList", new RelationsModel()) {

        @Override
        protected void populateItem(final ListItem<EaterRelation> item) {
            // if the dialog contains unread message, use a different CSS style
            if (item.getModelObject().getStatus().equals(EaterRelation.STATUS_PENDING)) {
                item.add(new AttributeAppender("class", new Model<String>("rowMessageUnread"), " "));
            }
            boolean isPendingFriendRequest = item.getModelObject().getStatus()
                    .equals(EaterRelation.STATUS_PENDING)
                    && item.getModelObject().getToUser().equals(getLoggedInUser());
            BookmarkablePageLink linkToUser = new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    new PageParameters(
                            YoueatHttpParams.YOUEAT_ID + "=" + item.getModelObject().getToUser().getId()));
            item.add(linkToUser);
            final Eater eaterToshow;
            if (getLoggedInUser().equals(item.getModelObject().getToUser())) {
                eaterToshow = item.getModelObject().getFromUser();
            } else {
                eaterToshow = item.getModelObject().getToUser();
            }
            linkToUser.add(new Label(EaterRelation.TO_USER + ".firstname", eaterToshow.getFirstname()));
            linkToUser.add(new Label(EaterRelation.TO_USER + ".lastname", eaterToshow.getLastname()));

            item.add(ImagesAvatar.getAvatar("avatar", eaterToshow, this.getPage(), true));
            item.add(new Label(EaterRelation.TYPE));
            item.add(new Label(EaterRelation.STATUS));
            // item.add(new Label(EaterRelation.TO_USER + ".userRelation"));
            item.add(new AjaxFallbackLink<EaterRelation>("remove",
                    new Model<EaterRelation>(item.getModelObject())) {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        ((FriendsPage) getPage()).eaterRelationService.remove(getModelObject());
                        noYetFriends.setVisible(friendsList.getModelObject().size() == 0);
                        info(getString("info.userRelationRemoved"));
                    } catch (YoueatException e) {
                        error(new StringResourceModel("genericErrorMessage", this, null).getString());
                    }
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                        target.addComponent((noYetFriends));
                        target.addComponent((friendsListContainer));
                        target.addComponent(((FriendsPage) target.getPage()).getFeedbackPanel());
                    }
                }
            }.setVisible(!isPendingFriendRequest));
            item.add(new AjaxFallbackLink<EaterRelation>("acceptFriend",
                    new Model<EaterRelation>(item.getModelObject())) {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        ((FriendsPage) getPage()).eaterRelationService
                                .performFriendRequestConfirm(getModelObject());
                        noYetFriends.setVisible(friendsList.getModelObject().size() == 0);
                        // info(new StringResourceModel("info.userRelationRemoved", this, null).getString());
                    } catch (YoueatException e) {
                        error(new StringResourceModel("genericErrorMessage", this, null).getString());
                    }
                    if (target != null) {
                        target.addComponent((noYetFriends));
                        target.addComponent((friendsListContainer));
                        target.addComponent(((FriendsPage) target.getPage()).getFeedbackPanel());
                    }
                }
            }.setVisible(isPendingFriendRequest));

            item.add(new AjaxFallbackLink<EaterRelation>("ignoreFriendRequest",
                    new Model<EaterRelation>(item.getModelObject())) {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        ((FriendsPage) getPage()).eaterRelationService
                                .performFriendRequestIgnore(getModelObject());
                        noYetFriends.setVisible(friendsList.getModelObject().size() == 0);
                        // info(new StringResourceModel("info.userRelationRemoved", this, null).getString());
                    } catch (YoueatException e) {
                        error(new StringResourceModel("genericErrorMessage", this, null).getString());
                    }
                    if (target != null) {
                        target.addComponent((noYetFriends));
                        target.addComponent((friendsListContainer));
                        target.addComponent(((FriendsPage) target.getPage()).getFeedbackPanel());
                    }
                }
            }.setVisible(isPendingFriendRequest));
            item.add(new SendMessageButton("sendMessage", getLoggedInUser(), eaterToshow, item.getModelObject(),
                    sendMessageMW));

        }
    };
    friendsListContainer.add(friendsList);
    add(new AjaxFallbackLink<String>("goSearchFriendPage") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            setResponsePage(SearchFriendPage.class);
        }
    });

    // Activities
    try {
        activities = activityService.findByEaterFriendAndEater(getLoggedInUser(),
                activityPagingUser.getFirstResult(), activityPagingUser.getMaxResults());
    } catch (YoueatException e) {
        activities = new ArrayList<ActivityEaterRelation>();
        error(new StringResourceModel("error.errorGettingListActivities", this, null).getString());
    }

    activitiesListContainer = new WebMarkupContainer("activitiesListContainer");
    activitiesListContainer.setOutputMarkupId(true);
    add(activitiesListContainer);
    activitiesList = new ActivitiesRelationListView("activitiesList", activities);
    activitiesList.setOutputMarkupId(true);
    activitiesListContainer.add(activitiesList);
    AjaxFallbackLink<String> moreActivitiesLink = new AjaxFallbackLink<String>("moreActivitiesLink") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            activityPagingUser.addNewPage();
            try {
                activities.addAll(activityService.findByEaterFriendAndEater(getLoggedInUser(),
                        activityPagingUser.getFirstResult(), activityPagingUser.getMaxResults()));
                if (target != null) {
                    target.addComponent(activitiesListContainer);
                }
            } catch (YoueatException e) {
                error(new StringResourceModel("error.errorGettingListActivities", this, null).getString());
            }
        }
    };
    activitiesListContainer.add(moreActivitiesLink);
}

From source file:it.av.youeat.web.page.MessageListPage.java

License:Apache License

public MessageListPage() {
    super();/*from  w  w w  .j a  v a2  s  .  co m*/
    add(getFeedbackPanel());
    final Label noYetMessages = new Label("noYetMessages", getString("noMessages")) {
        @Override
        protected void onBeforeRender() {
            super.onBeforeRender();
            setVisible(getLastMessages().size() == 0);
        }
    };
    noYetMessages.setOutputMarkupId(true);
    noYetMessages.setOutputMarkupPlaceholderTag(true);
    add(noYetMessages);

    final WebMarkupContainer messagesListContainer = new WebMarkupContainer("messagesListContainer");
    messagesListContainer.setOutputMarkupPlaceholderTag(true);
    add(messagesListContainer);
    messageList = new PropertyListView<Message>("messagesList", new MessagesModel()) {

        @Override
        protected void populateItem(final ListItem<Message> item) {
            // if the dialog contains unread message, use a different CSS style
            if (!(item.getModelObject().getSender().equals(getLoggedInUser()))
                    && item.getModelObject().getReadTime() == null) {
                item.add(new AttributeAppender("class", new Model<String>("rowMessageUnread"), " "));
            }
            Eater sender = item.getModelObject().getSender();
            Eater recipient = item.getModelObject().getDialog().checkCounterpart(sender);
            item.add(ImagesAvatar.getAvatar("avatar", sender, this.getPage(), true));
            item.add(new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    EaterUtil.createParamsForEater(sender)).add(new Label(Message.SENDER_FIELD)));
            BookmarkablePageLink recipientLink = new BookmarkablePageLink("linkToRecipientUser",
                    EaterViewPage.class, EaterUtil.createParamsForEater(recipient));
            recipientLink.add(new Label("recipient", recipient.toString()));
            //visible only on Sent page
            recipientLink.setVisible(!inBox);
            item.add(recipientLink);
            item.add(new Label(Message.SENTTIME_FIELD));
            item.add(new OpenMessage("openMessageTitle", new Model<Message>(item.getModelObject()), item)
                    .add(new Label(Message.TITLE_FIELD)));
            String messageBodyShort = StringUtils.abbreviate(
                    templateUtil.resolveTemplateEater(item.getModelObject(), false, null, getWebPage()), 150);
            item.add(new OpenMessage("openMessage", new Model<Message>(item.getModelObject()), item)
                    .add(new Label(Message.BODY_FIELD, messageBodyShort)));
            item.add(new AjaxFallbackLink<Message>("remove", new Model<Message>(item.getModelObject())) {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    try {
                        ((MessageListPage) getPage()).dialogService.delete(getModelObject().getDialog(),
                                getLoggedInUser());
                        noYetMessages.setVisible(getLastMessages().size() == 0);
                        info(getString("info.userRelationRemoved"));
                    } catch (YoueatException e) {
                        error(new StringResourceModel("genericErrorMessage", this, null).getString());
                    }
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                        target.addComponent((noYetMessages));
                        target.addComponent((messagesListContainer));
                        target.addComponent(((MessageListPage) target.getPage()).getFeedbackPanel());
                    }
                }
            });
            item.add(new OpenMessage("open", new Model<Message>(item.getModelObject()), item));
        }
    };
    messagesListContainer.add(messageList);

    add(new BookmarkablePageLink("goSearchFriendPage", SearchFriendPage.class));

    long numberUnreadMsgs = messageService.countUnreadMessages(getLoggedInUser());
    final WebMarkupContainer separator = new WebMarkupContainer("separator");
    separator.setVisible(numberUnreadMsgs > 0);

    final Label unreadMsgs = new Label("unreadMessages", new Model<Long>(numberUnreadMsgs));
    unreadMsgs.setOutputMarkupPlaceholderTag(true);
    unreadMsgs.setVisible(numberUnreadMsgs > 0);

    AjaxFallbackLink<String> inboxButton = new AjaxFallbackLink<String>("inbox") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            inBox = true;
            noYetMessages.setVisible(getLastMessages().size() == 0);
            if (target != null) {
                target.addComponent((messagesListContainer));
                target.addComponent((noYetMessages));
            }
        }
    };
    add(inboxButton);
    add(new Label("numberMessages", Integer.toString(messageList.getModel().getObject().size())));
    add(unreadMsgs);
    add(separator);
    add(new AjaxFallbackLink<String>("sentitems") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            inBox = false;
            noYetMessages.setVisible(getLastMessages().size() == 0);
            if (target != null) {
                target.addComponent((messagesListContainer));
                target.addComponent((noYetMessages));
            }
        }
    });
    long numberSentMsgs = dialogService.countCreatedDialogs(getLoggedInUser());
    add(new Label("numberSentMessages", Long.toString(numberSentMsgs)));
}

From source file:it.av.youeat.web.page.RistoranteAddNewPage.java

License:Apache License

/**
 * Constructor that is invoked when page is invoked without a session.
 * /*from  w  w  w  .jav a  2s . com*/
 * @throws YoueatException
 */
public RistoranteAddNewPage() {
    ristorante = new Ristorante();
    ristorante.setCountry(getLoggedInUser().getCountry());
    form = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante));
    add(getFeedbackPanel());
    AjaxFormComponentUpdatingBehavior updatingBehavior = new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            try {
                String ristoName = form.get(Ristorante.NAME).getDefaultModelObjectAsString();
                ristoName = StringEscapeUtils.unescapeHtml(ristoName);
                Country ristoCountry = ((DropDownChoice<Country>) form.get(Ristorante.COUNTRY))
                        .getModelObject();
                List<DataRistorante> ristosFound = new ArrayList<DataRistorante>(
                        dataRistoranteService.getBy(ristoName, cityName, ristoCountry));
                if (!(ristosFound.isEmpty())) {
                    DataRistorante dataRistorante = ristosFound.get(0);
                    form.get(Ristorante.ADDRESS).setDefaultModelObject(dataRistorante.getAddress());
                    form.get(Ristorante.PHONE_NUMBER).setDefaultModelObject(dataRistorante.getPhoneNumber());
                    form.get(Ristorante.POSTALCODE).setDefaultModelObject(dataRistorante.getPostalCode());
                    form.get(Ristorante.PROVINCE).setDefaultModelObject(dataRistorante.getProvince());
                    form.get(Ristorante.WWW).setDefaultModelObject(dataRistorante.getWww());
                    info(new StringResourceModel("info.autocompletedRistoSucces", form, null).getString());
                    target.addComponent(getFeedbackPanel());
                    target.addComponent(form);
                }
            } catch (Exception e) {
                error(new StringResourceModel("genericErrorMessage", form, null).getString());
                target.addComponent(getFeedbackPanel());
            }
        }
    };
    form.setOutputMarkupId(true);
    final RistoranteAutocompleteBox ristoName = new RistoranteAutocompleteBox(Ristorante.NAME,
            AutocompleteUtils.getAutoCompleteSettings());
    ristoName.setRequired(true);
    ristoName.add(updatingBehavior);
    form.add(ristoName);
    form.add(new RequiredTextField<String>(Ristorante.ADDRESS));
    CityAutocompleteBox city = new CityAutocompleteBox("city-autocomplete",
            AutocompleteUtils.getAutoCompleteSettings(), new Model<String>(cityName) {
                @Override
                public String getObject() {
                    return cityName;
                }

                @Override
                public void setObject(String object) {
                    cityName = (String) object;
                }
            });
    // With this component the city model is updated correctly after every change, fixing also the case of the city
    city.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            String ristoName = getComponent().getDefaultModelObjectAsString();
            Country ristoCountry = ((DropDownChoice<Country>) form.get(Ristorante.COUNTRY)).getModelObject();
            ristoName = StringEscapeUtils.unescapeHtml(ristoName);
            City city = cityService.getByNameAndCountry(ristoName, ristoCountry);
            if (city != null) {
                getComponent().setDefaultModelObject(city.getName());
            }
            if (target != null) {
                target.addComponent(getComponent());
            }
        }
    });
    // city.add(new CityValidator());
    form.add(city);
    form.add(new TextField<String>(Ristorante.PROVINCE));
    form.add(new TextField<String>(Ristorante.POSTALCODE));
    DropDownChoice<Country> country = new DropDownChoice<Country>(Ristorante.COUNTRY, countryService.getAll(),
            new CountryChoiceRenderer());
    country.add(new OnChangeAjaxBehavior() {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
        }
    });
    country.setRequired(true);
    form.add(country);
    form.add(new TextField<String>(Ristorante.PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.MOBILE_PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.WWW));

    buttonClearForm = new AjaxFallbackLink<Ristorante>("buttonClearForm", new Model<Ristorante>(ristorante)) {
        @Override
        public void onClick(AjaxRequestTarget target) {
            form.setModelObject(new Ristorante());
            target.addComponent(form);
        }
    };

    form.add(buttonClearForm);

    buttonOpenAddedRisto = new ButtonOpenRisto("buttonOpenAddedRisto", new Model<Ristorante>(ristorante),
            false);
    add(buttonOpenAddedRisto);

    buttonOpenAddedRistoRight = new ButtonOpenRisto("buttonOpenAddedRistoRight",
            new Model<Ristorante>(ristorante), false);
    add(buttonOpenAddedRistoRight);

    submitRestaurantBottom = new SubmitButton("submitRestaurant", form);
    form.add(submitRestaurantBottom);
    submitRestaurantRight = new SubmitButton("submitRestaurantRight", form);
    add(submitRestaurantRight);

    add(form);

    modalWindow = new WarningOnAlreadyPresentRistoModalWindow("warningOnAlreadyPresentRistoModalWindow", this);
    add(modalWindow);
}

From source file:it.av.youeat.web.panel.SearchFriendTableActionPanel.java

License:Apache License

/**
 * @param id component id/* w ww  . ja  v a2  s  .  c o  m*/
 * @param model model for contact
 */
public SearchFriendTableActionPanel(String id, IModel<Eater> model) {
    super(id, model);
    add(new AjaxFallbackLink<Eater>("addFriend", model) {

        @Override
        public void onClick(AjaxRequestTarget target) {
            SearchFriendPage page = ((SearchFriendPage) getPage());
            try {
                userRelationService.addFriendRequest(page.getLoggedInUser(), getModelObject());
                page.refreshDataTable();
                info(getString("friendRequestSent", getModel()));
            } catch (YoueatException e) {
                error(getString("genericErrorMessage"));
            }
            if (target != null) {
                target.addComponent(page.getSearchFriendsContainer());
                target.addComponent(page.getFeedbackPanel());
            }
        }
    });
    add(new AjaxFallbackLink<Eater>("followUser", model) {

        @Override
        public void onClick(AjaxRequestTarget target) {
            SearchFriendPage page = ((SearchFriendPage) getPage());
            try {
                userRelationService.addFollowUser(page.getLoggedInUser(), getModelObject());
                page.refreshDataTable();
                info(getString("followUserDone", getModel()));
            } catch (YoueatException e) {
                error(getString("genericErrorMessage"));
            }
            if (target != null) {
                target.addComponent(page.getSearchFriendsContainer());
                target.addComponent(page.getFeedbackPanel());
            }

        }
    });
}

From source file:nl.knaw.dans.dccd.web.entitytree.TreeLevelPanel.java

License:Apache License

@SuppressWarnings("unchecked")
public TreeLevelPanel(String id, IModel model) {
    super(id, model);

    // the model object should have a list of object supporting the toString?
    // or a list of strings?
    final List<Object> list = (List<Object>) model.getObject();
    final int lastIndex = list.size() - 1;

    // fill the list
    add(new ListView("level_list", list) {
        private static final long serialVersionUID = 5242639240679858437L;

        @Override/*  www  . j a v  a  2 s .co  m*/
        protected void populateItem(ListItem item) {
            //item.getIndex() + ":" + item.getModelObjectAsString()
            Link link = null;
            if (item.getIndex() == lastIndex) {
                // skip first separator at the end of the list
                item.add(new Label("separator", ""));

                // the last one should be a 'static' thing
                // because it is the current selection
                //item.add(new Label("level", new Model(item.getModelObjectAsString())));
                link = new AjaxFallbackLink("level", item.getModel()) {
                    private static final long serialVersionUID = -6041781592958070083L;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        // do nothing!
                    }
                };
                link.setEnabled(false);//? disabled might be visually wrong
            } else {
                item.add(new Label("separator", ">"));
                // make it a clickable Link?
                link = new AjaxFallbackLink("level", new Model(new Integer(item.getIndex()))) {//item.getModel()) {
                    private static final long serialVersionUID = 3960686165249813487L;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        //
                        Integer index = (Integer) getModelObject();
                        int levelsUp = lastIndex - index.intValue();
                        logger.info("clicked levels up: " + levelsUp);
                        onSelectionChanged(levelsUp, target);
                    }
                };
            }
            item.add(link);
            link.add(new Label("level_label", new Model(item.getDefaultModelObjectAsString())));

        }
    });
}

From source file:org.cipango.ims.hss.web.subscription.EditImplicitSetPage.java

License:Apache License

@SuppressWarnings("unchecked")
private RefreshingView getPublicIdView(final Item item) {
    final IModel<SortedSet<PublicUserIdentity>> model = new LoadableDetachableModel<SortedSet<PublicUserIdentity>>() {

        @Override/*from  w w  w.j av a 2  s  .c o m*/
        protected SortedSet<PublicUserIdentity> load() {
            return ((ImplicitRegistrationSet) item.getModelObject()).getPublicIdentities();
        }
    };

    return new RefreshingView<PublicUserIdentity>("publicIds", model) {

        @Override
        protected Iterator<IModel<PublicUserIdentity>> getItemModels() {
            List<IModel<PublicUserIdentity>> l = new ArrayList<IModel<PublicUserIdentity>>();
            Iterator<PublicUserIdentity> it = model.getObject().iterator();
            while (it.hasNext()) {
                PublicUserIdentity identity = it.next();
                l.add(new DaoLoadableModel<PublicUserIdentity, String>(identity, identity.getIdentity()) {

                    @Override
                    protected PublicUserIdentity load() {
                        return (PublicUserIdentity) _publicIdentityDao.findById(getKey());
                    }
                });

            }
            return l.iterator();
        }

        @Override
        protected void populateItem(Item<PublicUserIdentity> item2) {
            PublicUserIdentity identity = item2.getModelObject();
            MarkupContainer link = new BookmarkablePageLink("identity", EditPublicUserIdPage.class,
                    new PageParameters("id=" + identity.getIdentity()));
            item2.add(link);
            link.add(new Label("name", identity.getIdentity()));

            if (identity.isDefaultIdentity()) {
                item2.add(new WebMarkupContainer("default"));
                item2.add(new WebMarkupContainer("makeDefault").setVisible(false));
            } else {
                item2.add(new WebMarkupContainer("default").setVisible(false));
                item2.add(new AjaxFallbackLink("makeDefault", item2.getModel()) {

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        PublicUserIdentity identity = (PublicUserIdentity) getDefaultModelObject();
                        identity.setDefaultIdentity(true);
                        SortedSet<PublicUserIdentity> ids = (SortedSet<PublicUserIdentity>) getParent()
                                .getParent().getDefaultModelObject();

                        Iterator<PublicUserIdentity> it = ids.iterator();
                        while (it.hasNext()) {
                            PublicUserIdentity publicId = it.next();
                            publicId.setDefaultIdentity(identity == publicId);
                            _publicIdentityDao.save(publicId);
                        }
                        resort(ids);

                        if (target != null) {
                            target.addComponent(getPage().get("form:container"));
                            target.addComponent(getPage().get("feedback"));
                        }
                    }
                });
            }
        }

    };
}

From source file:org.lbogdanov.poker.web.page.MySessionsPage.java

License:Apache License

/**
 * Creates a new instance of <code>MySessionsPage</code> page.
 *//*from   w  w w  . j av  a 2s.  co  m*/
@SuppressWarnings("unchecked")
public MySessionsPage() {
    final SessionsProvider dataProvider = new SessionsProvider();
    dataProvider.setSort("created", SortOrder.DESCENDING); // default sort: created, desc
    List<AbstractColumn<Session, String>> columns = Arrays.asList(new Column("session.name", "name", "name") {

        @Override
        public void populateItem(Item<ICellPopulator<Session>> item, String compId, IModel<Session> model) {
            Session session = model.getObject();
            PageParameters params = new PageParameters().add("code", session.getCode());
            Link<?> go = new BookmarkablePageLink<Void>("goto", SessionPage.class, params);
            go.add(new BodylessLabel("name", session.getName()));
            item.add(new Fragment(compId, "nameLink", MySessionsPage.this).add(go));
        }

    }, new Column("session.description", null, "description"),
            new Column("session.created", "created", "created") {

                @Override
                @SuppressWarnings("rawtypes")
                public IModel<Object> getDataModel(IModel<Session> rowModel) {
                    Date created = (Date) super.getDataModel(rowModel).getObject();
                    String formatted = DateFormat
                            .getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale())
                            .format(created);
                    return new Model(formatted);
                }

            }, new Column("session.author", "author", "author"),
            new AbstractColumn<Session, String>(new ResourceModel("session.actions")) {

                @Override
                public void populateItem(Item<ICellPopulator<Session>> item, String compId,
                        IModel<Session> model) {
                    Link<?> delete = new AjaxFallbackLink<Session>("delete", model) {

                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            sessionService.delete(getModelObject());
                            dataProvider.invalidate();
                            if (target != null) {
                                target.add(sessionsTable);
                            }
                        }

                        @Override
                        protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
                            super.updateAjaxAttributes(attributes);
                            AjaxCallListener listener = new AjaxCallListener();
                            listener.onPrecondition("return Poker.confirm(attrs.c);");
                            attributes.getAjaxCallListeners().add(listener);
                        }

                    };
                    item.add(new Fragment(compId, "actions", MySessionsPage.this).add(delete));
                }

                @Override
                public String getCssClass() {
                    return "actions";
                }

            });
    sessionsTable = new DataTable<Session, String>("sessions", columns, dataProvider, ITEMS_PER_PAGE.get(0));
    sessionsTable.addTopToolbar(new AjaxFallbackHeadersToolbar<String>(sessionsTable, dataProvider) {

        @Override
        protected WebMarkupContainer newSortableHeader(String borderId, String property,
                ISortStateLocator<String> locator) {
            return new AjaxFallbackOrderByBorder<String>(borderId, property, locator, getAjaxCallListener()) {

                @Override
                protected void onAjaxClick(AjaxRequestTarget target) {
                    target.add(getTable());
                }

                @Override
                protected void onSortChanged() {
                    dataProvider.invalidate();
                    getTable().setCurrentPage(0);
                }

            };
        }

    });
    sessionsTable.addBottomToolbar(new AjaxNavigationToolbar(sessionsTable) {

        @Override
        protected PagingNavigator newPagingNavigator(String navigatorId, final DataTable<?, ?> table) {
            return new BootstrapPagingNavigator(navigatorId, table) {

                @Override
                protected void onAjaxEvent(AjaxRequestTarget target) {
                    target.add(table);
                }

            };
        }

    });
    sessionsTable.addBottomToolbar(new NoRecordsToolbar(sessionsTable));

    TextField<?> sessionName = new TextField<String>("sessionName",
            PropertyModel.<String>of(dataProvider, "sessionName"));
    sessionName.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            dataProvider.invalidate();
            target.add(sessionsTable);
        }

        @Override
        protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
            super.updateAjaxAttributes(attributes);
            ThrottlingSettings throttling = new ThrottlingSettings("sessionName", Duration.milliseconds(300),
                    true);
            attributes.setThrottlingSettings(throttling);
        }

    });
    DropDownChoice<?> pageSize = new DropDownChoice<Long>("pageSize",
            PropertyModel.<Long>of(sessionsTable, "itemsPerPage"), ITEMS_PER_PAGE);
    pageSize.add(new OnChangeAjaxBehavior() {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            dataProvider.invalidate();
            target.add(sessionsTable);
        }

    });
    add(sessionsTable.setOutputMarkupId(true), sessionName, pageSize);
}