Example usage for org.apache.wicket.model AbstractReadOnlyModel AbstractReadOnlyModel

List of usage examples for org.apache.wicket.model AbstractReadOnlyModel AbstractReadOnlyModel

Introduction

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

Prototype

AbstractReadOnlyModel

Source Link

Usage

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

License:Open Source License

public PlayedGameListPanel(String id, IModel<List<Game>> gamesModel, final IModel<Player> selectedPlayerModel,
        final RatingCalculator rating) {
    super(id);/*from  w w w . ja v  a 2  s  . c om*/

    setOutputMarkupId(true);

    final PaginationModel<Game> paginationModel = new PaginationModel<Game>(gamesModel, 0, 20);

    add(new ListView<Game>("games", paginationModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(final ListItem<Game> item) {
            item.add(RowColorModifier.create(item));
            PageParameters pp = new PageParameters();
            pp.set(0, item.getModelObject().getId());
            BookmarkablePageLink<Void> link = new SecureExecutionBookmarkablePageLink<Void>("gameLink",
                    EditGamePage.class, pp);
            item.add(link);

            link.add(new DateLabel("date", new PropertyModel<Date>(item.getModel(), "date"),
                    new PatternDateConverter("yyyy-MM-dd", false)));

            //Add the winning and losing team
            Game game = item.getModelObject();
            List<GameTeam> teamsSortedByScore = game.getTeamsSortedByScore();
            item.add(new GameTeamPanel("team1", new Model<GameTeam>(teamsSortedByScore.get(0)),
                    selectedPlayerModel, rating));
            item.add(new GameTeamPanel("team2", new Model<GameTeam>(teamsSortedByScore.get(1)),
                    selectedPlayerModel, rating));

            //Add the game score
            item.add(new Label("score", new AbstractReadOnlyModel<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    StringBuilder b = new StringBuilder();
                    Game game = item.getModelObject();
                    List<GameTeam> teamsSortedByScore = game.getTeamsSortedByScore();
                    b.append(teamsSortedByScore.get(0).getScore());
                    b.append(" : ");
                    b.append(teamsSortedByScore.get(1).getScore());
                    return b.toString();
                }
            }));
        }
    });

    WebMarkupContainer footer = new WebMarkupContainer("footer") {
        private static final long serialVersionUID = 1L;

        @Override
        public boolean isVisible() {
            return paginationModel.isPaginationNeeded();
        }
    };
    add(footer);

    footer.add(new NavigationPanel<Game>("navigation", paginationModel) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onPageChanged(AjaxRequestTarget target, int selectedPage) {
            target.add(PlayedGameListPanel.this);
        }
    });
}

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);//from w ww  . j a  v  a  2 s . com

    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.RatingCalculatorSelector.java

License:Open Source License

public RatingCalculatorSelector(String id, IModel<RatingCalculatorType> model) {
    super(id, model);

    setRenderBodyOnly(true);/*from   w  w w  .  j a v  a2 s.  c o  m*/

    Select<RatingCalculatorType> select = new Select<RatingCalculatorType>("select", model);
    select.add(AttributeAppender.replace("class", new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            return RatingCalculatorSelector.this.getMarkupAttributes().getString("class", "");
        }
    }));
    add(select);

    List<RatingCalculatorType> groupNames = Arrays.asList(RatingCalculatorType.values());

    select.add(new SelectOptions<RatingCalculatorType>("selectOptions", groupNames,
            new IOptionRenderer<RatingCalculatorType>() {
                @Override
                public String getDisplayValue(RatingCalculatorType type) {
                    return type.getLongName();
                }

                @Override
                public IModel<RatingCalculatorType> getModel(RatingCalculatorType type) {
                    return new Model<RatingCalculatorType>(type);
                }

            }));
}

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

License:Open Source License

public static RowColorModifier create(final ListItem<?> listItem) {
    return new RowColorModifier(new AbstractReadOnlyModel<String>() {
        private static final long serialVersionUID = 1L;

        @Override//  w ww .j a  va2  s . c  o  m
        public String getObject() {
            return listItem.getIndex() % 2 == 0 ? "odd" : "even";
        }
    });
}

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);// w w w. j a  v  a 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.daily.DailyGamePage.java

License:Open Source License

