Example usage for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException

List of usage examples for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException

Introduction

In this page you can find the example usage for org.apache.wicket RestartResponseAtInterceptPageException RestartResponseAtInterceptPageException.

Prototype

public RestartResponseAtInterceptPageException(Class<? extends Page> interceptPageClass) 

Source Link

Document

Redirects to the specified intercept page, this will result in a bookmarkable redirect.

Usage

From source file:guru.mmp.application.web.WebAuthorizationStrategy.java

License:Apache License

private boolean checkAccess(Class<?> componentClass) {
    if (guru.mmp.application.web.pages.WebPage.class.isAssignableFrom(componentClass)) {
        WebPageSecurity webPageSecurity = componentClass.getAnnotation(WebPageSecurity.class);

        if (webPageSecurity != null) {
            String[] webPageSecurityFunctions = webPageSecurity.value();

            if (webPageSecurityFunctions.length > 0) {
                WebSession session = (WebSession) WebSession.get();

                if ((session == null) || (!session.isUserLoggedIn())) {
                    logger.warn("The anonymous user does not have access to the function(s): "
                            + StringUtil.delimit(webPageSecurityFunctions, ","));

                    if (session != null) {
                        session.invalidate();
                    }//from   w w w. j av a  2 s . c  o  m

                    throw new RestartResponseAtInterceptPageException(
                            ((WebApplication) session.getApplication()).getLogoutPage());
                }

                if (session.hasAccessToFunctions(webPageSecurityFunctions)) {
                    return true;
                }

                logger.warn("The user ("
                        + (StringUtil.isNullOrEmpty(session.getUsername()) ? "Unknown" : session.getUsername())
                        + ") does not have access to the function(s): "
                        + StringUtil.delimit(webPageSecurityFunctions, ","));

                if (Debug.inDebugMode()) {
                    logger.info("The user ("
                            + (StringUtil.isNullOrEmpty(session.getUsername()) ? "Unknown"
                                    : session.getUsername())
                            + ") has access to the following functions: "
                            + ((session.getFunctionCodes().size() == 0) ? "None"
                                    : StringUtil.delimit(session.getFunctionCodes(), ",")));
                }

                return false;
            }
        } else {
            SecureAnonymousWebPage secureAnonymousWebPage = componentClass
                    .getAnnotation(SecureAnonymousWebPage.class);

            if (secureAnonymousWebPage != null) {
                WebSession session = (WebSession) WebSession.get();

                if ((session == null) || (!session.isUserLoggedIn())) {
                    if (session != null) {
                        session.invalidate();
                    }

                    throw new RestartResponseAtInterceptPageException(
                            ((WebApplication) session.getApplication()).getLogoutPage());
                }
            }
        }
    }

    return true;
}

From source file:info.jtrac.wicket.ItemViewPage.java

License:Apache License

private void addComponents() {
    final ItemSearch itemSearch = JtracSession.get().getItemSearch();
    add(new ItemRelatePanel("relate", true, itemSearch));
    Link link = new Link("back") {
        @Override/*from   w ww .j  av a2  s.c om*/
        public void onClick() {
            itemSearch.setSelectedItemId(getItem().getId());
            if (itemSearch.getRefId() != null) {
                // user had entered item id directly, go back to search page
                setResponsePage(new ItemSearchFormPage(itemSearch));
            } else {
                setResponsePage(new ItemListPage(itemSearch));
            }
        }
    };
    if (itemSearch == null) {
        link.setVisible(false);
    }

    add(link);

    boolean isRelate = itemSearch != null && itemSearch.getRelatingItemRefId() != null;

    User user = getPrincipal();

    if (!user.isAllocatedToSpace(getItem().getSpace().getId())) {
        logger.debug("user is not allocated to space");
        throw new RestartResponseAtInterceptPageException(ErrorPage.class);
    }

    // Edit: Only if there is no history (related item) of the Item
    boolean hasHistory = getItem().hasHistory();

    // Edit: Also the owner of the item should change it.
    boolean canBeEdited = (getItem().wasLoggedBy(user) && getJtrac().isItemEditAllowed() && !hasHistory)
            || user.isSuperUser() || user.isAdminForSpace(getItem().getSpace().getId());
    add(new Link("edit") {
        @Override
        public void onClick() {
            setResponsePage(new ItemFormPage(getItem().getId()));
        }
    }.setVisible(canBeEdited));
    add(new ItemViewPanel("itemViewPanel", createItemModel(), isRelate || user.getId() == 0));

    if (user.isGuestForSpace(getItem().getSpace()) || isRelate) {
        add(new WebMarkupContainer("itemViewFormPanel").setVisible(false));
    } else {
        add(new ItemViewFormPanel("itemViewFormPanel", getItem()));
    }
}

From source file:info.jtrac.wicket.JtracApplication.java

License:Apache License

