Example usage for org.apache.wicket.markup.html.list ListView ListView

List of usage examples for org.apache.wicket.markup.html.list ListView ListView

Introduction

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

Prototype

public ListView(final String id, final List<T> list) 

Source Link

Usage

From source file:dk.frankbille.scoreboard.components.PlayerStatisticsPanel.java

License:Open Source License

public PlayerStatisticsPanel(String id, final IModel<Player> selectedPlayerModel, final League league,
        final RatingCalculator rating) {
    super(id);//www  .  j  a v a  2 s  . co  m

    IModel<List<PlayerResult>> playerResultsModel = new LoadableDetachableModel<List<PlayerResult>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<PlayerResult> load() {
            List<PlayerResult> playerResults = scoreBoardService.getPlayerResults(league);

            Collections.sort(playerResults, new Comparator<PlayerResult>() {
                @Override
                public int compare(PlayerResult o1, PlayerResult o2) {
                    double rating1 = rating.getPlayerRating(o1.getPlayer().getId()).getRating();
                    Double rating2 = rating.getPlayerRating(o2.getPlayer().getId()).getRating();
                    int compare = rating2.compareTo(rating1);

                    if (compare == 0) {
                        compare = new Double(o2.getGamesWonRatio()).compareTo(o1.getGamesWonRatio());
                    }

                    if (compare == 0) {
                        compare = new Integer(o2.getGamesWon()).compareTo(o1.getGamesWon());
                    }

                    if (compare == 0) {
                        compare = new Integer(o1.getGamesLost()).compareTo(o2.getGamesLost());
                    }

                    if (compare == 0) {
                        compare = new Integer(o1.getGamesCount()).compareTo(o2.getGamesCount());
                    }

                    if (compare == 0) {
                        compare = o1.getPlayer().getName().compareTo(o2.getPlayer().getName());
                    }

                    if (compare == 0) {
                        compare = o1.getPlayer().getId().compareTo(o2.getPlayer().getId());
                    }

                    return compare;
                }
            });

            return playerResults;
        }
    };

    add(new ListView<PlayerResult>("players", playerResultsModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<PlayerResult> item) {
            final PlayerResult playerResult = item.getModelObject();
            Player player = playerResult.getPlayer();
            Player selectedPlayer = selectedPlayerModel.getObject();

            item.add(new TooltipBehavior(new AbstractReadOnlyModel<CharSequence>() {
                private static final long serialVersionUID = 1L;

                @Override
                public CharSequence getObject() {
                    StringBuilder b = new StringBuilder();
                    Localizer localizer = Application.get().getResourceSettings().getLocalizer();
                    b.append(localizer.getString("won", item)).append(": ").append(playerResult.getGamesWon());
                    b.append(", ");
                    b.append(localizer.getString("lost", item)).append(": ")
                            .append(playerResult.getGamesLost());
                    return b;
                }
            }));

            item.add(RowColorModifier.create(item));
            if (selectedPlayer != null && player.getId().equals(selectedPlayer.getId())) {
                item.add(new AttributeAppender("class", new Model<String>("highlighted"), " "));
            }
            item.add(new Label("number", "" + (item.getIndex() + 1)));
            PageParameters pp = new PageParameters();
            pp.set(0, player.getId());
            BookmarkablePageLink<Void> playerLink = new BookmarkablePageLink<Void>("playerLink",
                    PlayerPage.class, pp);
            item.add(playerLink);
            playerLink.add(new Label("name", new PropertyModel<Integer>(item.getModel(), "player.name")));
            WebComponent medal = new WebComponent("medal") {
                private static final long serialVersionUID = 1L;

                @Override
                public boolean isVisible() {
                    return item.getIndex() < 3;
                }
            };
            medal.add(AttributeModifier.append("class", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (item.getIndex() == 0) {
                        return "gold";
                    } else if (item.getIndex() == 1) {
                        return "silver";
                    } else if (item.getIndex() == 2) {
                        return "bronze";
                    }

                    return null;
                }
            }));
            item.add(medal);
            item.add(new Label("gamesCount", new PropertyModel<Integer>(item.getModel(), "gamesCount")));
            item.add(new Label("winRatio", new FormatModel(new DecimalFormat("0.00"),
                    new PropertyModel<Double>(item.getModel(), "gamesWonRatio"))));
            item.add(new Label("rating", new FormatModel(new DecimalFormat("#"),
                    rating.getPlayerRating(player.getId()).getRating())));
            item.add(new Label("trend",
                    new StringResourceModel(item.getModelObject().getTrend().name().toLowerCase(), null)));
        }
    });
}

From source file:dk.frankbille.scoreboard.components.TeamStatisticsPanel.java

License:Open Source License

public TeamStatisticsPanel(String id, final League league, final RatingCalculator rating) {
    super(id);//  ww w  .j ava  2  s.  com

    IModel<List<TeamResult>> teamResultsModel = new LoadableDetachableModel<List<TeamResult>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<TeamResult> load() {
            List<TeamResult> teamResults = scoreBoardService.getTeamResults(league);

            Collections.sort(teamResults, new Comparator<TeamResult>() {
                @Override
                public int compare(TeamResult o1, TeamResult o2) {
                    double rating1 = rating.getTeamRating(o1.getTeam()).getRating();
                    Double rating2 = rating.getTeamRating(o2.getTeam()).getRating();
                    int compare = rating2.compareTo(rating1);

                    if (compare == 0) {
                        compare = new Double(o2.getGamesWonRatio()).compareTo(o1.getGamesWonRatio());
                    }

                    if (compare == 0) {
                        compare = new Integer(o2.getGamesWon()).compareTo(o1.getGamesWon());
                    }

                    if (compare == 0) {
                        compare = new Integer(o1.getGamesLost()).compareTo(o2.getGamesLost());
                    }

                    if (compare == 0) {
                        compare = new Integer(o1.getGamesCount()).compareTo(o2.getGamesCount());
                    }

                    return compare;
                }
            });

            return teamResults;
        }
    };

    add(new ListView<TeamResult>("teams", teamResultsModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<TeamResult> item) {
            final TeamResult teamResult = item.getModelObject();

            item.add(new TooltipBehavior(new AbstractReadOnlyModel<CharSequence>() {
                private static final long serialVersionUID = 1L;

                @Override
                public CharSequence getObject() {
                    StringBuilder b = new StringBuilder();
                    Localizer localizer = Application.get().getResourceSettings().getLocalizer();
                    b.append(localizer.getString("won", item)).append(": ").append(teamResult.getGamesWon());
                    b.append(", ");
                    b.append(localizer.getString("lost", item)).append(": ").append(teamResult.getGamesLost());
                    return b;
                }
            }));

            item.add(RowColorModifier.create(item));
            item.add(new Label("number", "" + (item.getIndex() + 1)));
            item.add(new Label("name", new PropertyModel<Integer>(item.getModel(), "name")));
            WebComponent medal = new WebComponent("medal") {
                private static final long serialVersionUID = 1L;

                @Override
                public boolean isVisible() {
                    return item.getIndex() < 3;
                }
            };
            medal.add(AttributeModifier.append("class", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (item.getIndex() == 0) {
                        return "gold";
                    } else if (item.getIndex() == 1) {
                        return "silver";
                    } else if (item.getIndex() == 2) {
                        return "bronze";
                    }

                    return null;
                }
            }));
            item.add(medal);
            item.add(new Label("gamesCount", new PropertyModel<Integer>(item.getModel(), "gamesCount")));
            item.add(new Label("winRatio", new FormatModel(new DecimalFormat("0.00"),
                    new PropertyModel<Double>(item.getModel(), "gamesWonRatio"))));
            item.add(new Label("rating", new FormatModel(new DecimalFormat("#"),
                    rating.getTeamRating(teamResult.getTeam()).getRating())));
            item.add(new Label("trend",
                    new StringResourceModel(item.getModelObject().getTrend().name().toLowerCase(), null)));
        }
    });
}