public DailyGamePage(final PageParameters parameters) {
    long leagueId = parameters.get("league").toLong(-1);
    if (leagueId < 1) {
        goToDefaultLeague();/*from w  w  w.  j a v  a  2s  . com*/
    }

    league = scoreBoardService.getLeague(leagueId);
    if (league == null) {
        goToDefaultLeague();
    }

    games = scoreBoardService.getAllGames(league);
    ratings = RatingProvider.getRatings(league, games);
    Collections.sort(games, new GameComparator());

    add(new Label("leagueName", league.getName()));

    WebMarkupContainer chartToggle = new WebMarkupContainer("chartToggle");
    chartToggle.add(AttributeAppender.replace("data-target", new AbstractReadOnlyModel<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            return "#" + chartContainer.getMarkupId();
        }
    }));
    chartToggle.add(new TooltipBehavior(new StringResourceModel("clickToSeeChart", null), Placement.RIGHT));
    add(chartToggle);

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

        @Override
        protected Player load() {
            ScoreBoardSession scoreBoardSession = ScoreBoardSession.get();
            if (scoreBoardSession.isAuthenticated()) {
                return scoreBoardSession.getUser().getPlayer();
            }
            return null;
        }
    };

    addGameResults();

    addPlayerStatistics();
    addTeamsStatistics();
}

From source file:dk.frankbille.scoreboard.game.EditGamePage.java

License:Open Source License

public EditGamePage(PageParameters pageParameters) {
    long gameId = pageParameters.get(0).toLong(-1);

    if (gameId > 0) {
        game = scoreBoardService.getGame(gameId);
    } else {/*ww w  .j av  a2s.com*/
        game = createNewGame();
    }

    add(new Label("editGameTitle", new AbstractReadOnlyModel<String>() {
        private static final long serialVersionUID = 1L;

        @Override
        public String getObject() {
            Localizer localizer = Application.get().getResourceSettings().getLocalizer();
            if (game.getId() == null) {
                return localizer.getString("newGame", EditGamePage.this);
            } else {
                return localizer.getString("editGame", EditGamePage.this);
            }
        }
    }));

    Form<Void> form = new Form<Void>("form") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit() {
            scoreBoardService.saveGame(game);

            PageParameters pp = new PageParameters();
            pp.add("league", game.getLeague().getId());
            getRequestCycle().setResponsePage(DailyGamePage.class, pp);
        }
    };
    add(form);

    form.add(new FeedbackPanel("feedback"));

    form.add(new DateField("gameDate", new PropertyModel<Date>(this, "game.date")));

    form.add(new GameTeamPanel("team1", new PropertyModel<GameTeam>(this, "game.team1")));
    form.add(new GameTeamPanel("team2", new PropertyModel<GameTeam>(this, "game.team2")));

    IModel<League> defaultLeagueModel = new PropertyModel<League>(this, "game.league");
    form.add(new LeagueSelector("leagueField", defaultLeagueModel));
    //      IModel<List<League>> possibleLeaguesModel = new LoadableDetachableModel<List<League>>() {
    //         private static final long serialVersionUID = 1L;
    //
    //         @Override
    //         protected List<League> load() {
    //            return scoreBoardService.getAllLeagues();
    //         }
    //      };
    //      ChoiceRenderer<League> renderer = new ChoiceRenderer<League>("name", "id");
    //
    //      DropDownChoice<League> leagueField = new DropDownChoice<League>("leagueField", defaultLeagueModel, possibleLeaguesModel, renderer);
    //      leagueField.add(new Select2Enabler());
    //      form.add(leagueField);
}

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

License:Apache License