@Override
public void init() {
    super.init();

    /*//from   w w w.  j  a v a 2  s . c o m
     * Get hold of spring managed service layer (see BasePage, BasePanel,
     * etc. for how it is used).
     */
    ServletContext sc = getServletContext();
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
    jtrac = (Jtrac) applicationContext.getBean("jtrac");

    /*
     * Check if acegi-cas authentication is being used, get reference to
     * object to be used by Wicket authentication to redirect to right
     * pages for login/logout.
     */
    try {
        jtracCasProxyTicketValidator = (JtracCasProxyTicketValidator) applicationContext
                .getBean("casProxyTicketValidator");
        logger.info("casProxyTicketValidator retrieved from application " + "context: "
                + jtracCasProxyTicketValidator);
    } catch (NoSuchBeanDefinitionException nsbde) {
        logger.debug(nsbde.getMessage());
        logger.info("casProxyTicketValidator not found in application "
                + "context, CAS single-sign-on is not being used");
    }

    /*
     * Delegate Wicket i18n support to spring i18n
     */
    getResourceSettings().addStringResourceLoader(new IStringResourceLoader() {
        /* (non-Javadoc)
        * @see org.apache.wicket.resource.loader.IStringResourceLoader#loadStringResource(java.lang.Class, java.lang.String, java.util.Locale, java.lang.String)
        */
        @Override
        public String loadStringResource(@SuppressWarnings("rawtypes") Class clazz, String key, Locale locale,
                String style) {
            try {
                return applicationContext.getMessage(key, null,
                        locale == null ? Session.get().getLocale() : locale);
            } catch (Exception e) {
                /*
                 * For performance, Wicket expects null instead of
                 * throwing an exception and Wicket may try to
                 * re-resolve using prefixed variants of the key.
                 */
                return null;
            }
        }

        /* (non-Javadoc)
        * @see org.apache.wicket.resource.loader.IStringResourceLoader#loadStringResource(org.apache.wicket.Component, java.lang.String)
        */
        @Override
        public String loadStringResource(Component component, String key) {
            String value = loadStringResource(null, key, component == null ? null : component.getLocale(),
                    null);
            if (logger.isDebugEnabled() && value == null) {
                logger.debug("i18n failed for key: '" + key + "', component: " + component);
            }
            return value;
        }
    });

    getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {
        /* (non-Javadoc)
        * @see org.apache.wicket.authorization.IAuthorizationStrategy#isActionAuthorized(org.apache.wicket.Component, org.apache.wicket.authorization.Action)
        */
        @Override
        public boolean isActionAuthorized(Component c, Action a) {
            return true;
        }

        /* (non-Javadoc)
        * @see org.apache.wicket.authorization.IAuthorizationStrategy#isInstantiationAuthorized(java.lang.Class)
        */
        @Override
        public boolean isInstantiationAuthorized(@SuppressWarnings("rawtypes") Class clazz) {
            if (BasePage.class.isAssignableFrom(clazz)) {
                if (JtracSession.get().isAuthenticated()) {
                    return true;
                }
                if (jtracCasProxyTicketValidator != null) {
                    /*
                     * ============================================
                     * Attempt CAS authentication
                     * ============================================
                     */
                    logger.debug("checking if context contains CAS authentication");
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                    if (authentication != null && authentication.isAuthenticated()) {
                        logger.debug("security context contains CAS authentication, initializing session");
                        JtracSession.get().setUser((User) authentication.getPrincipal());
                        return true;
                    }
                }

                /*
                 * ================================================
                 * Attempt remember-me auto login
                 * ================================================
                 */
                if (attemptRememberMeAutoLogin()) {
                    return true;
                }

                /*
                 * =================================================
                 * Attempt guest access if there are "public" spaces
                 * =================================================
                 */
                List<Space> spaces = getJtrac().findSpacesWhereGuestAllowed();
                if (spaces.size() > 0) {
                    logger.debug(spaces.size() + " public space(s) available, initializing guest user");
                    User guestUser = new User();
                    guestUser.setLoginName("guest");
                    guestUser.setName("Guest");
                    for (Space space : spaces) {
                        guestUser.addSpaceWithRole(space, Role.ROLE_GUEST);
                    }

                    JtracSession.get().setUser(guestUser);
                    // and proceed
                    return true;
                }

                /*
                 * Not authenticated, go to login page.
                 */
                logger.debug("not authenticated, forcing login, " + "page requested was " + clazz.getName());
                if (jtracCasProxyTicketValidator != null) {
                    String serviceUrl = jtracCasProxyTicketValidator.getServiceProperties().getService();
                    String loginUrl = jtracCasProxyTicketValidator.getLoginUrl();
                    logger.debug("cas authentication: service URL: " + serviceUrl);
                    String redirectUrl = loginUrl + "?service=" + serviceUrl;
                    logger.debug("attempting to redirect to: " + redirectUrl);
                    throw new RestartResponseAtInterceptPageException(new RedirectPage(redirectUrl));
                } else {
                    throw new RestartResponseAtInterceptPageException(LoginPage.class);
                }
            }
            return true;
        }
    });

    /*
     * Friendly URLs for selected pages
     */
    if (jtracCasProxyTicketValidator != null) {
        mountBookmarkablePage("/login", CasLoginPage.class);
        /*
         * This matches the value set in:
         * WEB-INF/applicationContext-acegi-cas.xml
         */
        mountBookmarkablePage("/cas/error", CasLoginErrorPage.class);
    } else {
        mountBookmarkablePage("/login", LoginPage.class);
    }

    mountBookmarkablePage("/logout", LogoutPage.class);
    mountBookmarkablePage("/svn", SvnStatsPage.class);
    mountBookmarkablePage("/options", OptionsPage.class);
    mountBookmarkablePage("/item/form", ItemFormPage.class);

    /*
     * Bookmarkable URL for search and search results
     */
    mount(new QueryStringUrlCodingStrategy("/item/search", ItemSearchFormPage.class));
    mount(new QueryStringUrlCodingStrategy("/item/list", ItemListPage.class));

    /*
     * Bookmarkable URL for viewing items
     */
    mount(new IndexedParamUrlCodingStrategy("/item", ItemViewPage.class));
}

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

License:Apache License

public EaterViewPage(PageParameters pageParameters) {
    add(getFeedbackPanel());/*from ww w  .  j a  v  a  2 s .c om*/
    String eaterId = pageParameters.get(YoueatHttpParams.YOUEAT_ID).toString("");
    if (StringUtils.isBlank(eaterId)) {
        throw new RestartResponseAtInterceptPageException(getApplication().getHomePage());
    }

    eater = eaterService.getByID(eaterId);

    add(new Label("eater", eater.getFirstname() + " " + eater.getLastname()));
    add(ImagesAvatar.getAvatar("avatar", eater, this.getPage(), true));
    // User activities
    try {
        activities = activityRistoranteService.findByEater(eater, activityPagingUser.getFirstResult(),
                activityPagingUser.getMaxResults());
    } catch (YoueatException e) {
        activities = new ArrayList<ActivityRistorante>();
        error(new StringResourceModel("error.errorGettingListActivities", this, null).getString());
    }

    activitiesListContainer = new WebMarkupContainer("activitiesListContainer");
    activitiesListContainer.setOutputMarkupId(true);
    add(activitiesListContainer);
    activitiesList = new ActivitiesListView("activitiesList", activities, false);
    add(activitiesList);

    activitiesList.setOutputMarkupId(true);
    activitiesListContainer.add(activitiesList);
    AjaxFallbackLink<String> moreActivitiesLink = new AjaxFallbackLink<String>("moreActivities") {
        @Override
        public void onClick(AjaxRequestTarget target) {
            activityPagingUser.addNewPage();
            try {
                activities.addAll(activityRistoranteService.findByEater(eater,
                        activityPagingUser.getFirstResult(), activityPagingUser.getMaxResults()));
                if (target != null) {
                    target.addComponent(activitiesListContainer);
                }
            } catch (YoueatException e) {
                error(new StringResourceModel("error.errorGettingListActivities", this, null).getString());
            }
        }
    };
    activitiesListContainer.add(moreActivitiesLink);
    ModalWindow sendMessageMW = SendMessageModalWindow.getNewModalWindow("sendMessagePanel");
    add(sendMessageMW);
    EaterRelation relation = eaterRelationService.getRelation(getLoggedInUser(), eater);
    add(new SendMessageButton("sendMessage", getLoggedInUser(), eater, relation, sendMessageMW));
    sendFriendRequest = new SendFriendRequestButton("sendFriendRequest", getLoggedInUser(), eater, relation);
    add(sendFriendRequest);
    startFollow = new StartFollowEaterButton("startFollow", getLoggedInUser(), eater, relation);
    add(startFollow);

    int numberOfFriends = eaterRelationService.countFriends(eater);
    add(new Label("numberOfFriends", new Model<Integer>(numberOfFriends)).setVisible(numberOfFriends > 0));
    PropertyListView<EaterRelation> friendsList = new PropertyListView<EaterRelation>("friendsList",
            new RelationsModel()) {

        @Override
        protected void populateItem(final ListItem<EaterRelation> item) {

            BookmarkablePageLink linkToUser = new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    new PageParameters(
                            YoueatHttpParams.YOUEAT_ID + "=" + item.getModelObject().getToUser().getId()));
            item.add(linkToUser);
            linkToUser.add(new Label("eater.name", item.getModelObject().getToUser().toString()));
            item.add(ImagesAvatar.getAvatar("avatar", item.getModelObject().getToUser(), this.getPage(), true));
        }
    };
    friendsList.setVisible(numberOfFriends > 0);
    add(friendsList);

    int numberCommonFriends = eaterRelationService.countCommonFriends(getLoggedInUser(), eater);
    add(new Label("numberCommonFriend", new Model<Integer>(numberCommonFriends))
            .setVisible(numberCommonFriends > 0));
    PropertyListView<Eater> commonFriendsList = new PropertyListView<Eater>("commonFriendsList",
            new CommonFriends(getLoggedInUser(), eater)) {
        @Override
        protected void populateItem(final ListItem<Eater> item) {

            BookmarkablePageLink linkToUser = new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    new PageParameters(YoueatHttpParams.YOUEAT_ID + "=" + item.getModelObject().getId()));
            item.add(linkToUser);
            linkToUser.add(new Label("eater.name", item.getModelObject().toString()));
            item.add(ImagesAvatar.getAvatar("avatar", item.getModelObject(), this.getPage(), true));
        }
    };
    commonFriendsList.setVisible(numberCommonFriends > 0);
    add(commonFriendsList);

    add(new RistosListView("favoriteRistosList", activityRistoranteService.findFavoriteRisto(eater, 0)));

    add(new RistosListView("contributionsList", activityRistoranteService.findContributedByEater(eater, 8)));
    final SuggestNewFriendModalWindow toFriendsModalWindow = new SuggestNewFriendModalWindow(
            "suggestToFriendModalWindow");
    add(toFriendsModalWindow);

    add(new SuggestNewFriendButton("suggestToFriends", eater, toFriendsModalWindow));

}

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