From source file:dk.frankbille.scoreboard.league.LeagueListPage.java

License:Open Source License

public LeagueListPage() {
    add(new SecureRenderingBookmarkablePageLink<League>("addNewLeagueLink", LeagueEditPage.class));

    IModel<List<League>> leagueListModel = new LoadableDetachableModel<List<League>>() {
        private static final long serialVersionUID = 1L;

        @Override//w w  w . ja  v a 2  s.  c  om
        protected List<League> load() {
            return scoreBoardService.getAllLeagues();
        }
    };

    add(new ListView<League>("leagues", leagueListModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<League> item) {
            PageParameters pp = new PageParameters();
            pp.set(0, item.getModelObject().getId());
            Link<League> link = new SecureExecutionBookmarkablePageLink<League>("leagueLink",
                    LeagueEditPage.class, pp);
            link.add(new Label("name", new PropertyModel<String>(item.getModel(), "name")));
            item.add(link);

            item.add(new Label("active", new StringResourceModel("active.${active}", item.getModel())));
            item.add(new Label("ratingCalculator",
                    new PropertyModel<String>(item.getModel(), "ratingCalculator.name")));
        }
    });
}

From source file:dk.frankbille.scoreboard.player.PlayerListPage.java

License:Open Source License

public PlayerListPage() {
    add(new SecureRenderingLink<Void>("addNewPlayerLink") {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w w  .j a va 2  s.  c o  m*/
        public void onClick() {
            getRequestCycle().setResponsePage(new PlayerEditPage(new Model<Player>(new Player())));
        }
    });

    IModel<List<Player>> playerListModel = new LoadableDetachableModel<List<Player>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<Player> load() {
            return scoreBoardService.getAllPlayers();
        }
    };

    add(new ListView<Player>("players", playerListModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<Player> item) {
            PageParameters parameters = new PageParameters();
            parameters.set(0, item.getModelObject().getId());
            BookmarkablePageLink<Player> link = new BookmarkablePageLink<Player>("playerLink", PlayerPage.class,
                    parameters);
            link.add(new Label("name", new PropertyModel<String>(item.getModel(), "name")));
            item.add(link);

            item.add(new Label("fullName", new PropertyModel<String>(item.getModel(), "fullName")));
            item.add(new Label("groupName", new PropertyModel<String>(item.getModel(), "groupName")));
        }
    });
}

From source file:dk.netdesign.common.osgi.config.wicket.ConfigurationPage.java

License:Apache License

public final void setUpPage() {
    String name = controllerModel.getObject().getName();
    String id = controllerModel.getObject().getID();
    Label configName = new Label("configName", Model.of(name));
    add(configName);/*from ww w  . ja  v a2s. c  o  m*/
    Label configID = new Label("configID", Model.of(id));
    add(configID);

    final ListView<AttributeValue> attributePanels = new ListView<AttributeValue>("attribute-panels",
            attributeModel) {

        @Override
        protected void populateItem(ListItem<AttributeValue> item) {
            AttributeValue attributeAndValue = item.getModelObject();
            item.add(new ConfigurationItemPanel(attributeAndValue.getAttribute(), attributeAndValue.getValue(),
                    attributeAndValue.errorMessageModel, "attribute-panel"));
        }
    };

    Form configForm = new Form("configForm");

    configForm.add(new AjaxFormSubmitBehavior("submit") {
        @Override
        protected void onSubmit(AjaxRequestTarget target) {
            super.onSubmit(target);

            LOGGER.info("Attempting to persist new configuration");
            for (AttributeValue value : attributeModel.getObject()) {
                value.setErrorMessage(null);
            }

            Map<String, ParsingException> exceptions = new HashMap<>();
            for (AttributeValue value : attributeModel.getObject()) {
                try {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Parsing " + value.getValue().getObject());
                    }
                    Object castObject = value.getValue().getCastObject();
                    LOGGER.debug("Parsed object: " + castObject);
                    controllerModel.getObject().setItem(value.getAttribute(), castObject);
                } catch (ParsingException ex) {
                    ParsingException previousException = exceptions.put(ex.getKey(), ex);
                    if (previousException != null) {
                        LOGGER.info("Exception overwritten for key " + ex.getKey() + ": "
                                + previousException.getMessage());
                    }
                }

            }

            if (!exceptions.isEmpty()) {

                resetCommit(controllerModel.getObject());
                for (AttributeValue value : attributeModel.getObject()) {
                    ParsingException ex = exceptions.get(value.attribute.getID());
                    if (ex != null) {
                        if (ex.getCause() != null && ex.getCause() instanceof TypeFilterException) {
                            value.setErrorMessage(ex.getCause().getMessage());
                        } else {
                            value.setErrorMessage(ex.getMessage());
                        }

                    }
                }

            } else {
                try {
                    controllerModel.getObject().commitProperties();
                } catch (MultiParsingException ex) {
                    for (ParsingException pex : ex.getExceptions()) {
                        for (AttributeValue value : attributeModel.getObject()) {
                            if (value.attribute.getID().equals(pex.getKey())) {
                                if (pex.getCause() != null && pex.getCause() instanceof TypeFilterException) {
                                    value.setErrorMessage(pex.getCause().getMessage());
                                } else {
                                    value.setErrorMessage(pex.getMessage());
                                }
                                break;
                            }
                        }
                    }
                } catch (InvocationException ex) {
                    LOGGER.warn("Attempted to commit configuration, but controller was not in set-state", ex);
                }
            }
            LOGGER.debug("Committing configuration: " + controllerModel.getObject());

            target.add(ConfigurationPage.this);
        }
    });

    configForm.add(attributePanels);

    add(configForm);
}