public ConfigurationItemPanel(final Attribute attribute, final IModel<Serializable> currentValue,
        IModel<String> errorMessage, String id) {
    super(id);//from   w w w.  j  av a2  s.  com
    this.attribute = attribute;

    String panelTextFieldID = attribute.getID() + "Input";
    String panelSmallLabelID = attribute.getID() + "Details";

    String attributeDefault = attribute.getDefaultValue() != null && attribute.getDefaultValue().length > 0
            && attribute.getDefaultValue()[0] != null ? attribute.getDefaultValue()[0] : null;

    String methodReturnSimpleName = attribute.getMethodReturnType().getSimpleName();

    final boolean usingDefault;

    configValue = currentValue;

    if (currentValue.getObject() == null
            || (currentValue.getObject() instanceof String && ((String) currentValue.getObject()).isEmpty())) {
        currentValue.setObject(attributeDefault);
        usingDefault = true;
    } else {
        usingDefault = false;
    }

    String propertyNameAndCardinality = attribute.getName() + "(" + attribute.getCardinalityDef().name() + ")";
    WebMarkupContainer formLabel = new WebMarkupContainer("nameLabel");

    Label labelText = new Label("labelText", Model.of(propertyNameAndCardinality));
    formLabel.add(labelText);

    final Label labelMessage = new ErrorLabel("labelMsg", errorMessage);

    formLabel.add(labelMessage);

    formLabel.add(AttributeModifier.replace("for", panelTextFieldID));
    formLabel.add(AttributeModifier.replace("title", attribute.getInputType().getSimpleName()));
    add(formLabel);

    final Class attributeInputType = attribute.getInputType();
    final Class attributeMethodType = attribute.getMethodReturnType();

    //WebMarkupContainer inputArea = new WebMarkupContainer("inputArea");
    InputFragment fragment;

    if (attributeInputType.equals(Number.class)) {
        fragment = new NumberFieldFragment("inputArea", "numberBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, (IModel<Number>) configValue);
    } else if (attributeInputType.equals(String.class) && attributeMethodType.equals(URL.class)) {
        fragment = new URLFieldFragment("inputArea", "urlBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, (IModel<String>) configValue);
    } else if (attributeInputType.equals(Boolean.class)) {
        fragment = new BooleanFieldFragment("inputArea", "checkBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, (IModel<Boolean>) configValue);
    } else if (attributeInputType.equals(String.class)) {
        fragment = new TextFieldFragment("inputArea", "textBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, (IModel<String>) configValue);
    } else if (attributeInputType.equals(Character[].class)) {
        fragment = new PasswordFragment("inputArea", "passwordBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, (IModel<Character[]>) configValue);
    } else {
        fragment = new UnknownTypeFragment("inputArea", "textBox", this, attribute, panelTextFieldID,
                panelSmallLabelID, configValue);
    }

    //inputArea.add(fragment);
    add(fragment);

    //        formInput.add(AttributeModifier.replace("type", new LoadableDetachableModel<String>() {
    //            @Override
    //            protected String load() {
    //                if (attributeInputType == Character[].class) {
    //                    return "password";
    //                } else if (Number.class.isAssignableFrom(attributeInputType)) {
    //                    return "number";
    //                } else if(URL.class.isAssignableFrom(attributeMethodType)){
    //                    return "url";
    //                }
    //                else{
    //                    return "text";
    //                }
    //            }
    //        }));

    fragment.getFormInput().add(AttributeModifier.append("style", new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            if (labelMessage.isVisible()) {
                return "background-color:#d9534f;";
            } else if (attribute.getCardinalityDef().equals(Property.Cardinality.Required)
                    && currentValue.getObject() == null) {
                return "background-color:#d9534f;";
            } else if (usingDefault) {
                return "background-color:#f0ad4e;";
            } else {
                return null;
            }
        }

    }));

    Label smallLabel = new Label("smallLabel", attribute.getDescription());

    smallLabel.add(AttributeModifier.replace("id", panelSmallLabelID));

    add(smallLabel);

}

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

License:Apache License

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

    /*/* ww  w.  j  a v  a 2  s.c  o  m*/
     * 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.calendar.PeriodsCalendarPanel.java

License:Apache License

@Override
protected IModel<List<TimeSlot<PeriodBookingTimeSlotPayload>>> getTimeSlotModel(final DateMidnight date) {
    return new AbstractReadOnlyModel<List<TimeSlot<PeriodBookingTimeSlotPayload>>>() {
        private static final long serialVersionUID = 1L;

        @Override/*from  ww  w . j  a  v a2 s.c om*/
        public List<TimeSlot<PeriodBookingTimeSlotPayload>> getObject() {
            List<TimeSlot<PeriodBookingTimeSlotPayload>> timeSlots = new ArrayList<TimeSlot<PeriodBookingTimeSlotPayload>>();
            List<DatePeriod> periods = datePeriodsModel.getObject();
            DatePeriod currentDatePeriod = null;
            for (DatePeriod datePeriod : periods) {
                if (datePeriod.getDate().equals(date)) {
                    currentDatePeriod = datePeriod;
                    break;
                }
            }

            if (currentDatePeriod != null) {
                List<Period> periodsList = currentDatePeriod.getPeriods();
                for (Period period : periodsList) {
                    DateTime startTime = period.getStartTime().toDateTime(date);
                    DateTime endTime = period.getEndTime().toDateTime(date);

                    DateTime time = startTime;
                    while (time.isBefore(endTime)) {
                        /*
                         * Booking
                         */
                        Bookings bookings = bookingsModel.getObject();
                        Booking booking = bookings.getBooking(period, time);

                        PeriodBookingTimeSlotPayload payload = new PeriodBookingTimeSlotPayload();
                        payload.setPeriod(period);
                        payload.setBooking(booking);

                        timeSlots.add(new TimeSlot<PeriodBookingTimeSlotPayload>(time.toLocalTime(),
                                time.toLocalTime().plusMinutes(period.getLessonDuration()), payload));

                        time = time.plusMinutes(period.getIntervalBetweenLessonStart());
                    }
                }
            }

            return timeSlots;
        }

        @Override
        public void detach() {
            datePeriodsModel.detach();
            bookingsModel.detach();
        }
    };
}