License:Apache License

/**
 * Constructor that is invoked when page is invoked without a session.
 * //from   w  ww  .  j a va2s . c om
 * @throws YoueatException
 */
public MessagePage(PageParameters parameters) throws YoueatException {
    super();
    final String dialogId = parameters.get(YoueatHttpParams.DIALOG_ID).toString("");
    if (StringUtils.isBlank(dialogId)) {
        throw new RestartResponseAtInterceptPageException(getApplication().getHomePage());
    }

    add(getFeedbackPanel());

    dialog = dialogService.readDiscussion(dialogId, getLoggedInUser());

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

        @Override
        protected void populateItem(final ListItem<Message> item) {
            item.add(new BookmarkablePageLink("linkToUser", EaterViewPage.class,
                    new PageParameters(
                            YoueatHttpParams.YOUEAT_ID + "=" + item.getModelObject().getSender().getId()))
                                    .add(new Label(Message.SENDER_FIELD)));
            item.add(new Label(Message.SENTTIME_FIELD));
            String body = templateUtil.resolveTemplateEater(item.getModelObject(), true, null, getWebPage());
            item.add(new Label(Message.BODY_FIELD, body).setEscapeModelStrings(false));
            item.add(new Label(Message.TITLE_FIELD));
            item.add(ImagesAvatar.getAvatar("avatar", item.getModelObject().getSender(), this.getPage(), true));
        }
    };
    messageListContainer.add(messageList);

    final Form<Message> sendMessageForm = new Form<Message>("sendMessageForm",
            new CompoundPropertyModel<Message>(getNewMessage()));
    sendMessageForm.setOutputMarkupId(true);
    add(sendMessageForm);
    sendMessageForm.add(new TextArea<String>("body").setRequired(true)
            .add(StringValidator.maximumLength(Message.BODY_MAX_LENGTH)));
    sendMessageForm.add(new AjaxFallbackButton("submit", sendMessageForm) {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            Message msgToSend = (Message) form.getModelObject();
            dialogService.reply(msgToSend, dialog, dialog.checkCounterpart(getLoggedInUser()), getWebPage());
            dialog = dialogService.readDiscussion(dialogId, getLoggedInUser());
            sendMessageForm.setModelObject(getNewMessage());
            if (target != null) {
                target.addComponent(getFeedbackPanel());
                target.addComponent(sendMessageForm);
                target.addComponent(messageListContainer);
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            // for the moment I don't want show the error message
            target.addComponent(getFeedbackPanel());
        }
    });

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

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

License:Apache License

/**
 * /*from w  w  w.  j  av a 2s.  c o  m*/
 * @param parameters
 */