From source file:dk.teachus.frontend.components.calendar.CalendarPanel.java

License:Apache License

public CalendarPanel(String id, IModel<DateMidnight> weekDateModel) {
    super(id, weekDateModel);

    /*/*from  w w  w  . ja  va2  s.  c om*/
     * Navigation
     */
    Link<DateMidnight> previousWeekLink = new Link<DateMidnight>("previousWeek", weekDateModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            setModelObject(getModelObject().minusWeeks(1));
        }
    };
    previousWeekLink.add(new Label("label", TeachUsSession.get().getString("CalendarPanelV2.previousWeek"))); //$NON-NLS-1$ //$NON-NLS-2$
    add(previousWeekLink);
    Link<DateMidnight> thisWeekLink = new Link<DateMidnight>("thisWeek", weekDateModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            setModelObject(new DateMidnight());
        }
    };
    thisWeekLink.add(new Label("label", TeachUsSession.get().getString("CalendarPanelV2.thisWeek"))); //$NON-NLS-1$ //$NON-NLS-2$
    add(thisWeekLink);
    Link<DateMidnight> nextWeekLink = new Link<DateMidnight>("nextWeek", weekDateModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick() {
            setModelObject(getModelObject().plusWeeks(1));
        }
    };
    nextWeekLink.add(new Label("label", TeachUsSession.get().getString("CalendarPanelV2.nextWeek"))); //$NON-NLS-1$ //$NON-NLS-2$
    add(nextWeekLink);

    /*
     * Calendar
     */
    IModel<List<DateMidnight>> daysModel = new LoadableDetachableModel<List<DateMidnight>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<DateMidnight> load() {
            DateMidnight thisMonday = CalendarPanel.this.getModelObject()
                    .withDayOfWeek(DateTimeConstants.MONDAY);
            List<DateMidnight> days = new ArrayList<DateMidnight>();
            for (int i = 0; i < 7; i++) {
                days.add(thisMonday);
                thisMonday = thisMonday.plusDays(1);
            }
            return days;
        }
    };

    final IModel<List<LocalTime>> timesModel = new LoadableDetachableModel<List<LocalTime>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<LocalTime> load() {
            int minutesDivider = 30;
            LocalTime localTime = getCalendarStartTime();
            final List<LocalTime> times = new ArrayList<LocalTime>();
            for (int i = 0; i < calculateNumberOfCalendarHours() * (60 / minutesDivider); i++) {
                times.add(localTime);
                localTime = localTime.plusMinutes(minutesDivider);
            }

            return times;
        }
    };

    // Headers
    add(new ListView<DateMidnight>("headers", daysModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<DateMidnight> item) {
            item.add(new Label("label", new AbstractReadOnlyModel<String>() { //$NON-NLS-1$
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return HEADER_FORMAT.withLocale(TeachUsSession.get().getLocale())
                            .print(item.getModelObject());
                }
            }).setRenderBodyOnly(true));
        }
    });

    // Body
    // Times
    add(new ListView<LocalTime>("times", timesModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<LocalTime> item) {
            Label label = new Label("label", new AbstractReadOnlyModel<String>() { //$NON-NLS-1$
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (item.getModelObject().getMinuteOfHour() == 0) {
                        return TIME_FORMAT.withLocale(TeachUsSession.get().getLocale())
                                .print(item.getModelObject());
                    } else {
                        return null;
                    }
                }
            });
            item.add(label);

            IModel<String> appendModel = new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    if (item.getModelObject().getMinuteOfHour() == 0) {
                        return "timehour"; //$NON-NLS-1$
                    } else {
                        return null;
                    }
                }
            };
            item.add(AttributeModifier.append("class", appendModel)); //$NON-NLS-1$
        }
    });

    // Days
    add(new ListView<DateMidnight>("days", daysModel) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<DateMidnight> dayItem) {
            // Times
            dayItem.add(new ListView<LocalTime>("times", timesModel) { //$NON-NLS-1$
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(final ListItem<LocalTime> item) {
                    IModel<String> appendModel = new AbstractReadOnlyModel<String>() {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public String getObject() {
                            if (item.getModelObject().getMinuteOfHour() == 0) {
                                return "daytimehour"; //$NON-NLS-1$
                            } else {
                                return null;
                            }
                        }
                    };
                    item.add(AttributeModifier.append("class", appendModel)); //$NON-NLS-1$
                }
            });

            /*
             * Entries
             */
            dayItem.add(new ListView<TimeSlot<T>>("timeSlots", getTimeSlotModel(dayItem.getModelObject())) { //$NON-NLS-1$
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(final ListItem<TimeSlot<T>> timeSlotItem) {
                    timeSlotItem.setOutputMarkupId(true);

                    final LocalTime startTime = timeSlotItem.getModelObject().getStartTime();
                    final LocalTime endTime = timeSlotItem.getModelObject().getEndTime();
                    int dividerPixelHeight = 25;
                    double minutesPerDivider = calculateNumberOfCalendarHours() * 60
                            / timesModel.getObject().size();

                    // Calculate top/y (start time)
                    double minutesStart = startTime.getHourOfDay() * 60 + startTime.getMinuteOfHour();
                    minutesStart -= getCalendarStartTime().getHourOfDay() * 60
                            + getCalendarStartTime().getMinuteOfHour();
                    double pixelStart = minutesStart / minutesPerDivider;
                    long top = Math.round(pixelStart * dividerPixelHeight) - 1;

                    // Calculate height (end time)
                    final double minutesEnd = (endTime.getHourOfDay() * 60 + endTime.getMinuteOfHour())
                            - minutesStart - getCalendarStartTime().getHourOfDay() * 60
                            + getCalendarStartTime().getMinuteOfHour();
                    double pixelEnd = minutesEnd / minutesPerDivider;
                    long height = Math.round(pixelEnd * dividerPixelHeight) - 1;

                    timeSlotItem.add(AttributeModifier.replace("style", //$NON-NLS-1$
                            "left: 0; top: " + top + "px; height: " + height + "px;")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

                    // Time slot content
                    IModel<List<String>> timeSlotContentModel = new LoadableDetachableModel<List<String>>() {
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected List<String> load() {
                            return getTimeSlotContent(dayItem.getModelObject(), timeSlotItem.getModelObject(),
                                    timeSlotItem);
                        }
                    };

                    timeSlotItem.add(new ListView<String>("timeSlotContent", timeSlotContentModel) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected void populateItem(ListItem<String> item) {
                            item.add(new Label("content", item.getModel()));
                            item.add(AttributeModifier.replace("title", item.getModel()));
                        }
                    });

                    // Details
                    final Component dayTimeLessonDetails = createTimeSlotDetailsComponent(
                            "dayTimeLessonDetails", timeSlotItem.getModelObject());
                    dayTimeLessonDetails.setOutputMarkupId(true);
                    timeSlotItem.add(dayTimeLessonDetails);
                    timeSlotItem.add(AttributeModifier.append("class", new AbstractReadOnlyModel<String>() {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public String getObject() {
                            if (dayTimeLessonDetails.isVisible()) {
                                return "popover-external";
                            }
                            return null;
                        }
                    }));
                    timeSlotItem.add(
                            AttributeModifier.replace("data-content-id", new AbstractReadOnlyModel<String>() { //$NON-NLS-1$
                                private static final long serialVersionUID = 1L;

                                @Override
                                public String getObject() {
                                    if (dayTimeLessonDetails.isVisible()) {
                                        return "#" + dayTimeLessonDetails.getMarkupId(); //$NON-NLS-1$
                                    } else {
                                        return null;
                                    }
                                }
                            }));
                }
            });
        }
    });
}

From source file:dk.teachus.frontend.components.form.SelectPupilsPanel.java

License:Apache License

public SelectPupilsPanel(String id, IModel<? extends Collection<Pupil>> model) {
    super(id, model);

    selectGroup = new CheckGroup<Pupil>("selectGroup", getModel());
    selectGroup.setRenderBodyOnly(false);
    add(selectGroup);/*from ww  w.  jav a2  s .  c om*/

    // Header
    selectGroup.add(new CheckGroupSelector("selectAll"));
    selectGroup.add(new Label("name", TeachUsSession.get().getString("General.pupil")));

    // Check list model
    IModel<List<Pupil>> pupilsModel = new LoadableDetachableModel<List<Pupil>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<Pupil> load() {
            List<Pupil> pupils = loadPupils();
            return pupils;
        }
    };

    selectGroup.add(new ListView<Pupil>("pupils", pupilsModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<Pupil> item) {
            item.add(AttributeModifier.replace("class", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return (item.getIndex() + 1) % 2 == 0 ? "even" : "odd";
                }
            }));

            Check<Pupil> check = new Check<Pupil>("select", item.getModel());
            item.add(check);
            FormComponentLabel label = new FormComponentLabel("label", check);
            item.add(label);
            label.add(new Label("name", new PropertyModel<String>(item.getModel(), "name"))
                    .setRenderBodyOnly(true));
        }
    });
}

From source file:dk.teachus.frontend.components.menu.MenuItemsPanel.java

License:Apache License

public MenuItemsPanel(String id, IModel<List<MenuItem>> itemsModel,
        final IModel<PageCategory> activeMenuItemModel) {
    super(id, itemsModel);

    add(new ListView<MenuItem>("menuItems", itemsModel) {
        private static final long serialVersionUID = 1L;

        @Override//from   w  w  w .j  ava2s .co  m
        protected void populateItem(final ListItem<MenuItem> listItem) {
            listItem.add(new AttributeAppender("class", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    PageCategory activeMenuType = activeMenuItemModel.getObject();
                    PageCategory menuItemType = listItem.getModelObject().getMenuItemType();

                    return activeMenuType == menuItemType ? "active" : null;
                }
            }));

            final WebMarkupContainer link;

            final MenuItem menuItem = listItem.getModelObject();
            if (menuItem instanceof MenuItemPageLink) {
                final MenuItemPageLink menuItemLink = (MenuItemPageLink) menuItem;

                link = new BookmarkablePageLink<Void>("menuLink", menuItemLink.getPageClass(),
                        menuItemLink.getPageParameters());
                listItem.add(link);

                link.add(new Label("menuLabel", menuItemLink.getLabel()).setRenderBodyOnly(true));
                link.add(new WebMarkupContainer("downIcon").setVisible(false));

                listItem.add(new WebComponent("subMenu").setVisible(false));
            } else if (menuItem instanceof MenuItemContainer) {
                MenuItemContainer menuItemContainer = (MenuItemContainer) menuItem;

                listItem.add(AttributeModifier.append("class", "dropdown"));

                link = new WebMarkupContainer("menuLink");
                link.setOutputMarkupId(true);
                link.add(AttributeModifier.replace("href", "#"));
                link.add(AttributeModifier.replace("class", "dropdown-toggle"));
                link.add(AttributeModifier.replace("data-toggle", "dropdown"));
                link.add(AttributeModifier.replace("role", "button"));
                listItem.add(link);

                link.add(new Label("menuLabel", menuItemContainer.getLabel()).setRenderBodyOnly(true));
                link.add(new WebMarkupContainer("downIcon").setRenderBodyOnly(true));

                MenuItemsPanel subMenu = new MenuItemsPanel("subMenu",
                        new PropertyModel<List<MenuItem>>(menuItemContainer, "subMenuItems"),
                        new AbstractReadOnlyModel<PageCategory>() {
                            private static final long serialVersionUID = 1L;

                            @Override
                            public PageCategory getObject() {
                                return null;
                            }
                        });
                subMenu.add(AttributeModifier.replace("class", "dropdown-menu"));
                subMenu.add(AttributeModifier.replace("role", "menu"));
                subMenu.add(AttributeModifier.replace("aria-labelledby", new AbstractReadOnlyModel<String>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String getObject() {
                        return link.getMarkupId();
                    }
                }));
                listItem.add(subMenu);
            } else {
                throw new IllegalStateException("Unknown menuItem type: " + menuItem);
            }

            // Icon
            WebComponent icon = new WebComponent("icon") {
                private static final long serialVersionUID = 1L;

                @Override
                public boolean isVisible() {
                    return menuItem.getIconName() != null;
                }
            };
            icon.add(AttributeModifier.replace("class", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return "icon-" + menuItem.getIconName();
                }
            }));
            link.add(icon);
        }
    });
}

From source file:drat.proteus.DratStartForm.java

License:Apache License