public RistoranteEditAddressPage(PageParameters parameters) {

    String ristoranteId = parameters.get(YoueatHttpParams.RISTORANTE_ID).toString("");
    if (StringUtils.isNotBlank(ristoranteId)) {
        this.ristorante = ristoranteService.getByID(ristoranteId);
    } else {
        throw new RestartResponseAtInterceptPageException(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 TextField<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.MOBILE_PHONE_NUMBER));
    form.add(new TextField<String>(Ristorante.FAX_NUMBER));

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

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

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

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

License:Apache License

/**
 * //from  w w w.ja  v a2  s. c o  m
 * @param parameters
 * @throws YoueatException
 */
public RistoranteEditDataPage(PageParameters parameters) throws YoueatException {

    String ristoranteId = parameters.get(YoueatHttpParams.RISTORANTE_ID).toString("");
    if (StringUtils.isNotBlank(ristoranteId)) {
        this.ristorante = ristoranteService.getByID(ristoranteId);
    } else {
        throw new RestartResponseAtInterceptPageException(getApplication().getHomePage());
    }
    actualDescriptionLanguage = getInitialLanguage();
    ristorante = ristorante.addDescLangIfNotPresent(actualDescriptionLanguage);
    ristorante = ristorante.addBlackboardLangIfNotPresent(actualDescriptionLanguage);
    form = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante));
    form.setOutputMarkupId(true);
    form.add(new RequiredTextField<String>(Ristorante.NAME));

    form.add(new TextField<String>(Ristorante.WWW));
    form.add(new TextField<String>(Ristorante.EMAIL).add(EmailAddressValidator.getInstance()));
    form.add(new TagBox(new Model<String>(""), "tagBox", ristorante));

    // form.add(new CheckBox("types.ristorante"));
    // form.add(new CheckBox("types.pizzeria"));
    // form.add(new CheckBox("types.bar"));

    form.add(new ListView<Tag>(Ristorante.TAGS) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<Tag> item) {
            item.add(new Label("tagItem", item.getModelObject().getTag()));
            item.add(new AjaxFallbackLink<String>("buttonTagItemRemove") {
                @Override
                public void onClick(AjaxRequestTarget target) {
                    getList().remove(getParent().getDefaultModelObject());
                    if (target != null) {
                        target.addComponent(form);
                    }
                }
            });
        }
    });
    descriptionLinksContainer = new WebMarkupContainer("descriptionLinksContainer");
    descriptionLinksContainer.setOutputMarkupId(true);
    form.add(descriptionLinksContainer);
    ListView<Language> descriptionsLinks = new ListView<Language>("descriptionLinks",
            languageService.getAll()) {
        @Override
        protected void populateItem(final ListItem<Language> item) {

            if (actualDescriptionLanguage.getCountry().equals(item.getModelObject().getCountry())) {
                item.add(new AttributeAppender("class", new Model<String>("ui-tabs-selected ui-state-active"),
                        " "));
            }

            item.add(new AjaxFallbackButton("descriptionLink", form) {

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    actualDescriptionLanguage = item.getModelObject();
                    ristorante = ristorante.addDescLangIfNotPresent(actualDescriptionLanguage);
                    ristorante = ristorante.addBlackboardLangIfNotPresent(actualDescriptionLanguage);
                    descriptions.removeAll();
                    if (target != null) {
                        target.addComponent(descriptionsContainer);
                        target.addComponent(descriptionLinksContainer);
                        target.addComponent(restaurateurBlackboardsContainer);
                    }
                }

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    // TODO 1.5 Auto-generated method stub
                }
            }.add(new Label("linkName", getString(item.getModelObject().getCountry()))));
        }
    };
    descriptionLinksContainer.add(descriptionsLinks);
    descriptionsContainer = new WebMarkupContainer("descriptionsContainer");
    descriptionsContainer.setOutputMarkupId(true);
    form.add(descriptionsContainer);
    descriptions = new ListView<RistoranteDescriptionI18n>("descriptions") {
        @Override
        protected void populateItem(ListItem<RistoranteDescriptionI18n> item) {
            boolean visible = actualDescriptionLanguage.equals(item.getModelObject().getLanguage());
            item.add(new TextArea<String>(RistoranteDescriptionI18n.DESCRIPTION,
                    new PropertyModel<String>(item.getModelObject(), RistoranteDescriptionI18n.DESCRIPTION))
                            .setVisible(visible));
        }
    };
    descriptions.setReuseItems(false);
    descriptions.setOutputMarkupId(true);
    descriptionsContainer.add(descriptions);
    // form.add(new DropDownChoice<EaterProfile>("userProfile", new
    // ArrayList<EaterProfile>(userProfileService.getAll()), new UserProfilesList()).setOutputMarkupId(true));

    //RestaurateurBlackboards
    restaurateurBlackboardsContainer = new WebMarkupContainer("restaurateurBlackboardsContainer");
    form.add(restaurateurBlackboardsContainer);
    restaurateurBlackboardsContainer.setOutputMarkupId(true);
    form.add(restaurateurBlackboardsContainer);
    restaurateurBlackboards = new ListView<RestaurateurBlackboardI18n>("restaurateurBlackboards") {
        @Override
        protected void populateItem(ListItem<RestaurateurBlackboardI18n> item) {
            boolean visible = actualDescriptionLanguage.equals(item.getModelObject().getLanguage());
            TextArea<String> blackboard = new TextArea<String>("restaurateurBlackboard",
                    new PropertyModel<String>(item.getModelObject(), RestaurateurBlackboardI18n.BLACKBOARD));
            blackboard.setVisible(visible);
            blackboard.add(new AttributeAppender("class",
                    new Model("blackboard_" + getInitialLanguage().getLanguage()), " "));
            item.add(blackboard);
        }
    };
    restaurateurBlackboards.setReuseItems(false);
    restaurateurBlackboards.setOutputMarkupId(true);
    restaurateurBlackboardsContainer.add(restaurateurBlackboards);
    //Shows restaurateurBlackboards only to the owner
    if (getLoggedInUser() != null && getLoggedInUser().equals(ristorante.getRestaurateur())) {
        restaurateurBlackboardsContainer.setVisible(true);
    } else {
        restaurateurBlackboardsContainer.setVisible(false);
    }

    form.add(new AjaxFallbackButton("addTag", form) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form) {
            String tagValue = ((TagBox) form.get("tagBox")).getModelObject();
            if (StringUtils.isNotBlank(tagValue)) {
                Ristorante risto = ((Ristorante) form.getModelObject());
                try {
                    risto.getTags().add(tagService.insert(tagValue));
                    form.setModelObject(risto);
                    if (target != null) {
                        target.addComponent(form);
                    }
                } catch (YoueatException e) {
                    error("genericErrorMessage");
                    if (target != null) {
                        target.addComponent(getFeedbackPanel());
                    }
                }
            }
            // after clean up the tagBox
            ((TagBox) form.get("tagBox")).setModelObject(null);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            if (target != null) {
                target.addComponent(getFeedbackPanel());
            }
        }
    });

    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));
    ButtonOpenRisto buttonOpenAddedRisto = new ButtonOpenRisto("buttonOpenAddedRisto",
            new Model<Ristorante>(ristorante), true);
    add(buttonOpenAddedRisto);

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

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

License:Apache License

/**
 * @param parameters//from w ww . j a va 2 s .  c o  m
 * @throws YoueatException
 */