public DratStartForm(String name, FileUploadField fileUploader, TextField<String> path) {
    super(name);/*from   w  w  w . j  ava  2 s.c o m*/
    fileUploadField = fileUploader;
    pathField = path;
    String[] cmdArray = { "Crawl", "Index", "Map", "Reduce", "Go" };
    List<String> commands = (List<String>) Arrays.asList(cmdArray);
    cmdSelect = new ListView<String>("cmd", commands) {
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String cmdItemLabel = item.getModelObject();
            SubmitLink link = new SubmitLink("cmd_link") {
                @Override
                public void onSubmit() {
                    theCommand = cmdItemLabel;
                }
            };

            link.add(new Label("cmd_item_label", cmdItemLabel));
            item.add(link);

        }
    };
    this.add(fileUploadField);
    this.add(path);
    this.add(cmdSelect);
}

From source file:edu.colorado.phet.website.panels.simulation.SimulationMainPanel.java

public SimulationMainPanel(String id, final LocalizedSimulation simulation, final PageContext context) {
    super(id, context);

    String simulationVersionString = simulation.getSimulation().getProject().getVersionString();

    add(new Label("simulation-main-title", simulation.getTitle()));

    //add( HeaderContributor.forCss( CSS.SIMULATION_MAIN ) );

    if (simulation.getLocale().equals(context.getLocale())) {
        add(new InvisibleComponent("untranslated-sim-text"));
    } else {//from www .  ja v a 2 s  . co  m
        add(new LocalizedText("untranslated-sim-text", "simulationMainPanel.untranslatedMessage"));
    }

    RawLink link = simulation.getRunLink("simulation-main-link-run-main");

    WebImage image = (simulation.getSimulation().isHTML()) ? simulation.getSimulation().getHTMLImage()
            : simulation.getSimulation().getImage();
    link.add(new StaticImage("simulation-main-screenshot", image,
            StringUtils.messageFormat(getPhetLocalizer().getString("simulationMainPanel.screenshot.alt", this),
                    new Object[] { encode(simulation.getTitle()) })));
    if (simulation.getSimulation().isHTML()) {
        WebMarkupContainer html5Badge = new WebMarkupContainer("html5-badge");
        link.add(html5Badge);
        html5Badge.add(new SimpleAttributeModifier("class", "sim-badge-html"));
        html5Badge.add(new SimpleAttributeModifier("style", "left: 284px"));
    } else {
        link.add(new InvisibleComponent("html5-badge"));
    }
    add(link);

    //add( new Label( "simulation-main-description", simulation.getDescription() ) );
    add(new LocalizedText("simulation-main-description", simulation.getSimulation().getDescriptionKey()));
    add(new LocalizedText("simulationMainPanel.version", "simulationMainPanel.version",
            new Object[] { HtmlUtils.encode(simulationVersionString), }));

    {
        String name = simulation.getSimulation().getName();
        if (HTML_SIM_LINK_MAP.containsKey(name)) {
            WebMarkupContainer container = new WebMarkupContainer("html-button");
            // TODO: isolate specific HTML5 sim links out!
            container.add(new RawLink("html-link", HTML_SIM_LINK_MAP.get(name)));
            add(container);
        } else {
            add(new InvisibleComponent("html-button"));
        }
    }

    add(DonatePanel.getLinker().getLink("donate-link", context, getPhetCycle()));

    //        SmallOrangeButtonBorder orangeButton = new SmallOrangeButtonBorder( "orange-button", context );
    //        add( orangeButton );
    //        orangeButton.add( DonatePanel.getLinker().getLink( "support-link", context, getPhetCycle() ) );

    /*---------------------------------------------------------------------------*
    * rating icons
    *----------------------------------------------------------------------------*/

    if (simulation.getSimulation().isUnderConstruction()) {
        Link uclink = AboutLegendPanel.getLinker().getLink("rating-under-construction-link", context,
                getPhetCycle());
        uclink.add(new StaticImage("rating-under-construction-image", Images.UNDER_CONSTRUCTION_SMALL,
                getPhetLocalizer().getString("tooltip.legend.underConstruction", this)));
        add(uclink);
    } else {
        add(new InvisibleComponent("rating-under-construction-link"));
    }

    if (simulation.getSimulation().isGuidanceRecommended()) {
        Link uclink = AboutLegendPanel.getLinker().getLink("rating-guidance-recommended-link", context,
                getPhetCycle());
        uclink.add(new StaticImage("rating-guidance-recommended-image", Images.GUIDANCE_RECOMMENDED_SMALL,
                getPhetLocalizer().getString("tooltip.legend.guidanceRecommended", this)));
        add(uclink);
    } else {
        add(new InvisibleComponent("rating-guidance-recommended-link"));
    }

    if (simulation.getSimulation().isClassroomTested()) {
        Link uclink = AboutLegendPanel.getLinker().getLink("rating-classroom-tested-link", context,
                getPhetCycle());
        uclink.add(new StaticImage("rating-classroom-tested-image", Images.CLASSROOM_TESTED_SMALL,
                getPhetLocalizer().getString("tooltip.legend.classroomTested", this)));
        add(uclink);
    } else {
        add(new InvisibleComponent("rating-classroom-tested-link"));
    }

    /*---------------------------------------------------------------------------*
    * teacher's guide
    *----------------------------------------------------------------------------*/

    final List<TeachersGuide> guides = new LinkedList<TeachersGuide>();
    HibernateUtils.wrapTransaction(getHibernateSession(), new HibernateTask() {
        public boolean run(Session session) {
            List li = session.createQuery("select tg from TeachersGuide as tg where tg.simulation = :sim")
                    .setEntity("sim", simulation.getSimulation()).list();
            if (!li.isEmpty()) {
                guides.add((TeachersGuide) li.get(0));
            }
            return true;
        }
    });
    if (!guides.isEmpty()) {
        add(new LocalizedText("guide-text", "simulationMainPanel.teachersGuide",
                new Object[] { guides.get(0).getLinker().getHref(context, getPhetCycle()) }));
        //            Label visLabel = new Label( "tips-for-teachers-visible", "" );
        //            visLabel.setRenderBodyOnly( true ); // don't make anything appear
        //            add( visLabel );
        hasTeacherTips = true;
    } else {
        // make the teachers guide text (and whole section) invisible
        add(new InvisibleComponent("guide-text"));
        //            add( new InvisibleComponent( "tips-for-teachers-visible" ) );

        hasTeacherTips = false;
    }

    /*---------------------------------------------------------------------------*
    * contributions
    *----------------------------------------------------------------------------*/

    if (DistributionHandler.displayContributions(getPhetCycle())) {
        final List<Contribution> contributions = new LinkedList<Contribution>();
        HibernateUtils.wrapTransaction(getHibernateSession(), new HibernateTask() {
            public boolean run(Session session) {
                List list = session.createQuery(
                        "select c from Contribution as c where :simulation member of c.simulations and c.approved = true")
                        .setEntity("simulation", simulation.getSimulation()).list();
                for (Object o : list) {
                    Contribution contribution = (Contribution) o;
                    contributions.add(contribution);

                    // we need to read levels
                    contribution.getLevels();

                    // we also need to read the types
                    contribution.getTypes();

                    for (Object x : contribution.getSimulations()) {
                        Simulation sim = (Simulation) x;

                        // we need to be able to read these to determine the localized simulation title later
                        sim.getLocalizedSimulations();
                    }
                }
                return true;
            }
        });
        add(new ContributionBrowsePanel("contributions-panel", context, contributions, false));
        //            Label visLabel = new Label( "teacher-ideas-visible", "" );
        //            visLabel.setRenderBodyOnly( true ); // don't make anything appear
        //            add( visLabel );
    } else {
        add(new InvisibleComponent("contributions-panel"));
        //            add( new InvisibleComponent( "teacher-ideas-visible" ) );
    }

    /*---------------------------------------------------------------------------*
    * translations
    *----------------------------------------------------------------------------*/

    List<LocalizedSimulation> simulations = HibernateUtils.getLocalizedSimulationsMatching(
            getHibernateSession(), null, simulation.getSimulation().getName(), null);
    HibernateUtils.orderSimulations(simulations, context.getLocale());

    List<LocalizedSimulation> otherLocalizedSimulations = new LinkedList<LocalizedSimulation>();

    // TODO: improve model?
    for (final LocalizedSimulation sim : simulations) {
        if (!sim.getLocale().equals(simulation.getLocale())) {
            otherLocalizedSimulations.add(sim);
        }
    }

    // TODO: allow localization of locale display names
    ListView simulationList = new ListView<LocalizedSimulation>("simulation-main-translation-list",
            otherLocalizedSimulations) {
        protected void populateItem(ListItem<LocalizedSimulation> item) {
            LocalizedSimulation simulation = item.getModelObject();
            Locale simLocale = simulation.getLocale();
            RawLink runLink = simulation.getRunLink("simulation-main-translation-link");
            RawLink downloadLink = simulation.getDownloadLink("simulation-main-translation-download");
            String defaultLanguageName = simLocale.getDisplayName(context.getLocale());
            String languageName = ((PhetLocalizer) getLocalizer()).getString(
                    "language.names." + LocaleUtils.localeToString(simLocale), this, null, defaultLanguageName,
                    false);
            item.add(runLink);
            if (DistributionHandler.displayJARLink(getPhetCycle(), simulation)) {
                item.add(downloadLink);
            } else {
                item.add(new InvisibleComponent("simulation-main-translation-download"));
            }
            item.add(new Label("simulation-main-translation-title", simulation.getTitle()));
            Link lang1 = TranslatedSimsPage.getLinker(simLocale).getLink("language-link-1", context,
                    getPhetCycle());
            item.add(lang1);
            Link lang2 = TranslatedSimsPage.getLinker(simLocale).getLink("language-link-2", context,
                    getPhetCycle());
            item.add(lang2);
            lang1.add(new Label("simulation-main-translation-locale-name", languageName));
            lang2.add(new Label("simulation-main-translation-locale-translated-name",
                    simLocale.getDisplayName(simLocale)));

            WicketUtils.highlightListItem(item);
        }
    };
    add(simulationList);
    /*---------------------------------------------------------------------------*
    * run / download links
    *----------------------------------------------------------------------------*/

    // TODO: move from direct links to page redirections, so bookmarkables will be minimized
    RawLink runOnlineLink = simulation.getRunLink("run-online-link");
    add(runOnlineLink);

    RawLink downloadLink = simulation.getDownloadLink("run-offline-link");
    add(downloadLink);

    if (getPhetCycle().isInstaller()) {
        add(new InvisibleComponent("embed-button"));
    } else {
        add(new WebMarkupContainer("embed-button"));
    }

    final String directEmbedText = simulation.getDirectEmbeddingSnippet();
    String indirectEmbedText = simulation
            .getClickToLaunchSnippet(getPhetLocalizer().getString("embed.clickToLaunch", this));
    if (directEmbedText != null) {
        add(new Label("direct-embed-text", directEmbedText));
    } else {
        add(new InvisibleComponent("direct-embed-text"));
    }
    add(new Label("indirect-embed-text", indirectEmbedText) {
        {
            if (directEmbedText == null) {
                // if we can't directly embed, set our markup ID so that this text is automatically selected
                setMarkupId("embeddable-text");
                setOutputMarkupId(true);
            }
        }
    });

    /*---------------------------------------------------------------------------*
    * keywords / topics
    *----------------------------------------------------------------------------*/

    List<Keyword> keywords = new LinkedList<Keyword>();
    List<Keyword> topics = new LinkedList<Keyword>();

    // TODO: improve handling here
    Transaction tx = null;
    try {
        Session session = getHibernateSession();
        tx = session.beginTransaction();

        Simulation sim = (Simulation) session.load(Simulation.class, simulation.getSimulation().getId());
        //System.out.println( "Simulation keywords for " + sim.getName() );
        for (Object o : sim.getKeywords()) {
            Keyword keyword = (Keyword) o;
            keywords.add(keyword);
            //System.out.println( keyword.getKey() );
        }
        for (Object o : sim.getTopics()) {
            Keyword keyword = (Keyword) o;
            topics.add(keyword);
            //System.out.println( keyword.getKey() );
        }

        tx.commit();
    } catch (RuntimeException e) {
        logger.warn("Exception: " + e);
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                logger.error("ERROR: Error rolling back transaction", e1);
            }
            throw e;
        }
    }

    ListView topicList = new ListView<Keyword>("topic-list", topics) {
        protected void populateItem(ListItem<Keyword> item) {
            Keyword keyword = item.getModelObject();
            item.add(new RawLabel("topic-label", new ResourceModel(keyword.getKey())));
        }
    };
    add(topicList);
    if (topics.isEmpty()) {
        topicList.setVisible(false);
    }

    ListView keywordList = new ListView<Keyword>("keyword-list", keywords) {
        protected void populateItem(ListItem<Keyword> item) {
            Keyword keyword = item.getModelObject();
            Link link = SimsByKeywordPage.getLinker(keyword.getSubKey()).getLink("keyword-link", context,
                    getPhetCycle());
            //                Link link = new StatelessLink( "keyword-link" ) {
            //                    public void onClick() {
            //                        // TODO: fill in keyword links!
            //                    }
            //                };
            link.add(new RawLabel("keyword-label", new ResourceModel(keyword.getKey())));
            item.add(link);
        }
    };
    add(keywordList);
    if (keywords.isEmpty()) {
        keywordList.setVisible(false);
    }

    /*---------------------------------------------------------------------------*
    * system requirements
    *----------------------------------------------------------------------------*/

    /*
     * Requirements are laid out in 3 columns for java/flash sims and 4 columns for
     * HTML sims. Depending on the sim type, different content gets added to each
     * column.
     */
    List<String> column1 = new LinkedList<String>();
    List<String> column2 = new LinkedList<String>();
    List<String> column3 = new LinkedList<String>();
    List<String> column4 = new LinkedList<String>();

    // column headers for java/flash sims
    if (!simulation.getSimulation().isHTML()) {
        add(new Label("column1-header", "Windows"));
        add(new Label("column2-header", "Macintosh"));
        add(new Label("column3-header", "Linux"));
        add(new InvisibleComponent("column4-header"));

        column1.add("Microsoft Windows");
        column1.add("XP/Vista/7");

        column2.add("OS 10.5 or later");
    }
    // column headers for HTML sims
    else {
        add(new Label("column1-header", "Windows 7+ PCs"));
        add(new Label("column2-header", "Mac OS 10.7+ PCs"));
        add(new Label("column3-header", "iPad and iPad Mini with iOS"));
        add(new Label("column4-header", "Chromebook with Chrome OS"));
    }

    // column content for different sim types
    if (simulation.getSimulation().isJava()) {
        column1.add("Sun Java 1.5.0_15 or later");
        column2.add("Sun Java 1.5.0_19 or later");
        column3.add("Sun Java 1.5.0_15 or later");
    } else if (simulation.getSimulation().isFlash()) {
        column1.add("Macromedia Flash 9 or later");
        column2.add("Macromedia Flash 9 or later");
        column3.add("Macromedia Flash 9 or later");
    } else if (simulation.getSimulation().isHTML()) {
        column1.add("Internet Explorer 10+");
        column1.add("latest versions of Chrome and Firefox");
        column2.add("Safari 6.1 and up");
        column2.add("latest versions of Chrome and Firefox");
        column3.add("latest version of Safari");
        column4.add("latest version of Chrome");
    }

    // Add a list view for each column
    ListView column1View = new ListView<String>("column1-list", column1) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("column1-item", str));
        }
    };
    add(column1View);

    ListView column2View = new ListView<String>("column2-list", column2) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("column2-item", str));
        }
    };
    add(column2View);

    ListView column3View = new ListView<String>("column3-list", column3) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("column3-item", str));
        }
    };
    add(column3View);

    // show column4 only for HTML sims
    if (simulation.getSimulation().isHTML()) {
        ListView column4View = new ListView<String>("column4-list", column4) {
            protected void populateItem(ListItem<String> item) {
                String str = item.getModelObject();
                item.add(new Label("column4-item", str));
            }
        };
        add(column4View);
    } else {
        // column 4 is invisible for legacy sims
        add(new InvisibleComponent("column4-list"));
    }

    // so we don't emit an empty <table></table> that isn't XHTML Strict compatible
    if (otherLocalizedSimulations.isEmpty()) {
        simulationList.setVisible(false);
    }

    PhetLocalizer localizer = (PhetLocalizer) getLocalizer();

    /*---------------------------------------------------------------------------*
    * title
    *----------------------------------------------------------------------------*/

    // we initialize the title in the panel. then whatever page that wants to adopt this panel's "title" as the page
    // title can
    List<String> titleParams = new LinkedList<String>();
    titleParams.add(simulation.getEncodedTitle());
    for (Keyword keyword : keywords) {
        titleParams.add(localizer.getString(keyword.getKey(), this));
    }

    if (keywords.size() < 3) {
        title = simulation.getEncodedTitle();
    } else {
        try {
            title = StringUtils.messageFormat(localizer.getString("simulationPage.title", this),
                    titleParams.toArray());
        } catch (RuntimeException e) {
            e.printStackTrace();
            title = simulation.getEncodedTitle();
        }
    }

    addCacheParameter("title", title);

    /*---------------------------------------------------------------------------*
    * related simulations
    *----------------------------------------------------------------------------*/

    List<LocalizedSimulation> relatedSimulations = getRelatedSimulations(simulation);
    if (relatedSimulations.isEmpty()) {
        add(new InvisibleComponent("related-simulations-panel"));
        add(new InvisibleComponent("related-simulations-visible"));
    } else {
        add(new SimulationDisplayPanel("related-simulations-panel", context, relatedSimulations));
        add(new RawBodyLabel("related-simulations-visible", "")); // visible but shows nothing, so the related simulations "see below" shows up
    }

    /*---------------------------------------------------------------------------*
    * more info (design team, libraries, thanks, etc
    *----------------------------------------------------------------------------*/

    List<String> designTeam = new LinkedList<String>();
    List<String> libraries = new LinkedList<String>();
    List<String> thanks = new LinkedList<String>();
    List<String> learningGoals = new LinkedList<String>();

    String rawDesignTeam = simulation.getSimulation().getDesignTeam();
    if (rawDesignTeam != null) {
        for (String item : rawDesignTeam.split("<br/>")) {
            if (item != null && item.length() > 0) {
                designTeam.add(item);
            }
        }
    }

    String rawLibraries = simulation.getSimulation().getLibraries();
    if (rawLibraries != null) {
        for (String item : rawLibraries.split("<br/>")) {
            if (item != null && item.length() > 0) {
                libraries.add(item);
            }
        }
    }

    String rawThanks = simulation.getSimulation().getThanksTo();
    if (rawThanks != null) {
        for (String item : rawThanks.split("<br/>")) {
            if (item != null && item.length() > 0) {
                thanks.add(item);
            }
        }
    }

    String rawLearningGoals = getLocalizer().getString(simulation.getSimulation().getLearningGoalsKey(), this);
    if (rawLearningGoals != null) {
        for (String item : rawLearningGoals.split("<br/>")) {
            if (item != null && item.length() > 0) {
                learningGoals.add(item);
            }
        }
    }

    ListView designView = new ListView<String>("design-list", designTeam) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("design-item", str));
        }
    };
    if (designTeam.isEmpty()) {
        designView.setVisible(false);
    }
    add(designView);

    ListView libraryView = new ListView<String>("library-list", libraries) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("library-item", str));
        }
    };
    if (libraries.isEmpty()) {
        libraryView.setVisible(false);
    }
    add(libraryView);

    ListView thanksView = new ListView<String>("thanks-list", thanks) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new Label("thanks-item", str));
        }
    };
    if (thanks.isEmpty()) {
        thanksView.setVisible(false);
    }
    add(thanksView);

    // TODO: consolidate common behavior for these lists
    ListView learningGoalsView = new ListView<String>("learning-goals", learningGoals) {
        protected void populateItem(ListItem<String> item) {
            String str = item.getModelObject();
            item.add(new RawLabel("goal", str));
        }
    };
    if (learningGoals.isEmpty()) {
        learningGoalsView.setVisible(false);
    }
    add(learningGoalsView);

    addDependency(new EventDependency() {

        private IChangeListener projectListener;
        private IChangeListener stringListener;
        private IChangeListener teacherGuideListener;

        @Override
        protected void addListeners() {
            projectListener = new AbstractChangeListener() {
                public void onUpdate(Object object, PostUpdateEvent event) {
                    if (HibernateEventListener.getSafeHasChanged(event, "visible")) {
                        invalidate();
                    }
                }
            };
            teacherGuideListener = new AbstractChangeListener() {
                @Override
                public void onInsert(Object object, PostInsertEvent event) {
                    TeachersGuide guide = (TeachersGuide) object;
                    if (guide.getSimulation().getId() == simulation.getSimulation().getId()) {
                        invalidate();
                    }
                }

                @Override
                public void onUpdate(Object object, PostUpdateEvent event) {
                    TeachersGuide guide = (TeachersGuide) object;
                    if (guide.getSimulation().getId() == simulation.getSimulation().getId()) {
                        invalidate();
                    }
                }

                @Override
                public void onCollectionUpdate(Object object, PostCollectionUpdateEvent event) {
                    TeachersGuide guide = (TeachersGuide) object;
                    if (guide.getSimulation().getId() == simulation.getSimulation().getId()) {
                        invalidate();
                    }
                }

                @Override
                public void onDelete(Object object, PostDeleteEvent event) {
                    TeachersGuide guide = (TeachersGuide) object;
                    if (guide.getSimulation().getId() == simulation.getSimulation().getId()) {
                        invalidate();
                    }
                }
            };
            stringListener = createTranslationChangeInvalidator(context.getLocale());
            HibernateEventListener.addListener(Project.class, projectListener);
            HibernateEventListener.addListener(TranslatedString.class, stringListener);
            HibernateEventListener.addListener(Simulation.class, getAnyChangeInvalidator());
            HibernateEventListener.addListener(LocalizedSimulation.class, getAnyChangeInvalidator());
        }

        @Override
        protected void removeListeners() {
            HibernateEventListener.removeListener(Project.class, projectListener);
            HibernateEventListener.removeListener(TranslatedString.class, stringListener);
            HibernateEventListener.removeListener(Simulation.class, getAnyChangeInvalidator());
            HibernateEventListener.removeListener(LocalizedSimulation.class, getAnyChangeInvalidator());
        }
    });

    if (DistributionHandler.showSimSponsor(getPhetCycle())) {
        // this gets cached, so it will stay the same for the sim (but will be different for different sims)
        add(new SimSponsorPanel("pearson-sponsor", context, Sponsor.chooseRandomSimSponsor()));
    } else {
        add(new InvisibleComponent("pearson-sponsor"));
    }

    if (getPhetCycle().isInstaller()) {
        add(new WebMarkupContainer("sim-sponsor-installer-js"));
    } else {
        add(new InvisibleComponent("sim-sponsor-installer-js"));
    }

    add(new LocalizedText("submit-a", "simulationMainPanel.submitActivities",
            new Object[] { ContributionCreatePage.getLinker().getHref(context, getPhetCycle()) }));

    /*---------------------------------------------------------------------------*
    * FAQ
    *----------------------------------------------------------------------------*/

    if (simulation.getSimulation().isFaqVisible() && simulation.getSimulation().getFaqList() != null) {
        add(new LocalizedText("faq-text", "simulationMainPanel.simulationHasFAQ",
                new Object[] { SimulationFAQPage.getLinker(simulation).getHref(context, getPhetCycle()),
                        simulation.getSimulation().getFaqList().getPDFLinker(getMyLocale()).getHref(context,
                                getPhetCycle()) }));
    } else {
        add(new InvisibleComponent("faq-text"));
    }

    /*---------------------------------------------------------------------------*
    * metadata
    *----------------------------------------------------------------------------*/

    // add the necessary license meta tags for our license list
    add(new ListView<String>("license-list", simulation.getSimulation().getLicenseURLs()) {
        @Override
        protected void populateItem(final ListItem<String> item) {
            item.add(new WebMarkupContainer("license-meta-tag") {
                {
                    add(new AttributeModifier("content", true, new Model<String>(item.getModelObject())));
                }
            });
        }
    });

    add(new WebMarkupContainer("schema-thumbnail") {
        {
            add(new AttributeModifier("content", true, new Model<String>(
                    StringUtils.makeUrlAbsoluteProduction(simulation.getSimulation().getThumbnailUrl()))));
        }
    });

    if (simulation.getSimulation().getCreateTime() != null) {
        add(new WebMarkupContainer("schema-date-created") {
            {
                add(new AttributeModifier("content", true, new Model<String>(
                        WebsiteConstants.ISO_8601.format(simulation.getSimulation().getCreateTime()))));
            }
        });
    } else {
        add(new InvisibleComponent("schema-date-created"));
    }

    if (simulation.getSimulation().getUpdateTime() != null) {
        add(new WebMarkupContainer("schema-date-modified") {
            {
                add(new AttributeModifier("content", true, new Model<String>(
                        WebsiteConstants.ISO_8601.format(simulation.getSimulation().getUpdateTime()))));
            }
        });
    } else {
        add(new InvisibleComponent("schema-date-modified"));
    }

    List<Alignment> alignments = new ArrayList<Alignment>();
    alignments.addAll(simulation.getSimulation().getAlignments());
    alignments.addAll(simulation.getSimulation().getSecondaryAlignments());

    add(new ListView<Alignment>("alignment-list", alignments) {
        @Override
        protected void populateItem(final ListItem<Alignment> item) {
            item.add(new WebMarkupContainer("alignment") {
                {
                    add(new AttributeModifier("content", true,
                            new Model<String>(item.getModelObject().getUrl())));
                }
            });
        }
    });

    add(new WebMarkupContainer("schema-inLanguage") {
        {
            // currently, we fake BCP 47 somewhat by replacing the underscore with a dash if necessary
            add(new AttributeModifier("content", true,
                    new Model<String>(simulation.getLocaleString().replace('_', '-'))));
        }
    });
}