public RistoranteEditPicturePage(PageParameters parameters) throws YoueatException {
    add(getFeedbackPanel());
    ristoranteId = parameters.get(YoueatHttpParams.RISTORANTE_ID).toString("");
    if (StringUtils.isBlank(ristoranteId)) {
        throw new RestartResponseAtInterceptPageException(getApplication().getHomePage());
    }

    pictForm = new Form<Ristorante>("ristorantePicturesForm", new LoadableDetachableModel<Ristorante>() {
        @Override
        protected Ristorante load() {
            return ristoranteService.getByID(ristoranteId);
        }
    });
    add(pictForm);
    // pictForm.setOutputMarkupId(true);
    pictForm.setMultiPart(true);
    pictForm.setMaxSize(Bytes.megabytes(1));
    FileUploadField uploadField = new FileUploadField("uploadField");
    pictForm.add(uploadField);
    pictForm.add(new UploadProgressBar("progressBar", pictForm, uploadField));
    pictForm.add(new SubmitButton("submitForm", pictForm));

    picturesList = new ListView<RistorantePicture>("picturesList", new PicturesModel()) {
        @Override
        protected void populateItem(final ListItem<RistorantePicture> item) {
            // Button disabled, because the getPicture is not yet implemented
            item.add(new SubmitLink("publish-unpublish", pictForm) {
                @Override
                public void onSubmit() {
                    item.getModelObject().setActive(!item.getModelObject().isActive());
                    try {
                        ristorantePictureService.save(item.getModelObject());
                    } catch (YoueatException e) {
                        error(getString("genericErrorMessage"));
                    }
                }

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    if (item.getModelObject().isActive()) {
                        tag.getAttributes().put("title", getString("button.unpublish"));
                        tag.getAttributes().put("class", "unpublishPictureButton");
                    } else {
                        tag.getAttributes().put("title", getString("button.publish"));
                        tag.getAttributes().put("class", "publishPictureButton");
                    }
                }
            }.setVisible(false));
            item.add(new SubmitLink("remove", pictForm) {
                @Override
                public void onSubmit() {
                    try {
                        RistorantePicture picture = item.getModelObject();
                        Ristorante risto = ((Ristorante) getForm().getModelObject());
                        risto.getPictures().remove(picture);
                        ristoranteService.updateNoRevision(risto);
                        ristorantePictureService.remove(picture);
                        picturesList.setModel(new PicturesModel());
                    } catch (YoueatException e) {
                        error(getString("genericErrorMessage"));
                    }
                }
            });
            Link<RistorantePicture> imageLink = new Link<RistorantePicture>("pictureLink", item.getModel()) {
                @Override
                public void onClick() {
                    setResponsePage(new ImageViewPage(getModelObject().getPicture()));
                }
            };
            imageLink.add(ImageRisto.getThumbnailImage("picture", item.getModelObject().getPicture(), false));
            item.add(imageLink);
        }
    };
    picturesList.setOutputMarkupId(true);
    picturesList.setReuseItems(false);
    picturesListContainer = new WebMarkupContainer("picturesListContainer");
    picturesListContainer.setOutputMarkupId(true);
    pictForm.add(picturesListContainer);
    picturesListContainer.add(picturesList);

    ButtonOpenRisto buttonOpenAddedRisto = new ButtonOpenRisto("buttonOpenAddedRisto", pictForm.getModel(),
            true);
    add(buttonOpenAddedRisto);

    ButtonOpenRisto buttonOpenAddedRistoRight = new ButtonOpenRisto("buttonOpenAddedRistoRight",
            pictForm.getModel(), true);
    add(buttonOpenAddedRistoRight);
}

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

License:Apache License

/**
 * Constructor that is invoked when page is invoked without a session.
 * //from www  . j  av  a 2 s  .  com
 * @throws YoueatException
 */
public RistoranteViewPage(PageParameters parameters) throws YoueatException {
    actualDescriptionLanguage = getInitialLanguage();
    String ristoranteId = parameters.get(YoueatHttpParams.RISTORANTE_ID).toString("");
    if (StringUtils.isNotBlank(ristoranteId)) {
        this.ristorante = ristoranteService.getByID(ristoranteId);
    } else {
        throw new RestartResponseAtInterceptPageException(getApplication().getHomePage());
    }
    appendToPageTile(" " + ristorante.getName() + ", " + ristorante.getCity().getName());
    ristorante = ristorante.addDescLangIfNotPresent(actualDescriptionLanguage);
    ristorante = ristorante.addBlackboardLangIfNotPresent(actualDescriptionLanguage);
    formRisto = new Form<Ristorante>("ristoranteForm", new CompoundPropertyModel<Ristorante>(ristorante));
    add(formRisto);
    formRisto.setOutputMarkupId(true);
    formRisto.add(new Label(Ristorante.NAME));

    formRisto.add(new SmartLinkLabel(Ristorante.WWW));
    formRisto.add(new SmartLinkLabel(Ristorante.EMAIL));
    formRisto.add(new ListView<Tag>(Ristorante.TAGS) {

        @Override
        protected void populateItem(ListItem<Tag> item) {
            StringBuffer tag = new StringBuffer(item.getModelObject().getTag());
            if (item.getIndex() < ristorante.getTags().size() - 1) {
                tag.append(",");
            }
            item.add(new Label("tagItem", tag.toString()));
        }
    });
    descriptionLinksContainer = new WebMarkupContainer("descriptionLinksContainer");
    descriptionLinksContainer.setOutputMarkupId(true);
    formRisto.add(descriptionLinksContainer);
    ListView<Language> descriptionsLinks = new ListView<Language>("descriptionLinks",
            languageService.getAll()) {
        @Override
        protected void onComponentTag(ComponentTag tag) {
        };

        @Override
        protected void populateItem(final ListItem<Language> item) {
            if (actualDescriptionLanguage.getCountry().equals(item.getModelObject().getCountry())) {
                item.add(new AttributeAppender("class", new Model<String>("ui-tabs-selected ui-state-active"),
                        " "));
            }
            item.add(new AjaxFallbackButton("descriptionLink", formRisto) {

                @Override
                protected void onComponentTag(ComponentTag tag) {
                    super.onComponentTag(tag);
                    boolean langpresent = ristorante.checkDesctiption(item.getModelObject());
                    HashMap<String, String> tagAttrs = new HashMap<String, String>();
                    if (!langpresent) {
                        tagAttrs.put("title", getString("descriptionNotAvailableLang"));
                        tagAttrs.put("class", "descriptionNotAvailableLang");
                    }
                    tag.getAttributes().putAll(tagAttrs);
                }

                @Override
                protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                    actualDescriptionLanguage = item.getModelObject();
                    ristorante = ristorante.addDescLangIfNotPresent(actualDescriptionLanguage);
                    formRisto.setModelObject(ristorante);
                    descriptions.removeAll();
                    if (target != null) {
                        target.addComponent(descriptionsContainer);
                        target.addComponent(descriptionLinksContainer);
                        target.addComponent(restaurateurBlackboardsContainer);
                    }
                }

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    // TODO 1.5 Auto-generated method stub

                }
            }.add(new Label("linkName", getString(item.getModelObject().getCountry()))));
        }
    };
    descriptionLinksContainer.add(descriptionsLinks);
    descriptionsContainer = new WebMarkupContainer("descriptionsContainer");
    descriptionsContainer.setOutputMarkupId(true);
    formRisto.add(descriptionsContainer);
    descriptions = new ListView<RistoranteDescriptionI18n>("descriptions", new DescriptionsModel()) {
        @Override
        protected void populateItem(ListItem<RistoranteDescriptionI18n> item) {
            boolean visible = actualDescriptionLanguage.equals(item.getModelObject().getLanguage());
            if (item.getModelObject().getDescription() == null
                    || StringUtils.isBlank(item.getModelObject().getDescription())) {
                item.add(new Label(RistoranteDescriptionI18n.DESCRIPTION,
                        getString("descriptionNotAvailableLang")).setVisible(visible)
                                .setOutputMarkupPlaceholderTag(true));
            } else {
                item.add(new MultiLineLabel(RistoranteDescriptionI18n.DESCRIPTION,
                        new PropertyModel<String>(item.getModelObject(), RistoranteDescriptionI18n.DESCRIPTION))
                                .setVisible(visible).setOutputMarkupPlaceholderTag(true));
            }
        }
    };
    descriptionsContainer.add(descriptions);

    restaurateurBlackboardsContainer = new WebMarkupContainer("restaurateurBlackboardsContainer");
    restaurateurBlackboardsContainer.setOutputMarkupId(true);
    restaurateurBlackboards = new ListView<RestaurateurBlackboardI18n>("restaurateurBlackboards",
            new BlackBoardsModel()) {
        @Override
        protected void populateItem(ListItem<RestaurateurBlackboardI18n> item) {
            boolean visible = actualDescriptionLanguage.equals(item.getModelObject().getLanguage());
            if (item.getModelObject().getBlackboard() == null
                    || StringUtils.isBlank(item.getModelObject().getBlackboard())) {
                item.add(new Label("restaurateurBlackboard", "").setVisible(false)
                        .setOutputMarkupPlaceholderTag(true));
            } else {
                item.add(new MultiLineLabel("restaurateurBlackboard",
                        new PropertyModel<String>(item.getModelObject(), RestaurateurBlackboardI18n.BLACKBOARD))
                                .setVisible(visible).setOutputMarkupPlaceholderTag(true)
                                .add(new AttributeAppender("class",
                                        new Model("blackboard_" + getInitialLanguage().getLanguage()), " ")));
            }
        }
    };
    restaurateurBlackboardsContainer.add(restaurateurBlackboards);
    formRisto.add(restaurateurBlackboardsContainer);

    formRisto.add(new Label("revisionNumber"));

    Form<Ristorante> formAddress = new Form<Ristorante>("ristoranteAddressForm",
            new CompoundPropertyModel<Ristorante>(ristorante));
    add(formAddress);
    formAddress.add(new Label(Ristorante.ADDRESS));
    formAddress.add(new Label(Ristorante.CITY));
    formAddress.add(new Label(Ristorante.PROVINCE));
    formAddress.add(new Label(Ristorante.POSTALCODE));
    formAddress.add(new Label(Ristorante.COUNTRY));
    formAddress.add(new Label(Ristorante.MOBILE_PHONE_NUMBER));
    formAddress.add(new Label(Ristorante.PHONE_NUMBER));
    formAddress.add(new Label(Ristorante.FAX_NUMBER));
    formAddress.add(new RatingPanel("rating1", new PropertyModel<Integer>(getRistorante(), "rating"),
            new Model<Integer>(5), new PropertyModel<Integer>(getRistorante(), "rates.size"),
            new PropertyModel<Boolean>(this, "hasVoted"), true) {
        @Override
        protected boolean onIsStarActive(int star) {
            return star < ((int) (getRistorante().getRating() + 0.5));
        }

        @Override
        protected void onRated(int rating, AjaxRequestTarget target) {
            setHasVoted(Boolean.TRUE);
            ristoranteService.addRate(getRistorante(), getLoggedInUser(), rating);
            ristorante = ristoranteService.getByID(ristorante.getId());
            info(getString("info.ratingSaved"));
            if (target != null) {
                target.addComponent(getFeedbackPanel());
            }
        }
    });
    BookmarkablePageLink editAddressRistorante = new BookmarkablePageLink("editAddressRistorante",
            RistoranteEditAddressPage.class,
            new PageParameters(YoueatHttpParams.RISTORANTE_ID + "=" + ristorante.getId()));
    editAddressRistorante.setOutputMarkupId(true);
    add(editAddressRistorante);

    if (getApplication().getSecuritySettings().getAuthorizationStrategy()
            .isInstantiationAuthorized(RistoranteEditAddressPage.class)) {
        editAddressRistorante.setVisible(true);
    } else {
        editAddressRistorante.setVisible(false);
    }
    add(editAddressRistorante);

    BookmarkablePageLink editDataRistorante = new BookmarkablePageLink("editDataRistorante",
            RistoranteEditDataPage.class,
            new PageParameters(YoueatHttpParams.RISTORANTE_ID + "=" + ristorante.getId()));
    editDataRistorante.setOutputMarkupId(true);
    add(editDataRistorante);

    BookmarkablePageLink editPictures = new BookmarkablePageLink("editPictures",
            RistoranteEditPicturePage.class,
            new PageParameters(YoueatHttpParams.RISTORANTE_ID + "=" + ristorante.getId()));
    editPictures.setOutputMarkupId(true);
    add(editPictures);

    picturesList = new ListView<RistorantePicture>("picturesList", ristorante.getActivePictures()) {

        @Override
        protected void populateItem(final ListItem<RistorantePicture> item) {
            Link<RistorantePicture> imageLink = new Link<RistorantePicture>("pictureLink", item.getModel()) {
                @Override
                public void onClick() {
                    setResponsePage(new ImageViewPage(getModelObject().getPicture()));
                }
            };
            imageLink.add(ImageRisto.getThumbnailImage("picture", item.getModelObject().getPicture(), true));
            item.add(imageLink);
        }
    };
    formRisto.add(picturesList);

    add(revisionModal = new ModalWindow("revisionsPanel"));
    //revisionModal.setWidthUnit("%");
    //revisionModal.setInitialHeight(40);
    //revisionModal.setInitialWidth(90);
    revisionModal.setResizable(false);
    RistoranteRevisionsPanel revisionsPanel = new RistoranteRevisionsPanel(revisionModal.getContentId(),
            getFeedbackPanel());
    revisionsPanel.refreshRevisionsList(ristorante, actualDescriptionLanguage);
    revisionModal.setContent(revisionsPanel);
    revisionModal.setTitle("Revisions list");
    revisionModal.setCookieName("SC-revisionLists");
    //JQUERY LAYOUT
    //revisionModal.setCssClassName("ui-widget ui-widget-content ui-corner-all");
    revisionModal.setCssClassName(ModalWindow.CSS_CLASS_BLUE);

    revisionModal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
        public boolean onCloseButtonClicked(AjaxRequestTarget target) {
            return true;
        }
    });

    revisionModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
        public void onClose(AjaxRequestTarget target) {

        }
    });

    add(new AjaxLink("showsAllRevisions") {
        public void onClick(AjaxRequestTarget target) {
            revisionModal.show(target);
        }
    });

    add(new AjaxLink<String>("tried") {
        public void onClick(AjaxRequestTarget target) {
            if (getLoggedInUser() != null) {
                activityService.addTriedRisto(getLoggedInUser(), ristorante);
                info(getString("info.IateHere", new Model<Ristorante>(ristorante)));
            } else {
                info(getString("action.notlogged"));
            }
            target.addComponent(getFeedbackPanel());
        }
    });

    AjaxFallbackLink<String> asfavourite = new AjaxFallbackLink<String>("asfavourite") {
        public void onClick(AjaxRequestTarget target) {
            if (getLoggedInUser() != null) {
                if (activityService.isFavouriteRisto(getLoggedInUser(), ristorante)) {
                    activityService.addRistoAsFavorite(getLoggedInUser(), ristorante);
                    info(getString("action.removedAsFavourite", new Model<Ristorante>(ristorante)));
                    asfavouriteLabel.setDefaultModelObject(getString("button.addAsFavourite"));
                } else {
                    activityService.save(new ActivityRistorante(getLoggedInUser(), ristorante,
                            ActivityRistorante.TYPE_ADDED_AS_FAVOURITE));
                    info(getString("action.addedAsFavourite", new Model<Ristorante>(ristorante)));
                    asfavouriteLabel.setDefaultModelObject(getString("button.removeAsFavourite"));
                }
            } else {
                info(getString("action.notlogged"));
            }
            if (target != null) {
                target.addComponent(asfavouriteLabel);
                target.addComponent(getFeedbackPanel());
            }
        }
    };
    add(asfavourite);

    formComment = new Form<Comment>("formComment", new CompoundPropertyModel<Comment>(new Comment()));
    formComment.setOutputMarkupId(true);
    add(formComment);
    final TextField<String> newCommentTitle = new TextField<String>(Comment.TITLE_FIELD);
    newCommentTitle.setVisible(false);
    newCommentTitle.add(StringValidator.maximumLength(Comment.TITLE_MAX_LENGTH));
    newCommentTitle.setOutputMarkupPlaceholderTag(true);
    formComment.add(newCommentTitle);
    final TextArea<String> newCommentBody = new TextArea<String>(Comment.BODY_FIELD);
    newCommentBody.setRequired(true);
    newCommentBody.add(StringValidator.maximumLength(Comment.BODY_MAX_LENGTH));
    newCommentBody.setVisible(false);
    newCommentBody.setOutputMarkupPlaceholderTag(true);
    formComment.add(newCommentBody);
    final Label newCommentTitleLabel = new Label("newCommentTitleLabel", getString("label.newCommentTitle"));
    newCommentTitleLabel.setOutputMarkupPlaceholderTag(true);
    newCommentTitleLabel.setVisible(false);
    formComment.add(newCommentTitleLabel);
    final AjaxFallbackButton submitNewComment = new AjaxFallbackButton("submitNewComment", formComment) {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (getLoggedInUser() != null) {
                Comment comment = (Comment) getForm().getModelObject();
                comment.setAuthor(getLoggedInUser());
                comment.setCreationTime(DateUtil.getTimestamp());
                ristorante.addComment(comment);
                try {
                    ristoranteService.updateNoRevision(ristorante);
                    activityService.save(new ActivityRistorante(getLoggedInUser(), ristorante,
                            ActivityRistorante.TYPE_NEW_COMMENT));
                    // reset the new comment formRisto
                    formComment.setModelObject(new Comment());
                    newCommentBody.setVisible(false);
                    newCommentTitle.setVisible(false);
                    newCommentTitleLabel.setVisible(false);
                    this.setVisible(false);
                    newCommentTitleLabel.setVisible(false);
                    Comment commeTitleToShow = new Comment();
                    commeTitleToShow.setTitle(comment.getTitle() != null ? "'" + comment.getTitle() + "'" : "");
                    info(getString("message.newCommentAdded", new Model<Comment>(commeTitleToShow)));
                    if (target != null) {
                        target.addComponent(formComment);
                    }
                } catch (YoueatException e) {
                    getFeedbackPanel().error(getString("genericErrorMessage"));
                }
                if (target != null) {
                    target.addComponent(getFeedbackPanel());
                }
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            if (target != null) {
                target.addComponent(getFeedbackPanel());
            }
        }
    };
    submitNewComment.setOutputMarkupPlaceholderTag(true);
    submitNewComment.setVisible(false);
    formComment.add(submitNewComment);
    commentsList = new ListView<Comment>("commentsList", new CommentsModel()) {

        @Override
        protected void populateItem(final ListItem<Comment> item) {
            item.add(new Label(Comment.AUTHOR_FIELD, item.getModelObject().getAuthor().getFirstname() + " "
                    + item.getModelObject().getAuthor().getLastname()));
            item.add(new Label(Comment.TITLE_FIELD, item.getModelObject().getTitle()));
            item.add(new Label(Comment.CREATIONTIME_FIELD,
                    DateUtil.SDF2SHOW.print(item.getModelObject().getCreationTime().getTime())));
            item.add(new MultiLineLabel(Comment.BODY_FIELD, item.getModelObject().getBody()));
        }
    };
    formComment.add(commentsList);
    add(new NewCommentButton("newComment", newCommentBody, submitNewComment, newCommentTitleLabel,
            newCommentTitle));
    add(new NewCommentButton("newCommentBottom", newCommentBody, submitNewComment, newCommentTitleLabel,
            newCommentTitle));
    asfavouriteLabel = new Label("asfavouriteLabel", getString("button.addAsFavourite"));
    if (activityService.isFavouriteRisto(getLoggedInUser(), ristorante)) {
        asfavouriteLabel.setDefaultModelObject(getString("button.removeAsFavourite"));
    }
    asfavouriteLabel.setOutputMarkupId(true);
    asfavourite.add(asfavouriteLabel);

    setHasVoted(ristoranteService.hasUsersAlreadyRated(getRistorante(), getLoggedInUser())
            || getLoggedInUser() == null);

    // position on the map
    final GMap2 bottomMap = new GMap2("map",
            new GMapHeaderContributor(((YoueatApplication) this.getApplication()).getGmapKey()));
    bottomMap.setOutputMarkupId(true);
    bottomMap.setMapType(GMapType.G_NORMAL_MAP);
    bottomMap.addControl(GControl.GSmallMapControl);
    bottomMap.addControl(GControl.GMapTypeControl);
    bottomMap.setZoom(16);
    if (ristorante.getLatitude() != 0 && ristorante.getLongitude() != 0) {
        GLatLng gLatLng = new GLatLng(ristorante.getLatitude(), ristorante.getLongitude());
        GMarkerOptions markerOptions = new GMarkerOptions(ristorante.getName());
        markerOptions = markerOptions.draggable(true);
        GMarker marker = new GMarker(gLatLng, markerOptions) {
            @Override
            protected void updateOnAjaxCall(AjaxRequestTarget target, GEvent overlayEvent) {
                super.updateOnAjaxCall(target, overlayEvent);
                if (getLoggedInUser() != null) {
                    ristorante.setLatitude(this.getLatLng().getLat());
                    ristorante.setLongitude(this.getLatLng().getLng());
                    ristorante = ristoranteService.updateLatitudeLongitude(ristorante);
                }
            }
        };
        marker.addListener(GEvent.dragend, new GEventHandler() {

            @Override
            public void onEvent(AjaxRequestTarget target) {
                //attach the ajax code to handle the event 
            }
        });
        bottomMap.addOverlay(marker);
        bottomMap.setCenter(gLatLng);
    } else {
        bottomMap.setVisible(false);
    }
    add(bottomMap);
    // users that already tried infos
    List<ActivityRistorante> friendThatAlreadyEat = new ArrayList<ActivityRistorante>(0);
    int numberUsersThatAlreadyEat = 0;

    if (getLoggedInUser() != null) {
        friendThatAlreadyEat = activityService.findByFriendWithActivitiesOnRistorante(getLoggedInUser(),
                ristorante, ActivityRistorante.TYPE_TRIED);
        numberUsersThatAlreadyEat = activityService.countByRistoAndType(ristorante,
                ActivityRistorante.TYPE_TRIED);
    }
    add(new Label("friendEaterListTitle",
            getString("numberOfUsersAlreadyEatAt",
                    new Model<NumberBean>(new NumberBean(numberUsersThatAlreadyEat))))
                            .setVisible(numberUsersThatAlreadyEat > 0));
    add(new FriendEaterListView("friendEaterList", friendThatAlreadyEat)
            .setVisible(friendThatAlreadyEat.size() > 0));

    // contribution infos
    List<ActivityRistorante> friendContributions = new ArrayList<ActivityRistorante>(0);
    int numberOfContributions = 0;

    if (getLoggedInUser() != null) {
        friendContributions = activityService.findByFriendContributionsOnRistorante(getLoggedInUser(),
                ristorante);
        numberOfContributions = activityService.countContributionsOnRistorante(ristorante);
    }
    add(new Label("numberOfContributions",
            getString("numberOfContributions", new Model<NumberBean>(new NumberBean(numberOfContributions))))
                    .setVisible(numberOfContributions > 0));
    add(new FriendEaterListView("friendContributionsList", friendContributions)
            .setVisible(friendContributions.size() > 0));
}

From source file:jp.go.nict.langrid.management.web.view.ServiceManagerApplication.java

License:Open Source License

@Override
protected void init() {
    setSpringSettings();//ww  w.j a  v  a  2s .c  om
    try {
        MessageUtil.setContext(getServletContext());
    } catch (ParameterRequiredException e) {
        e.printStackTrace();
        LogWriter.writeError("Service Manager System", e, ServiceManagerApplication.class,
                "Service Manager can't initialized.");
    }
    getPageSettings().setAutomaticMultiWindowSupport(true);
    /** When rendered page, Comments are striped in page. **/
    getMarkupSettings().setStripComments(true);
    getRequestCycleSettings().setResponseRequestEncoding("UTF-8");
    getApplicationSettings().setInternalErrorPage(RequestResponseUtil.getPageClassForErrorRequest());
    getApplicationSettings().setPageExpiredErrorPage(RequestResponseUtil.getPageClassForSessionTimeOut());
    getSecuritySettings().setCryptFactory(new KeyInSessionSunJceCryptFactory());
    getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {
        public boolean isActionAuthorized(Component component, Action action) {
            return true;
        }

        public boolean isInstantiationAuthorized(Class componentClass) {
            if (!ServiceManagerPage.class.isAssignableFrom(componentClass)) {
                return true;
            }
            if (NewsLogOutPage.class.isAssignableFrom(componentClass)
                    || NodeListLogOutPage.class.isAssignableFrom(componentClass)
                    || LanguageResourcesLogOutPage.class.isAssignableFrom(componentClass)
                    || LanguageServiceLogOutPage.class.isAssignableFrom(componentClass)
                    || LanguageGridUsersLogOutPage.class.isAssignableFrom(componentClass)
                    || OverviewLogOutPage.class.isAssignableFrom(componentClass)
                    || LoginPage.class.isAssignableFrom(componentClass)
                    || LanguageResourceProfilePage.class.isAssignableFrom(componentClass)
                    || ServiceProfilePage.class.isAssignableFrom(componentClass)
                    || LanguageInputFormPopupPage.class.isAssignableFrom(componentClass)
                    || NodeProfilePage.class.isAssignableFrom(componentClass)
                    || UserProfilePage.class.isAssignableFrom(componentClass)
                    || OperatersOfConnectedLanguageGridLogOutPage.class.isAssignableFrom(componentClass)
                    || ExpiredPasswordChangePage.class.isAssignableFrom(componentClass)
                    || ProtocolsOfServiceLogOutPage.class.isAssignableFrom(componentClass)
                    || ServiceTypeListLogOutPage.class.isAssignableFrom(componentClass)
                    || ServiceTypeProfilePage.class.isAssignableFrom(componentClass)
                    || MonitoringLanguageServicePublicLogOutPage.class.isAssignableFrom(componentClass)
                    || MonitoringLanguageServiceStatisticPublicLogOutPage.class.isAssignableFrom(componentClass)
                    || ManualLogOutPage.class.isAssignableFrom(componentClass)
                    || RequestResponseUtil.getPageClassForErrorRequest().isAssignableFrom(componentClass)
                    || RequestResponseUtil.getPageClassForErrorPopupRequest()
                            .isAssignableFrom(componentClass)) {
                return true;
            }
            if (!((ServiceManagerSession) Session.get()).isLoginedAccess()) {
                throw new RestartResponseAtInterceptPageException(LoginPage.class);
            }
            if (!((ServiceManagerSession) Session.get()).isLogin()) {
                throw new RestartResponseAtInterceptPageException(
                        RequestResponseUtil.getPageClassForSessionTimeOut());
            }
            return true;
        }
    });
    // bookmarkable pages
    mount(new QueryStringUrlCodingStrategy("/login", LoginPage.class));
    mount(new QueryStringUrlCodingStrategy("/overview", OverviewLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/news", NewsLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/service-monitoring",
            MonitoringLanguageServicePublicLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/service-type", ServiceTypeListLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/users", LanguageGridUsersLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/language-resources", LanguageResourcesLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/language-services", LanguageServiceLogOutPage.class));
    mount(new QueryStringUrlCodingStrategy("/computation-resources", NodeListLogOutPage.class));
    mount(new MixedParamUrlCodingStrategy("/language-services/profile", ServiceProfilePage.class,
            new String[] { "gridId", "id" }));
    mount(new QueryStringUrlCodingStrategy("/users/profile", UserProfilePage.class));
    mount(new MixedParamUrlCodingStrategy("/language-resources/profile", LanguageResourceProfilePage.class,
            new String[] { "gridId", "id" }));
    mount(new MixedParamUrlCodingStrategy("/computation-resources/profile", NodeProfilePage.class,
            new String[] { "gridId", "id" }));
    mount(new MixedParamUrlCodingStrategy("/service-type/profile", ServiceTypeProfilePage.class,
            new String[] { "domainId", "id" }));

    String selfGridId = new ServletContextParameterContext(getServletContext()).getValue("langrid.node.gridId");
    if (selfGridId == null)
        throw new RuntimeException("failed to initialize service manager.");
    ServiceFactory.getInstance().getGridService().setSelfGridId(selfGridId);
}