code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import com.github.wolfie.blackboard.Event;
import com.github.wolfie.blackboard.Listener;
import com.github.wolfie.blackboard.annotation.ListenerMethod;
import com.vaadin.ui.Component;
public class PlatesInfoEvent implements Event {
public Component source;
PlatesInfoEvent(Component source) {
this.source = source;
}
public interface PlatesInfoListener extends Listener {
@ListenerMethod
public void plateLoadingUpdate(final PlatesInfoEvent event);
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
public enum TimeStoppedNotificationReason {
UNKNOWN,
STOP_START_BUTTON,
FORCE_AS_CURRENT,
CURRENT_LIFTER_CHANGE,
LIFTER_WITHDRAWAL,
REFEREE_DECISION
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.util.ArrayList;
import java.util.List;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.generators.CommonFieldFactory;
import org.concordiainternational.competition.ui.list.GenericList;
import org.concordiainternational.competition.utils.ItemAdapter;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Window;
/**
* Editing of Competition Session (aka Group) information.
*
* @author jflamy
*/
@SuppressWarnings({ "serial" })
public class SessionForm extends Form {
final private static Logger logger = LoggerFactory.getLogger(SessionForm.class);
Window window = null;
GenericList<?> parentList = null;
private Item item;
public SessionForm() {
super();
this.setFormFieldFactory(new CommonFieldFactory(CompetitionApplication.getCurrent()));
setWriteThrough(true);
HorizontalLayout footer = new HorizontalLayout();
footer.setSpacing(true);
footer.addComponent(ok);
footer.addComponent(cancel);
footer.setVisible(true);
setFooter(footer);
}
Button ok = new Button(Messages.getString("Common.OK", CompetitionApplication.getCurrentLocale()),new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
commit();
Object object = ItemAdapter.getObject(item);
Session hbnSession = CompetitionApplication.getCurrent().getHbnSession();
hbnSession.merge(object);
hbnSession.flush();
closeWindow();
}
});
Button cancel = new Button(Messages.getString("Common.cancel", CompetitionApplication.getCurrentLocale()),new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
discard();
closeWindow();
}
});
@Override
public void setItemDataSource(Item newDataSource) {
item = newDataSource;
if (newDataSource != null) {
List<Object> orderedProperties = new ArrayList<Object>();
orderedProperties.add("name");
orderedProperties.add("weighInTime");
orderedProperties.add("competitionTime");
orderedProperties.add("platform");
orderedProperties.add("categories");
orderedProperties.add("announcer");
orderedProperties.add("marshall");
orderedProperties.add("timeKeeper");
orderedProperties.add("technicalController");
orderedProperties.add("referee1");
orderedProperties.add("referee2");
orderedProperties.add("referee3");
orderedProperties.add("jury");
super.setItemDataSource(newDataSource, orderedProperties);
getFooter().setVisible(true);
} else {
super.setItemDataSource(null);
getFooter().setVisible(false);
}
}
@Override
public Window getWindow() {
return window;
}
public void setWindow(Window window) {
this.window = window;
}
public GenericList<?> getParentList() {
return parentList;
}
public void setParentList(GenericList<?> parentList) {
this.parentList = parentList;
}
/**
*
*/
private void closeWindow() {
logger.debug("closeWindow {}",parentList);
if (window != null) {
Window parent = window.getParent();
parent.removeWindow(window);
}
if (parentList != null) {
// this could be improved, but little gain as this function is called once per competition session only.
if (parentList instanceof SessionList) {
// kludge to force update of editable table;
// need to investigate why this is happening even though we are passing the table item.
parentList.toggleEditable();
parentList.toggleEditable();
} else {
parentList.refresh();
}
}
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Locale;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import org.concordiainternational.competition.decision.IDecisionController;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent.MessageDisplayListener;
import org.concordiainternational.competition.publicAddress.PublicAddressTimerEvent;
import org.concordiainternational.competition.publicAddress.PublicAddressTimerEvent.MessageTimerListener;
import org.concordiainternational.competition.timer.CountdownTimer;
import org.concordiainternational.competition.timer.CountdownTimerListener;
import org.concordiainternational.competition.ui.SessionData.UpdateEvent;
import org.concordiainternational.competition.ui.SessionData.UpdateEventListener;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.DecisionLightsWindow;
import org.concordiainternational.competition.ui.generators.TimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.Action;
import com.vaadin.event.ShortcutAction;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* Show an WebPage underneath a banner.
* @author jflamy
*
*/
public class AttemptBoardView extends VerticalLayout implements
ApplicationView,
CountdownTimerListener,
MessageDisplayListener,
MessageTimerListener,
Window.CloseListener,
URIHandler,
DecisionEventListener
{
public final static Logger logger = LoggerFactory.getLogger(AttemptBoardView.class);
private static final long serialVersionUID = 1437157542240297372L;
public String urlString;
private String platformName;
private SessionData masterData;
private GridLayout grid;
final private transient CompetitionApplication app;
private Label nameLabel = new Label("", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label firstNameLabel = new Label("", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label clubLabel = new Label("", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label attemptLabel = new Label("", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label timeDisplayLabel = new Label();
private Label weightLabel = new Label();
private LoadImage plates;
private UpdateEventListener updateListener;
private DecisionLightsWindow decisionLights;
protected boolean waitingForDecisionLightsReset;
private ShortcutActionListener action1ok;
private ShortcutActionListener action1fail;
private ShortcutActionListener action2ok;
private ShortcutActionListener action2fail;
private ShortcutActionListener action3ok;
private ShortcutActionListener action3fail;
private ShortcutActionListener startAction;
private ShortcutActionListener stopAction;
private ShortcutActionListener oneMinuteAction;
private ShortcutActionListener twoMinutesAction;
public AttemptBoardView(boolean initFromFragment, String viewName, boolean publicFacing) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
this.publicFacing = publicFacing;
}
this.app = CompetitionApplication.getCurrent();
boolean prevDisabledPush = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
if (platformName == null) {
// get the default platform nameLabel
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
create(app);
masterData = app.getMasterData(platformName);
// we cannot call push() at this point
synchronized (app) {
boolean prevDisabled = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
createDecisionLights();
plates = new LoadImage(null);
display(platformName, masterData);
} finally {
app.setPusherDisabled(prevDisabled);
}
logger.debug("browser panel: push disabled = {}",app.getPusherDisabled());
}
// URI handler must remain, so is not part of the register/unRegister paire
app.getMainWindow().addURIHandler(this);
registerAsListener();
} finally {
app.setPusherDisabled(prevDisabledPush);
}
}
/**
*
*/
protected void createDecisionLights() {
decisionLights = new DecisionLightsWindow(false, publicFacing);
decisionLights.setSizeFull();
decisionLights.setMargin(false);
}
private UpdateEventListener registerAsListener(final String platformName1, final SessionData masterData1) {
// locate the current group data for the platformName
if (masterData1 != null) {
logger.debug(urlString + "{} listening to: {}", platformName1, masterData1); //$NON-NLS-1$
//masterData.addListener(SessionData.UpdateEvent.class, this, "update"); //$NON-NLS-1$
SessionData.UpdateEventListener listener = new SessionData.UpdateEventListener() {
@Override
public void updateEvent(UpdateEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
// logger.debug("request to display {}",
// AttemptBoardView.this);
if (!waitingForDecisionLightsReset) {
display(platformName1, masterData1);
}
}
}).start();
}
};
masterData1.addListener(listener); //$NON-NLS-1$
return listener;
} else {
logger.debug(urlString + "{} NOT listening to: = {}", platformName1, masterData1); //$NON-NLS-1$
return null;
}
}
/**
* @param app1
* @param platformName
* @throws MalformedURLException
*/
private void create(UserActions app1) {
this.setSizeFull();
grid = new GridLayout(4,4);
grid.setSizeFull();
grid.setMargin(true);
grid.addStyleName("newAttemptBoard");
grid.setColumnExpandRatio(0, 50.0F);
grid.setColumnExpandRatio(1, 50.0F);
grid.setColumnExpandRatio(2, 0.0F);
grid.setColumnExpandRatio(3, 0.0F);
grid.setRowExpandRatio(0, 0.0F);
grid.setRowExpandRatio(1, 0.0F);
grid.setRowExpandRatio(2, 65.0F);
grid.setRowExpandRatio(3, 35.0F);
// we do not add the time display, plate display
// and decision display -- they react to timekeeping
grid.addComponent(nameLabel, 0, 0, 3, 0);
nameLabel.setSizeUndefined();
nameLabel.addStyleName("text");
grid.setComponentAlignment(nameLabel, Alignment.MIDDLE_LEFT);
grid.addComponent(firstNameLabel, 0, 1, 2, 1);
firstNameLabel.setSizeUndefined();
firstNameLabel.addStyleName("text");
grid.setComponentAlignment(firstNameLabel, Alignment.MIDDLE_LEFT);
grid.addComponent(clubLabel, 3, 1, 3, 1);
clubLabel.setSizeUndefined();
clubLabel.addStyleName("text");
grid.setComponentAlignment(clubLabel, Alignment.MIDDLE_CENTER);
grid.addComponent(weightLabel, 3, 2, 3, 2);
weightLabel.setSizeUndefined();
weightLabel.addStyleName("weightLabel");
grid.setComponentAlignment(weightLabel, Alignment.MIDDLE_CENTER);
grid.addComponent(attemptLabel, 3, 3, 3, 3);
attemptLabel.setSizeUndefined();
attemptLabel.addStyleName("text");
grid.setComponentAlignment(attemptLabel, Alignment.MIDDLE_CENTER);
timeDisplayLabel.setSizeUndefined();
timeDisplayLabel.addStyleName("largeCountdown");
this.addComponent(grid);
this.setExpandRatio(grid, 100.0F);
}
/**
* @param platformName1
* @param masterData1
* @throws RuntimeException
*/
private void display(final String platformName1, final SessionData masterData1) throws RuntimeException {
if (paShown) {
return;
}
synchronized (app) {
final Lifter currentLifter = masterData1.getCurrentLifter();
if (currentLifter != null) {
boolean done = fillLifterInfo(currentLifter);
updateTime(masterData1);
showDecisionLights(false);
timeDisplayLabel.setSizeUndefined();
timeDisplayLabel.setVisible(!done);
} else {
logger.debug("lifter null");
hideAll();
}
}
logger.debug("prior to display push disabled={}",app.getPusherDisabled());
app.push();
}
/**
*
*/
protected void hideAll() {
nameLabel.setValue(getWaitingMessage()); //$NON-NLS-1$
showDecisionLights(false);
timeDisplayLabel.setSizeUndefined();
timeDisplayLabel.setVisible(false);
firstNameLabel.setValue("");
clubLabel.setValue("");
attemptLabel.setValue("");
weightLabel.setValue("");
plates.setVisible(false);
}
/**
* @return message used when Announcer has not selected a group
*/
private String getWaitingMessage() {
String message = ""; //Messages.getString("ResultFrame.Waiting", CompetitionApplication.getCurrentLocale());
// List<Competition> competitions = Competition.getAll();
// if (competitions.size() > 0) {
// message = competitions.get(0).getCompetitionName();
// }
return message;
}
@Override
public void refresh() {
display(platformName, masterData);
}
public boolean fillLifterInfo(Lifter lifter) {
final Locale locale = CompetitionApplication.getCurrentLocale();
final int currentTry = 1 + (lifter.getAttemptsDone() >= 3 ? lifter.getCleanJerkAttemptsDone() : lifter
.getSnatchAttemptsDone());
boolean done = currentTry > 3;
synchronized (app) {
displayName(lifter, locale, done);
displayAttemptNumber(lifter, locale, currentTry, done);
displayRequestedWeight(lifter, locale, done);
}
app.push();
return done;
}
/**
* @param lifter
* @param alwaysShowName
* @param sb
* @param done
*/
private void displayName(Lifter lifter, final Locale locale, boolean done) {
// display lifter nameLabel and affiliation
if (!done) {
final String lastName = lifter.getLastName();
final String firstName = lifter.getFirstName();
final String club = lifter.getClub();
nameLabel.setValue(lastName.toUpperCase());
firstNameLabel.setValue(firstName);
clubLabel.setValue(club);
//nameLabel.setValue(lastName.toUpperCase() + " " + firstName + " " + club); //$NON-NLS-1$ //$NON-NLS-2$
//grid.addComponent(nameLabel, 0, 0, 3, 0);
} else {
nameLabel.setValue(MessageFormat.format(
Messages.getString("AttemptBoard.Done", locale), masterData.getCurrentSession().getName())); //$NON-NLS-1$
firstNameLabel.setValue("");
clubLabel.setValue("");
//grid.addComponent(nameLabel, 0, 0, 3, 0);
}
}
private void showDecisionLights(boolean decisionLightsVisible) {
// logger.debug("showDecisionLights {}",decisionLightsVisible);
// remove everything
grid.removeComponent(timeDisplayLabel);
grid.removeComponent(decisionLights);
grid.removeComponent(plates);
if (decisionLightsVisible) {
grid.addComponent(decisionLights,0,2,2,3);
decisionLights.setSizeFull();
decisionLights.setMargin(true);
grid.setComponentAlignment(decisionLights, Alignment.TOP_LEFT);
} else {
grid.addComponent(timeDisplayLabel, 0, 2, 1, 3);
grid.addComponent(plates, 2, 2, 2, 3);
plates.computeImageArea(masterData, masterData.getPlatform());
grid.setComponentAlignment(timeDisplayLabel, Alignment.MIDDLE_CENTER);
grid.setComponentAlignment(plates, Alignment.MIDDLE_CENTER);
timeDisplayLabel.setVisible(true);
plates.setVisible(true);
}
}
/**
* @param lifter
* @param sb
* @param locale
* @param currentTry
* @param done
*/
private void displayAttemptNumber(Lifter lifter, final Locale locale, final int currentTry, boolean done) {
// display current attemptLabel number
if (!done) {
//appendDiv(sb, lifter.getNextAttemptRequestedWeight()+Messages.getString("Common.kg",locale)); //$NON-NLS-1$
final String lift = lifter.getAttemptsDone() >= 3 ? Messages.getString("Common.shortCleanJerk", locale) //$NON-NLS-1$
: Messages.getString("Common.shortSnatch", locale);//$NON-NLS-1$
String tryInfo = MessageFormat.format(Messages.getString("ResultFrame.tryNumber", locale), //$NON-NLS-1$
currentTry, lift);
attemptLabel.setValue(tryInfo.replace(" ","<br>"));
} else {
attemptLabel.setValue("");
}
//grid.addComponent(attemptLabel, 3, 3, 3, 3); //$NON-NLS-1$
}
/**
* @param lifter
* @param sb
* @param locale
* @param done
* @return
*/
private void displayRequestedWeight(Lifter lifter, final Locale locale, boolean done) {
// display requested weightLabel
if (!done) {
weightLabel.setValue(lifter.getNextAttemptRequestedWeight() + Messages.getString("Common.kg", locale)); //$NON-NLS-1$
} else {
weightLabel.setValue(""); //$NON-NLS-1$
}
//grid.addComponent(weightLabel, 3, 2, 3, 2); //$NON-NLS-1$
}
/**
* @param groupData
*/
private void updateTime(final SessionData groupData) {
// we set the value to the time remaining for the current lifter as
// computed by groupData
int timeRemaining = groupData.getDisplayTime();
final CountdownTimer timer = groupData.getTimer();
if (!paShown){
showTimeRemaining(timeRemaining);
}
timer.addListener(this);
}
@Override
public void finalWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void forceTimeRemaining(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
if (!paShown){
showTimeRemaining(timeRemaining);
}
}
private void showTimeRemaining(int timeRemaining) {
synchronized (app) {
timeDisplayLabel.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
}
app.push();
}
@Override
public void initialWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void noTimeLeft(int timeRemaining) {
normalTick(timeRemaining);
}
int previousTimeRemaining = 0;
private String viewName;
protected boolean shown;
private String stylesheetName;
private boolean paShown;
private boolean publicFacing;
@Override
public void normalTick(int timeRemaining) {
if (nameLabel == null) return;
if (TimeFormatter.getSeconds(previousTimeRemaining) == TimeFormatter.getSeconds(timeRemaining)) {
previousTimeRemaining = timeRemaining;
return;
} else {
previousTimeRemaining = timeRemaining;
}
showTimeRemaining(timeRemaining);
}
@Override
public void pause(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
showTimeRemaining(timeRemaining);
}
@Override
public void start(int timeRemaining) {
showTimeRemaining(timeRemaining);
}
@Override
public void stop(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
showTimeRemaining(timeRemaining);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+platformName+"/"+(publicFacing == true ? "public" : "lifter")+(stylesheetName != null ? "/"+stylesheetName : "");
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
if (params.length >= 2) {
platformName = params[1];
}
if (params.length >= 3) {
String publicFacingString = params[2];
publicFacing = "public".equals(publicFacingString);
logger.trace("setting publicFacing to {}",publicFacing);
}
if (params.length >= 4) {
stylesheetName = params[3];
logger.trace("setting stylesheetName to {}",stylesheetName);
}
}
/* Listen to public address notifications.
* We only deal with creating and destroying the overlay that hides the normal display.
* @see org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent.MessageDisplayListener#messageUpdate(org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent)
*/
@Override
public void messageUpdate(PublicAddressMessageEvent event) {
synchronized(app) {
if (event.setHide()) {
removeMessage();
} else {
hideAll();
displayMessage(event.getTitle(),event.getMessage(),event.getRemainingMilliseconds());
}
}
app.push();
}
@Override
public void timerUpdate(PublicAddressTimerEvent event) {
if (!paShown) {
return;
}
synchronized(app) {
Integer remainingMilliseconds = event.getRemainingMilliseconds();
if (remainingMilliseconds != null) {
timeDisplayLabel.setVisible(true);
timeDisplayLabel.setValue(TimeFormatter.formatAsSeconds(remainingMilliseconds));
}
}
app.push();
}
/**
* Remove the currently displayed public message, if any.
*/
private void removeMessage() {
paShown = false;
refresh();
}
/**
* Display a new public address message
* Hide the current display with a popup.
* @param title
* @param message
* @param remainingMilliseconds
*/
private void displayMessage(String title, String message, Integer remainingMilliseconds) {
// create content formatting
// logger.debug("displayMessage {}",remainingMilliseconds);
synchronized (app) {
paShown = true;
nameLabel.setValue(Messages.getString("AttemptBoard.Pause", CompetitionApplication.getCurrentLocale()));
timeDisplayLabel.setVisible(true);
timeDisplayLabel.setValue(TimeFormatter.formatAsSeconds(remainingMilliseconds));
}
app.push();
}
/* Unregister listeners when window is closed.
* @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window.CloseEvent)
*/
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
logger.debug("re-registering handlers for {} {}",this,relativeUri);
registerAsListener();
return null;
}
/**
* Process a decision regarding the current lifter.
* Make sure that the nameLabel of the lifter does not change until after the decision has been shown.
* @see org.concordiainternational.competition.decision.DecisionEventListener#updateEvent(org.concordiainternational.competition.decision.DecisionEvent)
*/
@Override
public void updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
switch (updateEvent.getType()) {
case DOWN:
waitingForDecisionLightsReset = true;
decisionLights.setVisible(false);
break;
case SHOW:
// if window is not up, show it.
waitingForDecisionLightsReset = true;
shown = true;
showDecisionLights(true);
decisionLights.setVisible(true);
break;
case RESET:
// we are done
waitingForDecisionLightsReset = false;
if (shown) {
decisionLights.setVisible(false);
showDecisionLights(false);
shown = false;
}
display(platformName, masterData);
break;
case WAITING:
waitingForDecisionLightsReset = true;
decisionLights.setVisible(false);
break;
case UPDATE:
// show change only if the lights are already on.
waitingForDecisionLightsReset = true;
if (shown) {
showDecisionLights(true);
decisionLights.setVisible(true);
}
break;
case BLOCK:
waitingForDecisionLightsReset = true;
if (shown) {
showDecisionLights(true);
decisionLights.setVisible(true);
}
break;
}
}
}
}).start();
}
@Override
public void registerAsListener() {
// listen to changes in the competition data
logger.debug("listening to session data updates.");
updateListener = registerAsListener(platformName, masterData);
// listen to public address events
logger.debug("listening to public address events.");
masterData.addBlackBoardListener(this);
// listen to decisions
IDecisionController decisionController = masterData.getRefereeDecisionController();
if (decisionController != null) {
decisionController.addListener(decisionLights);
decisionController.addListener(this);
}
// listen to close events
app.getMainWindow().addListener((CloseListener)this);
// listen to keyboard
addActions(app.getMainWindow());
}
/**
* Undo what registerAsListener did.
*/
@Override
public void unregisterAsListener() {
// stop listening to changes in the competition data
if (updateListener != null) {
masterData.removeListener(updateListener);
logger.debug("stopped listening to UpdateEvents");
}
// stop listening to public address events
removeMessage();
masterData.removeBlackBoardListener(this);
logger.debug("stopped listening to PublicAddress TimerEvents");
// stop listening to decisions
IDecisionController decisionController = masterData.getRefereeDecisionController();
if (decisionController != null) {
decisionController.removeListener(decisionLights);
decisionController.removeListener(this);
}
// stop listening to close events
app.getMainWindow().removeListener((CloseListener)this);
// stop listening to keyboard
removeActions(app.getMainWindow());
}
@SuppressWarnings("serial")
private abstract class ShortcutActionListener extends ShortcutAction implements Action.Listener {
public ShortcutActionListener(String caption, int kc, int[] m) {
super(caption, kc, m);
}
public ShortcutActionListener(String caption, int kc) {
super(caption, kc, null);
}
}
@SuppressWarnings("serial")
private void addActions(Action.Notifier actionNotifier) {
final IDecisionController refereeDecisionController = masterData.getRefereeDecisionController();
startAction = new ShortcutActionListener("start", ShortcutAction.KeyCode.G){
@Override
public void handleAction(Object sender, Object target) {
masterData.startUpdateModel();
}
};
stopAction = new ShortcutActionListener("stop",ShortcutAction.KeyCode.P){
@Override
public void handleAction(Object sender, Object target) {
masterData.stopUpdateModel();
}
};
oneMinuteAction = new ShortcutActionListener("1 minute",ShortcutAction.KeyCode.O){
@Override
public void handleAction(Object sender, Object target) {
masterData.oneMinuteUpdateModel();
}
};
twoMinutesAction = new ShortcutActionListener("2 minutes",ShortcutAction.KeyCode.T){
@Override
public void handleAction(Object sender, Object target) {
masterData.twoMinuteUpdateModel();
}
};
action1ok = new ShortcutActionListener("1+",ShortcutAction.KeyCode.NUM1) {
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(0, true);
}
};
action1fail = new ShortcutActionListener("1-",ShortcutAction.KeyCode.NUM2){
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(0, false);
}
};
action2ok = new ShortcutActionListener("2+",ShortcutAction.KeyCode.NUM3){
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(1, true);
}
};
action2fail = new ShortcutActionListener("2-",ShortcutAction.KeyCode.NUM4){
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(1, false);
}
};
action3ok = new ShortcutActionListener("3+",ShortcutAction.KeyCode.NUM5){
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(2, true);
}
};
action3fail = new ShortcutActionListener("3-",ShortcutAction.KeyCode.NUM6){
@Override
public void handleAction(Object sender, Object target) {
refereeDecisionController.decisionMade(2, false);
}
};
actionNotifier.addAction(startAction);
actionNotifier.addAction(stopAction);
actionNotifier.addAction(oneMinuteAction);
actionNotifier.addAction(twoMinutesAction);
actionNotifier.addAction(action1ok);
actionNotifier.addAction(action1fail);
actionNotifier.addAction(action2ok);
actionNotifier.addAction(action2fail);
actionNotifier.addAction(action3ok);
actionNotifier.addAction(action3fail);
}
private void removeActions(Action.Notifier actionNotifier) {
actionNotifier.removeAction(startAction);
actionNotifier.removeAction(stopAction);
actionNotifier.removeAction(oneMinuteAction);
actionNotifier.removeAction(twoMinutesAction);
actionNotifier.removeAction(action1ok);
actionNotifier.removeAction(action1fail);
actionNotifier.removeAction(action2ok);
actionNotifier.removeAction(action2fail);
actionNotifier.removeAction(action3ok);
actionNotifier.removeAction(action3fail);
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Buffered.SourceException;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ConversionException;
import com.vaadin.data.Property.ReadOnlyException;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.data.util.FilesystemContainer;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.service.ApplicationContext;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Field;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Select;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class CompetitionEditor extends VerticalLayout implements ApplicationView {
private static final long serialVersionUID = 5562100583893230718L;
protected boolean editable = false;
private CompetitionApplication app;
Logger logger = LoggerFactory.getLogger(CompetitionEditor.class);
private TextField displayFN;
private Select editFN;
private String viewName;
public CompetitionEditor(boolean initFromFragment, String viewName) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
app = CompetitionApplication.getCurrent();
final Locale locale = app.getLocale();
this.setReadOnly(true);
HbnContainer<Competition> cmp = new HbnContainer<Competition>(Competition.class, app);
if (cmp.size() == 0) {
cmp.saveEntity(new Competition());
}
final Object firstItemId = cmp.firstItemId();
HbnContainer<Competition>.EntityItem<Competition> competitionItem = cmp.getItem(firstItemId);
final FormLayout formLayout = new FormLayout();
this.addComponent(createTitleBar(locale, formLayout, cmp, competitionItem));
this.addComponent(createFormLayout(formLayout, locale, cmp, competitionItem));
this.setSpacing(true);
this.setMargin(true);
}
/**
* Display the competition information.
*
* REFACTOR: redo this using a form; this would enable us to use a
* FormFieldFactory and deal more elegantly with the dual nature of the file
* name field.
*
* @param formLayout
* @param locale
* @param cmp
* @param firstItemId
* @throws ReadOnlyException
* @throws ConversionException
* @throws SourceException
* @throws InvalidValueException
* @throws FileNotFoundException
*/
private FormLayout createFormLayout(final FormLayout formLayout, final Locale locale,
HbnContainer<Competition> cmp, final HbnContainer<Competition>.EntityItem<Competition> competitionItem)
{
addTextField(formLayout, locale, competitionItem, "competitionName", ""); //$NON-NLS-1$ //$NON-NLS-2$
addDateField(formLayout, locale, competitionItem, "competitionDate", new Date()); //$NON-NLS-1$
addTextField(formLayout, locale, competitionItem, "competitionSite", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "competitionCity", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "competitionOrganizer", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "invitedIfBornBefore", 0); //$NON-NLS-1$
addTextField(formLayout, locale, competitionItem, "masters", false); //$NON-NLS-1$
addTextField(formLayout, locale, competitionItem, "federation", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "federationAddress", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "federationWebSite", ""); //$NON-NLS-1$ //$NON-NLS-2$
addTextField(formLayout, locale, competitionItem, "federationEMail", ""); //$NON-NLS-1$ //$NON-NLS-2$
displayFN = addFileDisplay(formLayout, locale, competitionItem, "resultTemplateFileName", ""); //$NON-NLS-1$ //$NON-NLS-2$
editFN = addFileSelector(formLayout, locale, competitionItem, "resultTemplateFileName", ""); //$NON-NLS-1$ //$NON-NLS-2$)
editable = false;
setReadOnly(formLayout, true);
editFN.setVisible(false);
editFN.setImmediate(true);
displayFN.setWidth("120ex");
return formLayout;
}
/**
* @param formLayout
* @param locale
* @param competitionItem
* @param fieldName
* @param initialValue
* @return
* @throws FileNotFoundException
*/
private Select addFileSelector(FormLayout formLayout, Locale locale,
HbnContainer<Competition>.EntityItem<Competition> competitionItem, String fieldName, String initialValue) {
final ApplicationContext context = app.getContext();
WebApplicationContext wContext = (WebApplicationContext) context;
final Property itemProperty = competitionItem.getItemProperty(fieldName);;
FilesystemContainer fsContainer;
String relativeLocation = "/WEB-INF/classes/templates/teamResults";
relativeLocation = "/WEB-INF/classes/templates/competitionBook";
String realPath = wContext.getHttpSession().getServletContext().getRealPath(relativeLocation);
File file = new File(realPath);
if (realPath != null && file.isDirectory()) {
fsContainer = new FilesystemContainer(file, "xls", false);
} else {
fsContainer = findTemplatesWhenRunningInPlace(wContext);
}
Select fileSelector = new Select(Messages.getString("Competition." + fieldName, locale), fsContainer);
fileSelector.setItemCaptionPropertyId("Name");
fileSelector.addListener(new Property.ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) {
Property property = event.getProperty();
itemProperty.setValue(property);
}
});
fileSelector.setImmediate(true);
formLayout.addComponent(fileSelector);
return fileSelector;
}
/**
* kludge when running in-place under jetty (development mode) with Maven
* @param wContext
* @param fsContainer
* @return
*/
private FilesystemContainer findTemplatesWhenRunningInPlace(WebApplicationContext wContext) {
String realPath;
FilesystemContainer fsContainer;
String relativeLocationKludge = "/classes";
realPath = wContext.getHttpSession().getServletContext().getRealPath(relativeLocationKludge);
try {
logger.debug("findTemplatesWhenRunningInPlace 1 {}",realPath);
// really ugly, no benefit whatsoever in cleaning this up.
File file1 = new File(realPath).getParentFile().getParentFile();
logger.debug("findTemplatesWhenRunningInPlace 2 {}",file1.getAbsolutePath());
if (realPath != null && file1.isDirectory()) {
file1 = new File(file1,"resources/templates/teamResults");
logger.debug("findTemplatesWhenRunningInPlace 3 {}",file1.getAbsolutePath());
fsContainer = new FilesystemContainer(file1, "xls", false);
} else {
throw new RuntimeException("templates not found in WEB-INF or application root");
}
} catch (Throwable t) {
throw new RuntimeException("templates not found in WEB-INF or application root");
}
return fsContainer;
}
/**
* @param formLayout
* @param locale
* @param competitionItem
* @param fieldName
* @return
* @throws ReadOnlyException
* @throws ConversionException
*/
private TextField addTextField(final Layout formLayout, final Locale locale,
final HbnContainer<Competition>.EntityItem<Competition> competitionItem, final String fieldName,
final Object initialValue) throws ReadOnlyException, ConversionException {
final Property itemProperty = competitionItem.getItemProperty(fieldName);
TextField field = new TextField(Messages.getString("Competition." + fieldName, locale), itemProperty); //$NON-NLS-1$
field.setWidth("60ex"); //$NON-NLS-1$
formLayout.addComponent(field);
if (itemProperty.getValue() == null) itemProperty.setValue(initialValue); //$NON-NLS-1$
return field;
}
/**
* @param formLayout
* @param locale
* @param competitionItem
* @param fieldName
* @return
* @throws ReadOnlyException
* @throws ConversionException
*/
private TextField addFileDisplay(final Layout formLayout, final Locale locale,
final HbnContainer<Competition>.EntityItem<Competition> competitionItem, final String fieldName,
final String initialValue) throws ReadOnlyException, ConversionException {
final Property itemProperty = competitionItem.getItemProperty(fieldName);
Object stringValue = itemProperty.getValue();
if (stringValue == null) stringValue = initialValue; //$NON-NLS-1$
File value = (File) new File((String) stringValue);
TextField field = new TextField(Messages.getString("Competition." + fieldName, locale), new ObjectProperty<String>(value.getName(),String.class)); //$NON-NLS-1$
field.setWidth("60ex"); //$NON-NLS-1$
formLayout.addComponent(field);
return field;
}
/**
* @param formLayout
* @param locale
* @param competitionItem
* @param fieldName
* @return
* @throws ReadOnlyException
* @throws ConversionException
*/
private DateField addDateField(final Layout formLayout, final Locale locale,
final HbnContainer<Competition>.EntityItem<Competition> competitionItem, final String fieldName,
final Object initialValue) throws ReadOnlyException, ConversionException {
final Property itemProperty = competitionItem.getItemProperty(fieldName);
DateField field = new DateField(Messages.getString("Competition." + fieldName, locale), itemProperty); //$NON-NLS-1$
formLayout.addComponent(field);
if (itemProperty.getValue() == null) itemProperty.setValue(initialValue);
field.setResolution(DateField.RESOLUTION_DAY);
field.setDateFormat("yyyy-MM-dd");
return field;
}
/**
* @param locale
* @param formLayout
* @param cmp
*/
private HorizontalLayout createTitleBar(final Locale locale, final FormLayout formLayout,
final HbnContainer<Competition> cmp, final HbnContainer<Competition>.EntityItem<Competition> competitionItem) {
final HorizontalLayout hl = new HorizontalLayout();
final Label cap = new Label(Messages.getString("CompetitionApplication.Competition", locale)); //$NON-NLS-1$
cap.setWidth("20ex"); //$NON-NLS-1$
cap.setHeight("1.2em"); //$NON-NLS-1$
hl.setStyleName("title"); //$NON-NLS-1$
hl.addComponent(cap);
hl.setComponentAlignment(cap, Alignment.MIDDLE_LEFT);
final Button editButton = new Button(Messages.getString("Common.edit", locale)); //$NON-NLS-1$
hl.addComponent(editButton);
editButton.addListener(new ClickListener() {
private static final long serialVersionUID = 7441128401829794738L;
@Override
public void buttonClick(ClickEvent event) {
if (editable) {
// layout currently says "OK"
event.getButton().setCaption(Messages.getString("Common.edit", locale)); //$NON-NLS-1$
CompetitionEditor.this.setReadOnly(formLayout, true);
saveItem(competitionItem);
editFN.setVisible(false);
displayFN.setVisible(true);
editable = false;
} else {
// not editable, button currently says "Edit"
event.getButton().setCaption(Messages.getString("Common.OK", locale)); //$NON-NLS-1$
CompetitionEditor.this.setReadOnly(formLayout, false);
editFN.setVisible(true);
displayFN.setVisible(false);
editable = true;
}
}
private void saveItem(HbnContainer<Competition>.EntityItem<Competition> cmItem) {
Competition competition = (Competition) cmItem.getPojo();
final Session session = app.getHbnSession();
session.merge(competition);
session.flush();
};
});
return hl;
}
/**
* @throws SourceException
* @throws InvalidValueException
*/
public void setReadOnly(ComponentContainer cont, boolean b) throws SourceException, InvalidValueException {
for (Iterator<Component> iterator2 = (Iterator<Component>) cont.getComponentIterator(); iterator2.hasNext();) {
Component f = (Component) iterator2.next();
if (f instanceof Field && !(f instanceof Button)) {
f.setReadOnly(b);
((Field) f).setWriteThrough(!b);
}
}
}
@Override
public void refresh() {
// nothing to do.
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return true;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
}
@Override
public void registerAsListener() {
CompetitionApplication.getCurrent().getMainWindow().addListener((CloseListener) this);
}
@Override
public void unregisterAsListener() {
CompetitionApplication.getCurrent().getMainWindow().addListener((CloseListener) this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
public interface RefereeConsole {
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import com.vaadin.data.Item;
import com.vaadin.ui.Component;
public interface EditingView extends Component, Bookmarkable {
/**
* @return true if editor in bottom pane is pinned (not to be updated)
*/
public boolean isStickyEditor();
/**
* Indicate that the editor at bottom must not be updated
*
* @param freezeLifterCardEditor
*/
public void setStickyEditor(boolean freezeLifterCardEditor);
/**
* Indicate that the editor at bottom must not be updated
*
* @param freezeLifterCardEditor
*/
public void setStickyEditor(boolean freezeLifterCardEditor, boolean reloadLifterInfo);
/**
* Load the designated lifter in the bottom pane
*
* @param lifter
* @param lifterItem
*/
public void editLifter(Lifter lifter, Item lifterItem);
/**
* Switch to editing a new group.
*
* @param newSession
*/
public void setCurrentSession(CompetitionSession newSession);
public void setSessionData(SessionData newSessionData);
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.SocketException;
import java.net.URL;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.LocalizedSystemMessages;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.mobile.MJuryConsole;
import org.concordiainternational.competition.mobile.MRefereeConsole;
import org.concordiainternational.competition.mobile.MobileMenu;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.Menu;
import org.concordiainternational.competition.ui.components.ResultFrame;
import org.concordiainternational.competition.utils.Localized;
import org.concordiainternational.competition.webapp.WebApplicationConfiguration;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.vaadin.artur.icepush.ICEPush;
import com.vaadin.Application;
import com.vaadin.data.Buffered;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
import com.vaadin.event.ListenerMethod;
import com.vaadin.service.ApplicationContext;
import com.vaadin.service.ApplicationContext.TransactionListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.ErrorMessage;
import com.vaadin.terminal.ParameterHandler;
import com.vaadin.terminal.StreamResource;
import com.vaadin.terminal.StreamResource.StreamSource;
import com.vaadin.terminal.SystemError;
import com.vaadin.terminal.Terminal;
import com.vaadin.terminal.URIHandler;
import com.vaadin.terminal.UserError;
import com.vaadin.terminal.VariableOwner;
import com.vaadin.terminal.gwt.server.ChangeVariablesErrorEvent;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.AbstractComponentContainer;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UriFragmentUtility;
import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent;
import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;
public class CompetitionApplication extends Application implements HbnSessionManager, UserActions, Serializable {
private static final long serialVersionUID = -1774806616519381075L;
/**
* if true, use the language set in the browser
*/
final private static boolean USE_BROWSER_LANGUAGE = true;
private static Logger logger = LoggerFactory.getLogger(CompetitionApplication.class);
public static XLogger traceLogger = XLoggerFactory.getXLogger("Tracing"); //$NON-NLS-1$
private static LocalizedSystemMessages localizedMessages;
private static InheritableThreadLocal<CompetitionApplication> current = new InheritableThreadLocal<CompetitionApplication>();
public CompetitionApplication() {
super();
current.set(this);
logger.debug("new application {} {}",this, this.getLocale());
}
public CompetitionApplication(String suffix) {
super();
current.set(this);
setAppSuffix(suffix);
logger.debug("new application {} {}",this);
}
/**
* @return the current application.
*/
public static CompetitionApplication getCurrent() {
return current.get();
}
/**
* @return the current application.
*/
public static Locale getCurrentLocale() {
final CompetitionApplication current2 = getCurrent();
if (current2 == null) {
//logger.warn("*current locale={}",getDefaultLocale());
return getDefaultLocale();
}
//logger.warn("current locale={}",current2.getLocale());
return current2.getLocale();
}
/**
* @return the current application.
*/
public static Locale getCurrentSupportedLocale() {
final CompetitionApplication current2 = getCurrent();
if (current2 == null) {
return getDefaultLocale();
}
final Locale currentLocale = current2.getLocale();
// compare the current language with code retrieved from bundle. If the
// code is different, then the language is not directly translated.
final String languageCode = Messages.getString("Locale.languageCode", currentLocale); //$NON-NLS-1$
logger.info("Locale.languageCode({})={}",currentLocale,languageCode);
if (currentLocale.getLanguage().equals(languageCode)) {
return currentLocale;
} else {
return getDefaultLocale();
}
}
/**
* return the default locale to whoever needs it.
*/
public static Locale getDefaultLocale() {
final String defaultLanguage = Messages.getString("Locale.defaultLanguage", Locale.getDefault()); //$NON-NLS-1$
final String defaultCountry = Messages.getString("Locale.defaultCountry", Locale.getDefault()); //$NON-NLS-1$
Locale locale = Locale.getDefault();
if (defaultCountry == null) {
locale = new Locale(defaultLanguage);
} else {
locale = new Locale(defaultLanguage, defaultCountry);
}
return locale;
}
/**
* @param throwable
*
* @return
*/
public static Throwable getRootCause(Throwable throwable, Locale locale) {
Throwable cause = throwable.getCause();
while (cause != null) {
throwable = cause;
cause = throwable.getCause();
}
if (throwable instanceof Localized) {
((Localized) throwable).setLocale(locale);
}
return throwable;
}
/**
* Gets the SystemMessages for this application. SystemMessages are used to
* notify the user of various critical situations that can occur, such as
* session expiration, client/server out of sync, and internal server error.
*
* Note: this method is static; we need to call
* {@link LocalizedSystemMessages#setThreadLocale(Locale)} to change the
* language that will be used for this thread.
*
* @return the LocalizedSystemMessages for this application
*/
public static SystemMessages getSystemMessages() {
if (localizedMessages == null) localizedMessages = new LocalizedSystemMessages() {
private static final long serialVersionUID = -8705748397362824437L;
@Override
protected Locale getDefaultSystemMessageLocale() {
return getDefaultLocale();
}
};
return localizedMessages;
}
/**
* Set current application (used for junit tests).
*
* @param current
*/
public static void setCurrent(CompetitionApplication current) {
CompetitionApplication.current.set(current);
}
transient private CompetitionSession currentGroup;
transient public CompetitionApplicationComponents components;
protected UriFragmentUtility uriFragmentUtility = new UriFragmentUtility();
/*
* Display views
*/
// private SoundPlayer buzzer = new SoundPlayer();
protected ICEPush pusher = null;
protected TransactionListener httpRequestListener;
protected boolean pusherDisabled = false;
private String appSuffix = "/app/";
private Panel mobilePanel;
private boolean layoutCreated;
private MobileMenu mobileMenu;
protected String contextURI;
private VerticalLayout mainLayout;
private ApplicationView mainLayoutContent;
public void displayRefereeConsole(int refereeIndex) {
final ORefereeConsole view = (ORefereeConsole) components
.getViewByName(CompetitionApplicationComponents.OREFEREE_CONSOLE, false);
view.setIndex(refereeIndex);
setMainLayoutContent(view);
uriFragmentUtility.setFragment(view.getFragment(), false);
}
public void displayOJuryConsole(int refereeIndex) {
final ORefereeConsole view = (ORefereeConsole) components
.getViewByName(CompetitionApplicationComponents.OJURY_CONSOLE, false);
view.setIndex(refereeIndex);
setMainLayoutContent(view);
uriFragmentUtility.setFragment(view.getFragment(), false);
}
public void displayMRefereeConsole(int refereeIndex) {
final MRefereeConsole view = (MRefereeConsole) components
.getViewByName(CompetitionApplicationComponents.MREFEREE_CONSOLE, false);
view.setIndex(refereeIndex);
setMainLayoutContent(view);
uriFragmentUtility.setFragment(view.getFragment(), false);
}
public void displayMJuryConsole(int refereeIndex) {
final MJuryConsole view = (MJuryConsole) components
.getViewByName(CompetitionApplicationComponents.MJURY_CONSOLE, false);
view.setIndex(refereeIndex);
setMainLayoutContent(view);
uriFragmentUtility.setFragment(view.getFragment(), false);
}
/**
* @param viewName
*/
public void doDisplay(String viewName) {
// logger.debug("doDisplay {}",viewName);
ApplicationView view = components.getViewByName(viewName, false);
// remove all listeners on current view.
getMainLayoutContent().unregisterAsListener();
setMainLayoutContent(view);
uriFragmentUtility.setFragment(view.getFragment(), false);
}
/**
* @param viewName
*/
public void displayProjector(String viewName, String stylesheet) {
// logger.debug("doDisplay {}",viewName);
ResultFrame view = (ResultFrame) components.getViewByName(viewName, false);
setMainLayoutContent(view);
view.setStylesheet(stylesheet);
view.refresh();
uriFragmentUtility.setFragment(view.getFragment(), false);
}
/**
* @return
*/
synchronized protected ICEPush ensurePusher() {
if (pusher == null) {
pusher = new ICEPush();
getMainWindow().addComponent(pusher);
}
return pusher;
}
synchronized public void push() {
pusher = this.ensurePusher();
if (!pusherDisabled) {
logger.debug("pushing with {} on window {}",pusher,getMainWindow());
pusher.push();
}
}
public void setPusherDisabled(boolean disabled) {
pusherDisabled = disabled;
}
public boolean getPusherDisabled() {
return pusherDisabled;
}
// /**
// * @return the buzzer
// */
// public SoundPlayer getBuzzer() {
// return buzzer;
// }
public CompetitionSession getCurrentCompetitionSession() {
if (currentGroup != null) {
final String name = currentGroup.getName();
MDC.put("currentGroup", name);
} else {
MDC.put("currentGroup", "-");
}
return currentGroup;
}
/**
* Used to get current Hibernate session. Also ensures an open Hibernate
* transaction.
*/
@Override
public Session getHbnSession() {
Session currentSession = getCurrentSession();
if (!currentSession.getTransaction().isActive()) {
currentSession.beginTransaction();
}
return currentSession;
}
/**
* @param platformName
* @return
*/
public SessionData getMasterData() {
String platformName = getPlatformName();
if (platformName == null) {
platformName = CompetitionApplicationComponents.initPlatformName();
}
return getMasterData(platformName);
}
/**
* @param platformName
* @return
*/
public SessionData getMasterData(String platformName) {
SessionData masterData = SessionData.getSingletonForPlatform(platformName);
if (masterData != null) {
masterData.getCurrentSession();
return masterData;
} else {
logger.error("Master data for platformName " + platformName + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
public Platform getPlatform() {
return components.getPlatform();
}
public String getPlatformName() {
return components.getPlatformName();
}
/**
* Try to load a resource, accounting for the wide variations between run-time environments.
* Accounts for Tomcat, Eclipse, Jetty.
* @param path
* @return
* @throws IOException
*/
public InputStream getResourceAsStream(String path) throws IOException {
InputStream resourceAsStream;
// logger.debug("classpath: {}",System.getProperty("java.class.path"));
// first, search using class loader
resourceAsStream = this.getClass().getResourceAsStream(path); //$NON-NLS-1$
if (resourceAsStream == null) {
resourceAsStream = this.getClass().getResourceAsStream("/templates" + path); //$NON-NLS-1$
}
// if not found, try using the servlet context
final ServletContext servletContext = getServletContext();
if (resourceAsStream == null && servletContext != null) {
resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/templates" + path); //$NON-NLS-1$
}
if (resourceAsStream == null && servletContext != null) {
resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes" + path); //$NON-NLS-1$
}
if (resourceAsStream == null)
throw new IOException(
Messages.getString("CompetitionApplication.ResourceNotFoundOnClassPath", getLocale()) + path); //$NON-NLS-1$
return resourceAsStream;
}
/**
* Return the servlet container context to allow various HttpSessions to
* communicate with one another (e.g. sharing data structures such as the
* lifting order).
*/
public ServletContext getServletContext() {
ApplicationContext ctx = getContext();
if (ctx == null) return null;
final ServletContext sCtx = ((WebApplicationContext) ctx).getHttpSession().getServletContext();
return sCtx;
}
/**
* @return the uriFragmentUtility
*/
public UriFragmentUtility getUriFragmentUtility() {
return uriFragmentUtility;
}
@Override
public void init() {
sharedInit();
// create the initial look.
buildMainLayout();
}
/**
*
*/
public void sharedInit() {
// ignore the preference received from the browser.
if (!USE_BROWSER_LANGUAGE) this.setLocale(getDefaultLocale());
if (components == null) {
components = new CompetitionApplicationComponents(new Panel(), null, null);
}
// set system message language if any are shown while "init" is running.
LocalizedSystemMessages msg = (LocalizedSystemMessages) getSystemMessages();
msg.setThreadLocale(this.getLocale());
// the following defines what will happen before and after each http
// request.
if (httpRequestListener == null) {
httpRequestListener = attachHttpRequestListener();
}
}
/**
* @param streamSource
* @param filename
*/
@Override
public void openSpreadsheet(StreamResource.StreamSource streamSource, final String filename) {
StreamResource streamResource = new StreamResource(streamSource, filename + ".xls", this); //$NON-NLS-1$
streamResource.setCacheTime(5000); // no cache (<=0) does not work with IE8
streamResource.setMIMEType("application/x-msexcel"); //$NON-NLS-1$
// WebApplicationContext webAppContext = (WebApplicationContext)this.getContext();
// if (webAppContext.getBrowser().isChrome()) {
// this.getMainWindow().open(streamResource, "_blank"); //$NON-NLS-1$
// } else {
this.getMainWindow().open(streamResource, "_top"); //$NON-NLS-1$
// }
}
public void openPdf(StreamSource streamSource, final String filename) {
StreamResource streamResource = new StreamResource(streamSource, filename + ".pdf", this); //$NON-NLS-1$
streamResource.setCacheTime(5000); // no cache (<=0) does not work with IE8
streamResource.setMIMEType("application/pdf"); //$NON-NLS-1$
this.getMainWindow().open(streamResource, "_blank"); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.concordiainternational.competition.UserActions#setCurrentGroup(org
* .concordiainternational.competition.data.Group)
*/
@Override
public void setCurrentCompetitionSession(CompetitionSession newSession) {
if (newSession != null) {
final String name = newSession.getName();
MDC.put("currentGroup", "*"+name);
}
final CompetitionSession oldSession = currentGroup;
currentGroup = newSession;
final ApplicationView currentView = components.currentView;
if (currentView != null) {
if (currentView instanceof EditingView && oldSession != newSession) {
((EditingView) currentView).setCurrentSession(newSession);
} else {
currentView.refresh();
}
setMainLayoutContent(currentView);
}
}
/*
* (non-Javadoc)
*
* @see
* org.concordiainternational.competition.UserActions#setPlatform(java.lang
* .String)
*/
@Override
public void setPlatformByName(String platformName) {
components.setPlatformByName(platformName);
}
/**
* <p>
* Invoked by the terminal on any exception that occurs in application and
* is thrown by the <code>setVariable</code> to the terminal. The default
* implementation sets the exceptions as <code>ComponentErrors</code> to the
* component that initiated the exception and prints stack trace to standard
* error stream.
* </p>
* <p>
* You can safely override this method in your application in order to
* direct the errors to some other destination (for example log).
* </p>
*
* @param event
* the change event.
* @see com.vaadin.terminal.Terminal.ErrorListener#terminalError(com.vaadin.terminal.Terminal.ErrorEvent)
*/
@Override
public void terminalError(Terminal.ErrorEvent event) {
Throwable t = event.getThrowable();
if (t instanceof SocketException) {
// Most likely client browser closed socket
logger.debug(Messages.getString("CompetitionApplication.SocketException", getLocale()) //$NON-NLS-1$
+ Messages.getString("CompetitionApplication.BrowserClosedSession", getLocale())); //$NON-NLS-1$
return;
}
// Finds the original source of the error/exception
Object owner = null;
if (event instanceof VariableOwner.ErrorEvent) {
owner = ((VariableOwner.ErrorEvent) event).getVariableOwner();
} else if (event instanceof URIHandler.ErrorEvent) {
owner = ((URIHandler.ErrorEvent) event).getURIHandler();
} else if (event instanceof ParameterHandler.ErrorEvent) {
owner = ((ParameterHandler.ErrorEvent) event).getParameterHandler();
} else if (event instanceof ChangeVariablesErrorEvent) {
owner = ((ChangeVariablesErrorEvent) event).getComponent();
}
Throwable rootCause = CompetitionApplication.getRootCause(t, getLocale());
logger.debug("rootCause: {} locale={}", rootCause, getLocale()); //$NON-NLS-1$
String message = rootCause.getMessage();
if (message == null) message = t.toString();
logger.debug("t.class: {} locale={}", t.getClass().getName(), getLocale()); //$NON-NLS-1$
if ((t instanceof Buffered.SourceException || t instanceof ListenerMethod.MethodException || t instanceof RuleViolationException)) {
// application-level exception, some of which are not worth logging
// rule violations exceptions are one example.
if (!(rootCause instanceof RuleViolationException)) {
// log error cleanly with its stack trace.
StringWriter sw = new StringWriter();
rootCause.printStackTrace(new PrintWriter(sw));
logger.error("root cause \n" + sw.toString()); //$NON-NLS-1$
}
} else {
if (t instanceof SystemError) {
if (getMainWindow() != null) {
getMainWindow().showNotification(Messages.getString("RuleValidation.error", getLocale()), //$NON-NLS-1$
message, Notification.TYPE_ERROR_MESSAGE);
}
}
// super.terminalError(event);
// log error cleanly with its stack trace.
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
logger.error("exception: \n" + sw.toString()); //$NON-NLS-1$
// return;
}
// Shows the error in AbstractComponent
logger.debug("owner = {}", (owner == null ? "null!" : owner.getClass().toString()
+ System.identityHashCode(owner)));
if ((owner != null && owner instanceof AbstractComponent && !(owner instanceof AbstractComponentContainer))) {
logger.debug("case1A: showing component error for {}", message);
if (rootCause instanceof ErrorMessage) {
((AbstractComponent) owner).setComponentError((ErrorMessage) rootCause);
} else {
((AbstractComponent) owner).setComponentError(new UserError(message));
}
logger.debug("case1B: notification for {}", message);
// also as notification
if (getMainWindow() != null) {
getMainWindow().showNotification(Messages.getString("RuleValidation.error", getLocale()), //$NON-NLS-1$
message, Notification.TYPE_ERROR_MESSAGE);
}
} else {
logger.debug("case2: showing notification for {}", message);
if (getMainWindow() != null) {
getMainWindow().showNotification(Messages.getString("RuleValidation.error", getLocale()), //$NON-NLS-1$
message, Notification.TYPE_ERROR_MESSAGE);
}
}
}
/**
* Vaadin "transaction" equals "http request". This method fires for all
* servlets in the session.
*/
protected TransactionListener attachHttpRequestListener() {
TransactionListener listener = new TransactionListener() {
private static final long serialVersionUID = -2365336986843262181L;
@Override
public void transactionEnd(Application application, Object transactionData) {
// Transaction listener gets fired for all (Http) sessions
// of Vaadin applications, checking to be this one.
if (application == CompetitionApplication.this) {
closeHibernateSession();
}
current.remove();
}
@Override
public void transactionStart(Application application, Object transactionData) {
((LocalizedSystemMessages) getSystemMessages()).setThreadLocale(getLocale());
current.set(CompetitionApplication.this); // make the application available via ThreadLocal
HttpServletRequest request = (HttpServletRequest) transactionData;
final String requestURI = request.getRequestURI();
checkURI(requestURI);
if (requestURI.contains("juryDisplay")) {
request.getSession(true).setMaxInactiveInterval(-1);
} else {
request.getSession(true).setMaxInactiveInterval(3600);
}
getCurrentCompetitionSession(); // sets up the MDC
}
};
getContext().addTransactionListener(listener);
return listener;
}
/**
* Create the main layout.
*/
@SuppressWarnings("serial")
private void buildMainLayout() {
components.mainWindow = new Window(Messages.getString("CompetitionApplication.Title", getLocale())); //$NON-NLS-1$
setMainWindow(components.mainWindow);
mainLayout = new VerticalLayout();
// back and bookmark processing -- look at the presence of a fragment in
// the URL
mainLayout.addComponent(uriFragmentUtility);
uriFragmentUtility.addListener(new FragmentChangedListener() {
private static final long serialVersionUID = 1L;
@Override
public void fragmentChanged(FragmentChangedEvent source) {
logger.trace("fragmentChanged {}",source.getUriFragmentUtility().getFragment());
String frag = source.getUriFragmentUtility().getFragment();
displayView(frag);
}
});
components.mainWindow.addURIHandler(new URIHandler() {
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
final String externalForm = context.toExternalForm();
contextURI = externalForm;
// logger.debug("handleURI uris: {} {}",externalForm,contextURI);
if (layoutCreated) {
// logger.debug("layout exists, skipping");
return null; // already created layout
} else {
// logger.debug("creating layout");
}
if (contextURI.endsWith("/app/")){
// LoggerUtils.logException(logger, new Exception("creating app layout !"+externalForm+" "+contextURI));
// logger.debug("creating app layout");
createAppLayout(mainLayout);
if (relativeUri.isEmpty()) {
setMainLayoutContent(components.getViewByName("competitionEditor", false));
}
} else if (contextURI.endsWith("/m/")) {
// LoggerUtils.logException(logger, new Exception("creating mobile layout !"+externalForm+" "+contextURI));
createMobileLayout(mainLayout);
if (relativeUri.isEmpty()) {
setMainLayoutContent(components.getViewByName("", false));
}
} else {
throw new RuntimeException(Messages.getString("CompetitionApplication.invalidURL", getLocale()));
}
layoutCreated = true;
return null;
}});
}
/**
* @param mainLayout1
*/
private void createAppLayout(VerticalLayout mainLayout1) {
mobilePanel = null;
setTheme("competition"); //$NON-NLS-1$
// // include a sound player
// mainLayout1.addComponent(buzzer);
mainLayout1.setSizeFull();
//mainLayout1.setStyleName("blue"); //$NON-NLS-1$
components.menu = new Menu();
mainLayout1.addComponent(components.menu);
components.menu.setVisible(false);
mainLayout1.addComponent(components.mainPanel);
mainLayout1.setExpandRatio(components.mainPanel, 1);
components.mainPanel.setSizeFull();
getMainWindow().setContent(mainLayout1);
}
/**
* @param mainLayout1
*/
protected void createMobileLayout(VerticalLayout mainLayout1) {
components.mainPanel = null;
setTheme("m");
mainLayout1.setMargin(false,false,false,false);
mainLayout1.setSizeFull();
setMobileMenu(new MobileMenu());
getMobileMenu().setSizeFull();
mainLayout1.addComponent(getMobileMenu());
mobilePanel = new Panel();
mainLayout1.addComponent(mobilePanel);
mobilePanel.setSizeFull();
mobilePanel.setVisible(false);
getMainWindow().setContent(mainLayout1);
}
public void setMainLayoutContent(ApplicationView c) {
mainLayoutContent = c;
boolean needsMenu = c.needsMenu();
//logger.debug(">>>>> setting app view for {} -- view {}",this,c);
if (this.mobilePanel == null) {
this.components.currentView = c;
final Menu menu = this.components.menu;
if (menu != null) menu.setVisible(needsMenu);
this.components.mainPanel.setContent(c);
} else {
getMobileMenu().setVisible(needsMenu);
getMobileMenu().setSizeUndefined();
mobilePanel.setVisible(true);
mobilePanel.setContent(c);
mainLayout.setExpandRatio(getMobileMenu(),0);
mainLayout.setExpandRatio(mobilePanel,100);
}
}
public ApplicationView getMainLayoutContent() {
return mainLayoutContent;
}
/**
* @param uri
*
*/
private void checkURI(String uri) {
if (uri.endsWith("/app") || uri.endsWith("/m")) {
logger.error("missing trailing / after app : {}", uri);
getMainWindow().showNotification(
Messages.getString("CompetitionApplication.invalidURL", getLocale()) + "<br>", //$NON-NLS-1$
Messages.getString("CompetitionApplication.invalidURLExplanation", getLocale()),
Notification.TYPE_ERROR_MESSAGE);
}
}
private void closeHibernateSession() {
Session sess = getCurrentSession();
if (sess.getTransaction().isActive()) {
sess.getTransaction().commit();
if (sess.isOpen()) sess.flush();
}
if (sess.isOpen()) {
sess.close();
}
}
/**
* Get a Hibernate session so objects can be stored. If running as a junit
* test, we call the session factory with parameters that tell it not to
* persist the database.
*
* @return a Hibernate session
* @throws HibernateException
*/
private Session getCurrentSession() throws HibernateException {
return WebApplicationConfiguration.getSessionFactory().getCurrentSession();
}
protected void displayView(String frag) {
logger.debug("request to display view {}", frag); //$NON-NLS-1$
ApplicationView view = components.getViewByName(frag, true); // initialize from URI fragment
setMainLayoutContent(view);
}
public String getAppSuffix() {
return appSuffix;
}
public void setAppSuffix(String appSuffix) {
this.appSuffix = appSuffix;
}
public void setPusher(ICEPush pusher) {
this.pusher = pusher;
}
public ICEPush getPusher() {
return pusher;
}
public void setMobileMenu(MobileMenu mobileMenu) {
this.mobileMenu = mobileMenu;
}
public MobileMenu getMobileMenu() {
return mobileMenu;
}
}
| Java |
package org.concordiainternational.competition.ui;
public interface Bookmarkable {
/**
* @return
*/
public abstract String getFragment();
} | Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import org.concordiainternational.competition.data.Lifter;
import com.vaadin.data.Item;
public interface EditableList {
public Lifter getFirstLifter();
public Item getFirstLifterItem();
public SessionData getGroupData();
public void setGroupData(SessionData data);
public void clearSelection();
public void deleteItem(Object targetId);
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.WinningOrderComparator;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.publicAddress.PublicAddressForm;
import org.concordiainternational.competition.spreadsheet.JXLSCompetitionBook;
import org.concordiainternational.competition.spreadsheet.JXLSResultSheet;
import org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource;
import org.concordiainternational.competition.spreadsheet.MastersGroupResults;
import org.concordiainternational.competition.spreadsheet.OutputSheetStreamSource;
import org.concordiainternational.competition.ui.components.SessionSelect;
import org.concordiainternational.competition.ui.generators.CommonColumnGenerator;
import org.concordiainternational.competition.ui.generators.LiftCellStyleGenerator;
import org.concordiainternational.competition.ui.list.GenericBeanList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.Application;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.terminal.SystemError;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
/**
* This class displays the winning order for lifters.
*
* @author jflamy
*
*/
public class ResultList extends GenericBeanList<Lifter> implements Property.ValueChangeListener,
EditableList {
private static final Logger logger = LoggerFactory.getLogger(ResultList.class);
private static final long serialVersionUID = -6455130090728823622L;
private Application app = CompetitionApplication.getCurrent();
private EditingView parentView;
transient private SessionData data = null; // do not serialize
private SessionSelect sessionSelect;
private static String[] NATURAL_COL_ORDER = null;
private static String[] COL_HEADERS = null;
public ResultList(SessionData groupData, EditingView parentView) {
super(CompetitionApplication.getCurrent(), Lifter.class, Messages.getString(
"ResultList.title", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
this.parentView = parentView;
this.data = groupData;
init();
}
/**
* Clear the current selection from the table. This is done by the lift card
* editor once it has loaded the right lifter.
*/
@Override
public void clearSelection() {
table.select(null); // hide selection from table.
}
@Override
@SuppressWarnings("unchecked")
public Lifter getFirstLifter() {
BeanItem<Lifter> item = (BeanItem<Lifter>) table.getItem(table.firstItemId());
if (item != null) return (Lifter) item.getBean();
return null;
}
@Override
public Item getFirstLifterItem() {
return table.getItem(table.firstItemId());
}
@Override
public SessionData getGroupData() {
return data;
}
@Override
public void refresh() {
logger.debug("start refresh ResultList**************{}"); //$NON-NLS-1$`
sessionSelect.refresh();
Table oldTable = table;
// listeners to oldTable should listen no more (these listeners are
// those
// that need to know about users selecting a row).
oldTable.removeListener(Class.class, oldTable);
// populate the new table and connect it to us.
populateAndConfigureTable();
this.replaceComponent(oldTable, table);
positionTable();
setButtonVisibility();
logger.debug("end refresh ResultList **************{}"); //$NON-NLS-1$
}
@Override
public void setGroupData(SessionData data) {
this.data = data;
}
/*
* Value change, for a table, indicates that the currently selected row has
* changed. This method is only called when the user explicitly clicks on a
* lifter.
*
* @see
* com.vaadin.data.Property.ValueChangeListener#valueChange(com.vaadin.data
* .Property.ValueChangeEvent)
*/
@SuppressWarnings("unchecked")
@Override
public void valueChange(ValueChangeEvent event) {
Property property = event.getProperty();
if (property == table) {
Item item = table.getItem(table.getValue());
if (item == null) return;
if (parentView != null) {
Lifter lifter = (Lifter) ((BeanItem<Lifter>) item).getBean();
// on explicit selection by user, ignore the "sticky" and
// override, but don't reload the lifter info
parentView.setStickyEditor(false, false);
parentView.editLifter(lifter, item); // only bottom part
// changes.
}
}
}
@Override
protected void addGeneratedColumns() {
super.addGeneratedColumns();
// the following columns will be read-only.
final CommonColumnGenerator columnGenerator = new CommonColumnGenerator(app);
table.addGeneratedColumn("totalRank", columnGenerator); //$NON-NLS-1$
table.setColumnAlignment("totalRank",Table.ALIGN_RIGHT);
table.setColumnAlignment("lastName",Table.ALIGN_LEFT);
table.setColumnAlignment("firstName",Table.ALIGN_LEFT);
if (WinningOrderComparator.useRegistrationCategory) {
table.addGeneratedColumn("registrationCategory", columnGenerator); //$NON-NLS-1$
} else {
table.addGeneratedColumn("category", columnGenerator); //$NON-NLS-1$
}
table.addGeneratedColumn("total", columnGenerator); //$NON-NLS-1$
setExpandRatios();
}
@Override
protected void createToolbarButtons(HorizontalLayout tableToolbar1) {
// we do not call super because the default buttons are inappropriate.
final Locale locale = app.getLocale();
sessionSelect = new SessionSelect((CompetitionApplication) app, locale, parentView);
tableToolbar1.addComponent(sessionSelect);
{
final Button resultSpreadsheetButton = new Button(Messages.getString("ResultList.ResultSheet", locale)); //$NON-NLS-1$
final Button.ClickListener listener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
resultSpreadsheetButton.setComponentError(null);
if (!Competition.isMasters()) {
regularCompetition(locale);
} else {
mastersCompetition(locale);
}
}
/**
* @param locale1
* @throws RuntimeException
*/
private void regularCompetition(final Locale locale1) throws RuntimeException {
final JXLSWorkbookStreamSource streamSource = new JXLSResultSheet();
// final OutputSheetStreamSource<ResultSheet> streamSource = new OutputSheetStreamSource<ResultSheet>(
// ResultSheet.class, (CompetitionApplication) app, true);
if (streamSource.size() == 0) {
setComponentError(new SystemError(Messages.getString("ResultList.NoResults", locale1))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("ResultList.NoResults", locale1)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss") //$NON-NLS-1$
.format(new Date());
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("ResultList.ResultsPrefix", locale) + now); //$NON-NLS-1$
}
/**
* @param locale1
* @throws RuntimeException
*/
private void mastersCompetition(final Locale locale1) throws RuntimeException {
final OutputSheetStreamSource<MastersGroupResults> streamSource = new OutputSheetStreamSource<MastersGroupResults>(
MastersGroupResults.class, (CompetitionApplication) app, true);
if (streamSource.size() == 0) {
setComponentError(new SystemError(Messages.getString("ResultList.NoResults", locale1))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("ResultList.NoResults", locale1)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss") //$NON-NLS-1$
.format(new Date());
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("ResultList.ResultsPrefix", locale) + now); //$NON-NLS-1$
}
};
resultSpreadsheetButton.addListener(listener);
tableToolbar1.addComponent(resultSpreadsheetButton);
}
{
final Button teamResultSpreadsheetButton = new Button(Messages.getString(
"ResultList.TeamResultSheet", locale)); //$NON-NLS-1$
final Button.ClickListener teamResultClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
teamResultSpreadsheetButton.setComponentError(null);
final JXLSWorkbookStreamSource streamSource = new JXLSCompetitionBook();
if (streamSource.size() == 0) {
setComponentError(new SystemError(Messages.getString("ResultList.NoResults", locale))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("ResultList.NoResults", locale)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss") //$NON-NLS-1$
.format(new Date());
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("ResultList.TeamPrefix", locale) + now); //$NON-NLS-1$
// final OutputSheetStreamSource<CompetitionBook> streamSource = new OutputSheetStreamSource<CompetitionBook>(
// CompetitionBook.class, (CompetitionApplication) app, true);
// if (streamSource.size() == 0) {
// setComponentError(new SystemError(Messages.getString("ResultList.NoResults", locale))); //$NON-NLS-1$
// throw new RuntimeException(Messages.getString("ResultList.NoResults", locale)); //$NON-NLS-1$
// }
//
// String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss") //$NON-NLS-1$
// .format(new Date());
// ((UserActions) app).openSpreadsheet(streamSource, "teamResults_" + now); //$NON-NLS-1$
}
};
teamResultSpreadsheetButton.addListener(teamResultClickListener);
tableToolbar1.addComponent(teamResultSpreadsheetButton);
}
final Button refreshButton = new Button(Messages.getString("ResultList.Refresh", locale)); //$NON-NLS-1$
final Button.ClickListener refreshClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 7744958942977063130L;
@Override
public void buttonClick(ClickEvent event) {
logger.debug("reloading"); //$NON-NLS-1$
data.refresh(false);
}
};
refreshButton.addListener(refreshClickListener);
tableToolbar1.addComponent(refreshButton);
final Button editButton = new Button(Messages.getString("ResultList.edit", locale)); //$NON-NLS-1$
final Button.ClickListener editClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 7744958942977063130L;
@Override
public void buttonClick(ClickEvent event) {
editCompetitionSession(sessionSelect.getSelectedId(),sessionSelect.getSelectedItem());
}
};
editButton.addListener(editClickListener);
tableToolbar1.addComponent(editButton);
final Button publicAddressButton = new Button(Messages.getString("LiftList.publicAddress", app.getLocale())); //$NON-NLS-1$
final Button.ClickListener publicAddressClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 7744958942977063130L;
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication current = CompetitionApplication.getCurrent();
SessionData masterData = current.getMasterData(current.getPlatformName());
PublicAddressForm.editPublicAddress(ResultList.this, masterData);
}
};
publicAddressButton.addListener(publicAddressClickListener);
tableToolbar1.addComponent(publicAddressButton);
}
/**
* @return Localized captions for properties in same order as in
* {@link #getColOrder()}
*/
@Override
protected String[] getColHeaders() {
Locale locale = app.getLocale();
if (COL_HEADERS != null) return COL_HEADERS;
COL_HEADERS = new String[] { Messages.getString("Lifter.lotNumber", locale), //$NON-NLS-1$
Messages.getString("Lifter.lastName", locale), //$NON-NLS-1$
Messages.getString("Lifter.firstName", locale), //$NON-NLS-1$
//Messages.getString("Lifter.gender", locale), //$NON-NLS-1$
Messages.getString("Lifter.birthDate", locale), //$NON-NLS-1$
Messages.getString("Lifter.totalRank", locale), //$NON-NLS-1$
Messages.getString("Lifter.category", locale), //$NON-NLS-1$
Messages.getString("Lifter.bodyWeight", locale), //$NON-NLS-1$
Messages.getString("Lifter.club", locale), //$NON-NLS-1$
Messages.getString("Lifter.snatch1", locale), //$NON-NLS-1$
Messages.getString("Lifter.snatch2", locale), //$NON-NLS-1$
Messages.getString("Lifter.snatch3", locale), //$NON-NLS-1$
Messages.getString("Lifter.cleanJerk1", locale), //$NON-NLS-1$
Messages.getString("Lifter.cleanJerk2", locale), //$NON-NLS-1$
Messages.getString("Lifter.cleanJerk3", locale), //$NON-NLS-1$
Messages.getString("Lifter.total", locale), //$NON-NLS-1$
Messages.getString("Lifter.sinclair", locale), //$NON-NLS-1$
Messages.getString("Lifter.sinclairCat", locale), //$NON-NLS-1$
};
return COL_HEADERS;
}
/**
* @return Natural property order for Lifter bean. Used in tables and forms.
*/
@Override
protected String[] getColOrder() {
if (NATURAL_COL_ORDER != null) return NATURAL_COL_ORDER;
NATURAL_COL_ORDER = new String[] { "lotNumber", //$NON-NLS-1$
"lastName", //$NON-NLS-1$
"firstName", //$NON-NLS-1$
//"gender", //$NON-NLS-1$
"birthDate", //$NON-NLS-1$
"totalRank", //$NON-NLS-1$
(WinningOrderComparator.useRegistrationCategory ? "registrationCategory" //$NON-NLS-1$
: (Competition.isMasters() ? "mastersLongCategory" //$NON-NLS-1$
: "category")), //$NON-NLS-1$
"bodyWeight", //$NON-NLS-1$
"club", //$NON-NLS-1$
"snatch1ActualLift", //$NON-NLS-1$
"snatch2ActualLift", //$NON-NLS-1$
"snatch3ActualLift", //$NON-NLS-1$
"cleanJerk1ActualLift", //$NON-NLS-1$
"cleanJerk2ActualLift", //$NON-NLS-1$
"cleanJerk3ActualLift", //$NON-NLS-1$
"total", //$NON-NLS-1$
"sinclair", //$NON-NLS-1$
"categorySinclair", //$NON-NLS-1$
};
return NATURAL_COL_ORDER;
}
@Override
protected void init() {
super.init();
table.setSizeFull();
table.setNullSelectionAllowed(true);
table.setNullSelectionItemId(null);
}
/**
* Load container content to Table. We create a wrapper around the
* HbnContainer so we can sort on transient properties and suchlike.
*/
@Override
protected void loadData() {
List<Lifter> lifters = data.getResultOrder();
// logger.debug("loading data lifters={}",lifters);
if (lifters != null && !lifters.isEmpty()) {
final BeanItemContainer<Lifter> cont = new BeanItemContainer<Lifter>(Lifter.class,lifters);
table.setContainerDataSource(cont);
}
}
/**
* complete setup for table (after buildView has done its initial setup)
*/
@Override
protected void populateAndConfigureTable() {
super.populateAndConfigureTable(); // this creates a new table and calls
// loadData (below)
table.setColumnExpandRatio("lastName",100F);
table.setColumnExpandRatio("firstName",100F);
if (table.size() > 0) {
table.setEditable(false);
table.addListener(this); // listen to selection events
// set styling;
table.setCellStyleGenerator(new LiftCellStyleGenerator(table));
table.setCacheRate(0.1D);
}
this.updateTable();
clearSelection();
}
@Override
protected void setButtonVisibility() {
// nothing needed here, as this list contains no buttons
}
void sortTableInResultOrder() {
table.sort(new String[] { "resultOrderRank" }, new boolean[] { true }); //$NON-NLS-1$
}
/**
* Sorts the lifters in the correct order in response to a change in the
* data. Informs listeners that the order has been updated.
*/
void updateTable() {
// update our own user interface
this.sortTableInResultOrder(); // this does not change the selected row.
// final Item firstLifterItem = getFirstLifterItem();
// table.select(firstLifterItem); // so we change it.
// this.clearSelection();
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.CompetitionSessionLookup;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.webapp.WebApplicationConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* This class defines the screen layout for the competition secretary.
* <p>
* <ul>
* The top part shows the current lifter information and the lifters in lifting
* order. This list is actually the container from which data is pulled out.
* </ul>
* <ul>
* Clicking in the lift list selects a lifter, whose detail in shown in the
* bottom part.
* </ul>
* </p>
*
* @author jflamy
*
*/
public class ResultView extends VerticalSplitPanel implements ApplicationView, SessionData.UpdateEventListener, EditingView {
private static final long serialVersionUID = 7881028819569705161L;
private static final Logger logger = LoggerFactory.getLogger(ResultView.class);
private HorizontalLayout topPart;
private ResultList resultList;
private LifterCardEditor lifterCardEditor;
private CompetitionApplication app;
private boolean stickyEditor = false;
private SessionData groupData;
private String platformName;
private String viewName;
private String groupName;
/**
* Create view.
*
* @param mode
*/
public ResultView(boolean initFromFragment, String viewName) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.app = CompetitionApplication.getCurrent();
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (app.getPlatform() == null || !platformName.equals(app.getPlatformName())) {
app.setPlatformByName(platformName);
}
this.app = CompetitionApplication.getCurrent();
groupData = SessionData.getIndependentInstance();
final CompetitionSession currentGroup = groupData.getCurrentSession();
if (groupName != null && groupName.length() > 0) {
switchGroup(new CompetitionSessionLookup(app).lookup(groupName));
} else {
app.setCurrentCompetitionSession(currentGroup);
if (currentGroup != null) {
groupName = currentGroup.getName();
}
}
// left side is the lifting order, as well as the menu to switch groups.
resultList = new ResultList(groupData, this);
resultList.table.setPageLength(15);
resultList.table.setSizeFull();
resultList.setSizeFull();
topPart = new HorizontalLayout();
topPart.setSizeFull();
topPart.addComponent(resultList);
topPart.setExpandRatio(resultList, 100.0F);
this.setFirstComponent(topPart);
loadFirstLifterInfo(groupData, false);
adjustSplitBarLocation();
synchronized (app) {
boolean prevDisabled = app.getPusherDisabled();
app.setPusherDisabled(true);
// we are now fully initialized
groupData.addListener(this);
groupData.setAllowAll(true);
if (groupData.lifters.isEmpty()) {
logger.debug(
"switching groupData.lifters {}", groupData.lifters); //$NON-NLS-1$
switchGroup(app.getCurrentCompetitionSession());
} else {
logger.debug(
"not switching groupData {}", groupData.lifters); //$NON-NLS-1$
}
CompetitionApplication.getCurrent().getUriFragmentUtility().setFragment(getFragment(), false);
app.setPusherDisabled(prevDisabled);
}
app.push();
}
/**
* Update the lifter editor and the information panels with the first
* lifter.
*
* @param groupData1
*/
public void loadFirstLifterInfo(SessionData groupData1) {
final Lifter firstLifter = resultList.getFirstLifter();
final Item firstLifterItem = resultList.getFirstLifterItem();
updateLifterEditor(firstLifter, firstLifterItem);
}
/**
* Update the lifter editor and the information panels with the first
* lifter.
*
* @param groupData1
*/
public void loadFirstLifterInfo(SessionData groupData1, boolean sticky) {
loadFirstLifterInfo(groupData1);
if (lifterCardEditor != null) {
boolean buf = lifterCardEditor.ignoreChanges;
lifterCardEditor.ignoreChanges = true;
lifterCardEditor.setSticky(sticky);
lifterCardEditor.ignoreChanges = buf;
}
}
/**
* @param app
* @param lifter
*/
private void updateLifterEditor(final Lifter lifter, final Item lifterItem) {
// if (stickyEditor) return; // editor has asked not to be affected
if (lifter != null) {
if (lifterCardEditor == null) {
lifterCardEditor = new LifterCardEditor(resultList, this);
lifterCardEditor.loadLifter(lifter, lifterItem);
this.setSecondComponent(lifterCardEditor);
} else {
lifterCardEditor.loadLifter(lifter, lifterItem);
}
lifterCardEditor.setSticky(WebApplicationConfiguration.DEFAULT_STICKINESS); // make
// sticky
} else {
// no current lifter, hide bottom part if present.
if (lifterCardEditor != null) {
setSecondComponent(new Label("")); //$NON-NLS-1$
lifterCardEditor = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.concordiainternational.competition.ui.Refreshable#refresh()
*/
@Override
public void refresh() {
logger.debug("start refresh ----------"); //$NON-NLS-1$
CategoryLookup.getSharedInstance().reload();
resultList.refresh();
loadFirstLifterInfo(groupData);
logger.debug("end refresh ----------"); //$NON-NLS-1$
}
/**
* Set the split bar location
*/
void adjustSplitBarLocation() {
// compute percentage of split bar.
float height = app.getMainWindow().getHeight();
if (height > 0) this.setSplitPosition((int) ((height - 225) * 100 / height));
}
/**
* Load the designated lifter in the bottom pane
*
* @param lifter
* @param lifterItem
*/
@Override
public void editLifter(Lifter lifter, Item lifterItem) {
updateLifterEditor(lifter, lifterItem);
}
/**
* @return true if editor in bottom pane is pinned (not to be updated)
*/
@Override
public boolean isStickyEditor() {
return stickyEditor;
}
/**
* Indicate that the editor at bottom must not be updated
*
* @param freezeLifterCardEditor
*/
@Override
public void setStickyEditor(boolean freezeLifterCardEditor) {
setStickyEditor(freezeLifterCardEditor, true);
}
/**
* Indicate that the editor at bottom must not be updated
*
* @param freezeLifterCardEditor
*/
@Override
public void setStickyEditor(boolean freezeLifterCardEditor, boolean reloadLifterInfo) {
// logger.debug("is frozen: {}",freezeLifterCardEditor);
boolean wasSticky = this.stickyEditor;
this.stickyEditor = freezeLifterCardEditor;
// was sticky, no longer is
if (reloadLifterInfo && wasSticky && !freezeLifterCardEditor) loadFirstLifterInfo(groupData, false);
if (lifterCardEditor != null) lifterCardEditor.setSticky(freezeLifterCardEditor);
}
/**
* Copied from interface. Lift order has changed. Update the lift list and
* editor in the bottom part of the view.
*
* @see org.concordiainternational.competition.ui.SessionData.UpdateEventListener#updateEvent(org.concordiainternational.competition.ui.SessionData.UpdateEvent)
*/
@Override
public void updateEvent(final SessionData.UpdateEvent updateEvent) {
// FIXME: this throws an IllegalStateException
// Strange because this pattern is used everywhere else
// new Thread(new Runnable() {
// @Override
// public void run() {
synchronized (app) {
if (updateEvent.getForceRefresh()) {
logger.trace("updateEvent() received in Result view -- refreshing. ----------------------------------"); //$NON-NLS-1$
refresh();
return;
}
logger.trace("updateEvent() received in ResultView"); //$NON-NLS-1$
resultList.updateTable();
// loadFirstLifterInfo(groupData,WebApplicationConfiguration.DEFAULT_STICKINESS);
// update the info on the left side of the bottom part. This depends
// on the liftList info
// which has just changed.
if (lifterCardEditor != null
&& lifterCardEditor.lifterCardIdentification != null
&& !stickyEditor) {
lifterCardEditor.lifterCardIdentification.loadLifter(
lifterCardEditor.getLifter(),
resultList.getGroupData());
}
// updateLifterEditor(updateEvent.getCurrentLifter(),
// liftList.getFirstLifterItem());
}
app.push();
}
// }).start();
// }
/**
* Change the group that is being listened to.
*
* @param dataCurrentGroup
*/
private void switchGroup(final CompetitionSession dataCurrentGroup) {
logger.debug("===============ResultView switching to group {}", dataCurrentGroup); //$NON-NLS-1$
groupData.setCurrentSession(dataCurrentGroup);
if (dataCurrentGroup != null) {
groupName = dataCurrentGroup.getName();
} else {
groupName = "";
}
CompetitionApplication.getCurrent().getUriFragmentUtility().setFragment(getFragment(), false);
}
@Override
public void setCurrentSession(CompetitionSession competitionSession) {
setStickyEditor(false, false);
switchGroup(competitionSession);
}
/**
* @param groupData
* the groupData to set
*/
@Override
public void setSessionData(SessionData groupData) {
this.groupData = groupData;
}
/**
* @return the groupData
*/
public SessionData getSessionData() {
return groupData;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return true;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+(platformName == null ? "" : platformName)+"/"+(groupName == null ? "" : groupName);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
if (params.length >= 2) {
platformName = params[1];
} else {
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (params.length >= 3) {
groupName = params[2];
} else {
groupName = null;
}
}
@Override
public void registerAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void unregisterAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
/* Called on refresh.
* @see com.vaadin.terminal.URIHandler#handleURI(java.net.URL, java.lang.String)
*/
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
/**
* @return the resultList
*/
public ResultList getResultList() {
return resultList;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import java.util.Locale;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.decision.Speakers;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.list.GenericHbnList;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.hbnutil.HbnContainer.EntityItem;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class PlatformList extends GenericHbnList<Platform> implements ApplicationView {
private static final long serialVersionUID = -6455130090728823622L;
private String viewName;
final static org.slf4j.Logger logger = LoggerFactory.getLogger(PlatformList.class);
public PlatformList(boolean initFromFragment, String viewName) {
super(CompetitionApplication.getCurrent(), Platform.class, Messages.getString(
"PlatformList.Platforms", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
init();
}
private static String[] NATURAL_COL_ORDER = null;
private static String[] COL_HEADERS = null;
/**
* @return Natural property order for Category bean. Used in tables and
* forms.
*/
@Override
protected String[] getColOrder() {
if (NATURAL_COL_ORDER != null) return NATURAL_COL_ORDER;
NATURAL_COL_ORDER = new String[] {
"name", //$NON-NLS-1$
"hasDisplay", //$NON-NLS-1$
"showDecisionLights", //$NON-NLS-1$
"mixerName", //$NON-NLS-1$
"actions" //$NON-NLS-1$
};
return NATURAL_COL_ORDER;
}
/**
* @return Localized captions for properties in same order as in
* {@link #getColOrder()}
*/
@Override
protected String[] getColHeaders() {
Locale locale = app.getLocale();
if (COL_HEADERS != null) return COL_HEADERS;
COL_HEADERS = new String[] {
Messages.getString("CategoryEditor.name", locale), //$NON-NLS-1$
Messages.getString("Platform.NECDisplay", locale), //$NON-NLS-1$
Messages.getString("Platform.showDecisionLights", locale), //$NON-NLS-1$
Messages.getString("Platform.speakers", locale), //$NON-NLS-1$
Messages.getString("Common.actions", locale), //$NON-NLS-1$
};
return COL_HEADERS;
}
/**
* Default actions: delete.
*/
@Override
protected void addDefaultActions() {
table.removeGeneratedColumn("actions"); //$NON-NLS-1$
table.addGeneratedColumn("actions", new ColumnGenerator() { //$NON-NLS-1$
private static final long serialVersionUID = 7397136740353981832L;
@Override
public Component generateCell(Table source, final Object itemId, Object columnId) {
HorizontalLayout actions = new HorizontalLayout();
Button del = new Button(Messages.getString("Common.delete", app.getLocale())); //$NON-NLS-1$
del.addListener(new ClickListener() {
private static final long serialVersionUID = 5204920602544644705L;
@Override
public void buttonClick(ClickEvent event) {
try {
deleteItem(itemId);
} catch (ConstraintViolationException exception) {
throw new RuntimeException(Messages.getString("PlatformList.MustNotBeInUse", app
.getLocale()));
}
}
});
actions.addComponent(del);
return actions;
}
});
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.list.GenericHbnList#addGeneratedColumns()
*/
@Override
protected void addGeneratedColumns() {
super.addGeneratedColumns();
table.removeGeneratedColumn("mixerName"); //$NON-NLS-1$
table.addGeneratedColumn("mixerName", new ColumnGenerator() { //$NON-NLS-1$
private static final long serialVersionUID = 7397136740353981832L;
@SuppressWarnings("serial")
@Override
public Component generateCell(Table source, final Object itemId, Object columnId) {
final Item item = table.getItem(itemId);
//final Property uiProp = item.getItemProperty(columnId);
final Property prop = table.getContainerProperty(itemId, columnId);
if (!table.isEditable()) {
final Object value = prop.getValue();
return new Label((String) value); //$NON-NLS-1$
} else {
ComboBox ls = new ComboBox("", Speakers.getOutputNames());
ls.setNullSelectionAllowed(true);
ls.setPropertyDataSource(prop);
ls.setImmediate(true);
// normally, there is no need for a listener (the setImmediate will
// ensure that the setMixerName() method is called right away. But
// we would like audio feedback right away if there are multiple audio devices.
ls.addListener(new ValueChangeListener() {
@SuppressWarnings("rawtypes")
@Override
public void valueChange(ValueChangeEvent event) {
Platform pl = (Platform)((EntityItem) item).getPojo();
pl.setMixerName((String) event.getProperty().getValue());
new Speakers().testSound(pl.getMixer());
}
});
return ls;
}
}
});
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return true;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
}
@Override
public void registerAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void unregisterAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
/* Called on refresh.
* @see com.vaadin.terminal.URIHandler#handleURI(java.net.URL, java.lang.String)
*/
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.decision.Decision;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import org.concordiainternational.competition.decision.IDecisionController;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.mobile.IRefereeConsole;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UriFragmentUtility;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* Yes/No buttons for each referee.
*
* @author jflamy
*/
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class ORefereeConsole extends VerticalLayout implements DecisionEventListener, ApplicationView, CloseListener, URIHandler, IRefereeConsole {
private static final long serialVersionUID = 1L;
private HorizontalLayout top = new HorizontalLayout();
private HorizontalLayout bottom = new HorizontalLayout();
private SessionData masterData;
private CompetitionApplication app = CompetitionApplication.getCurrent();
private Logger logger = LoggerFactory.getLogger(ORefereeConsole.class);
private Integer refereeIndex = null;
private Label refereeReminder = new Label();
private String platformName;
private String viewName;
private IDecisionController decisionController;
private Label red;
private Label white;
public ORefereeConsole(boolean initFromFragment, String viewName) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
if (app == null) this.app = CompetitionApplication.getCurrent();
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
if (masterData == null) masterData = app.getMasterData(platformName);
if (decisionController == null) decisionController = getDecisionController();
app.getMainWindow().addURIHandler(this);
registerAsListener();
this.setSizeFull();
this.addStyleName("refereePad");
setupTop(decisionController);
setupBottom();
this.addComponent(top);
this.addComponent(bottom);
this.setExpandRatio(top, 80.0F);
this.setExpandRatio(bottom, 20.0F);
}
/**
* @return
*/
private IDecisionController getDecisionController() {
if (masterData == null) {
app = CompetitionApplication.getCurrent();
masterData = app.getMasterData(platformName);
}
return masterData.getRefereeDecisionController();
}
/**
* @param decisionController
*/
private void setupTop(final IDecisionController decisionController) {
top.setSizeFull();
top.setMargin(true);
top.setSpacing(true);
red = new Label();
red.setSizeFull();
red.addStyleName("red");
white = new Label();
white.addStyleName("white");
white.setSizeFull();
top.addComponent(red);
top.addComponent(white);
top.setExpandRatio(red,50.0F);
top.setExpandRatio(white,50.0F);
top.addListener(new LayoutClickListener() {
@Override
public void layoutClick(LayoutClickEvent event) {
Component child = event.getChildComponent();
if (child == red) {
new Thread(new Runnable() {
@Override
public void run() {
decisionController
.decisionMade(refereeIndex, false);
}
}).start();
redSelected();
} else if (child == white) {
new Thread(new Runnable() {
@Override
public void run() {
decisionController.decisionMade(refereeIndex, true);
}
}).start();
whiteSelected();
}
}
/**
*
*/
private void whiteSelected() {
white.removeStyleName("decisionUnselected");
red.removeStyleName("decisionSelected");
white.addStyleName("decisionSelected");
red.addStyleName("decisionUnselected");
resetBottom();
}
/**
*
*/
private void redSelected() {
white.removeStyleName("decisionSelected");
red.removeStyleName("decisionUnselected");
white.addStyleName("decisionUnselected");
red.addStyleName("decisionSelected");
resetBottom();
}
});
}
/**
*
*/
private void setupBottom() {
bottom.setSizeFull();
bottom.setMargin(false);
refereeReminder.setValue(refereeLabel(refereeIndex));
refereeReminder.setSizeFull();
bottom.addComponent(refereeReminder);
refereeReminder.setStyleName("refereeOk");
}
/**
* @param refereeIndex2
* @return
*/
private String refereeLabel(Integer refereeIndex2) {
if (refereeIndex2 == null) refereeIndex2 = 0;
return Messages.getString("RefereeConsole.Referee", CompetitionApplication.getCurrentLocale()) + " "
+ (refereeIndex2 + 1);
}
@Override
public void updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
Decision[] decisions = updateEvent.getDecisions();
final Boolean accepted = decisions[refereeIndex].accepted;
switch (updateEvent.getType()) {
case DOWN:
if (accepted == null) {
logger.info(
"referee #{} decision required after DOWN",
refereeIndex + 1);
requireDecision();
}
break;
case WAITING:
if (accepted == null) {
logger.info(
"referee #{} decision required WAITING",
refereeIndex + 1);
requireDecision();
}
break;
case UPDATE:
break;
case BLOCK:
// decisions are shown to the public; prevent refs from changing.
white.setEnabled(false);
red.setEnabled(false);
//top.setEnabled(false);
break;
case RESET:
logger.info("referee #{} RESET", refereeIndex + 1);
white.setStyleName("white");
red.setStyleName("red");
resetTop();
resetBottom();
break;
}
}
app.push();
}
}).start();
}
/**
* @param decisions
*/
@SuppressWarnings("unused")
private void allDecisionsIn(Decision[] decisions) {
synchronized (app) {
boolean allDecisionsIn = true;
for (int i = 0; i < 3; i++) {
allDecisionsIn = allDecisionsIn
&& (decisions[i].accepted != null);
}
white.setEnabled(!allDecisionsIn);
red.setEnabled(!allDecisionsIn);
}
app.push();
}
/**
*
*/
private void requireDecision() {
refereeReminder.setValue(Messages.getString("RefereeConsole.decisionRequired", CompetitionApplication.getCurrentLocale()));
refereeReminder.setStyleName("refereeReminder");
//CompetitionApplication.getCurrent().getMainWindow().executeJavaScript("alert('wakeup')");
}
/**
* reset styles for top part
*/
private void resetTop() {
white.setEnabled(true);
red.setEnabled(true);
}
@Override
public void refresh() {
}
private void resetBottom() {
synchronized (app) {
refereeReminder.setValue(refereeLabel(refereeIndex));
refereeReminder.setStyleName("refereeOk");
}
app.push();
}
/**
* @param refereeIndex
*/
@Override
public void setIndex(int refereeIndex) {
synchronized (app) {
this.refereeIndex = refereeIndex;
refereeReminder.setValue(refereeLabel(refereeIndex));
UriFragmentUtility uriFragmentUtility = CompetitionApplication.getCurrent().getUriFragmentUtility();
uriFragmentUtility.setFragment(getFragment(), false);
}
getDecisionController().addListener(this,refereeIndex);
app.push();
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+(platformName == null ? "" : platformName)+"/"+((int)this.refereeIndex+1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
if (params.length >= 2) {
platformName = params[1];
} else {
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (params.length >= 3) {
setIndex(Integer.parseInt(params[2])-1);
} else {
throw new RuleViolationException("Error.RefereeNumberIsMissing");
}
}
/**
* Register all listeners for this app.
* Exception: do not register the URIHandler here.
*/
@Override
public void registerAsListener() {
logger.debug("registering as listener");
app.getMainWindow().addListener((CloseListener)this);
if (refereeIndex != null) {
setIndex(refereeIndex);
}
}
/**
* Undo all registrations in {@link #registerAsListener()}.
*/
@Override
public void unregisterAsListener() {
logger.debug("unregistering as listener");
app.getMainWindow().removeListener((CloseListener)this);
decisionController.removeListener(this);
}
/* Will be called when page is loaded.
* @see com.vaadin.terminal.URIHandler#handleURI(java.net.URL, java.lang.String)
*/
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
app.getMainWindow().executeJavaScript("scrollTo(0,1)");
return null;
}
/* Will be called when page is unloaded (including on refresh).
* @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window.CloseEvent)
*/
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import java.util.Locale;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.list.GenericHbnList;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class CategoryList extends GenericHbnList<Category> implements ApplicationView {
private static final long serialVersionUID = -6455130090728823622L;
private String viewName;
public CategoryList(boolean initFromFragment, String viewName) {
super(CompetitionApplication.getCurrent(), Category.class, Messages.getString(
"CategoryList.Categories", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
init();
}
private static String[] NATURAL_COL_ORDER = null;
private static String[] COL_HEADERS = null;
/**
* @return Natural property order for Category bean. Used in tables and
* forms.
*/
@Override
public String[] getColOrder() {
if (NATURAL_COL_ORDER != null) return NATURAL_COL_ORDER;
NATURAL_COL_ORDER = new String[] { "name", //$NON-NLS-1$
"gender", //$NON-NLS-1$
"minimumWeight", //$NON-NLS-1$
"maximumWeight", //$NON-NLS-1$
"active", //$NON-NLS-1$
"actions" //$NON-NLS-1$
};
return NATURAL_COL_ORDER;
}
/**
* @return Localized captions for properties in same order as in
* {@link #getColOrder()}
*/
@Override
public String[] getColHeaders() {
Locale locale = app.getLocale();
if (COL_HEADERS != null) return COL_HEADERS;
COL_HEADERS = new String[] { Messages.getString("CategoryEditor.name", locale), //$NON-NLS-1$
Messages.getString("CategoryEditor.gender", locale), //$NON-NLS-1$
Messages.getString("CategoryEditor.minimumWeight", locale), //$NON-NLS-1$
Messages.getString("CategoryEditor.maximumWeight", locale), //$NON-NLS-1$
Messages.getString("CategoryEditor.Active", locale), //$NON-NLS-1$
Messages.getString("Common.actions", locale), //$NON-NLS-1$
};
return COL_HEADERS;
}
/**
* This method is used in response to a button click.
*/
@Override
public void toggleEditable() {
super.toggleEditable();
if (!table.isEditable()) {
CategoryLookup.getSharedInstance().reload();
}
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return true;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
}
@Override
public void registerAsListener() {
CompetitionApplication.getCurrent().getMainWindow().addListener((CloseListener) this);
}
@Override
public void unregisterAsListener() {
CompetitionApplication.getCurrent().getMainWindow().addListener((CloseListener) this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import java.util.Date;
import java.util.MissingResourceException;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.components.CategorySelect;
import org.concordiainternational.competition.ui.components.ISO8601DateField;
import org.concordiainternational.competition.ui.components.PlatformSelect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.Application;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Validator;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
import com.vaadin.data.validator.DoubleValidator;
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.InlineDateField;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
public class CommonFieldFactory extends DefaultFieldFactory {
private static final long serialVersionUID = 8789528655171127108L;
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(CommonFieldFactory.class);
private Application app;
public CommonFieldFactory(HbnSessionManager app) {
this.app = (Application) app;
}
/* (non-Javadoc)
* @see com.vaadin.ui.DefaultFieldFactory#createField(com.vaadin.data.Item, java.lang.Object, com.vaadin.ui.Component)
*/
@Override
public Field createField(Item item, Object propertyId, Component uiContext) {
Class<?> type = item.getItemProperty(propertyId).getType();
Field field = createFieldByPropertyType(type);
return adjustField(propertyId, uiContext, field);
}
/* (non-Javadoc)
* @see com.vaadin.ui.DefaultFieldFactory#createField(com.vaadin.data.Container, java.lang.Object, java.lang.Object, com.vaadin.ui.Component)
*/
@Override
public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) {
Property containerProperty = container.getContainerProperty(itemId, propertyId);
Class<?> type = containerProperty.getType();
Field field = createFieldByPropertyType(type);
return adjustField(propertyId, uiContext, field);
}
/**
* Adjust formatting and caption for the field.
* @param propertyId
* @param uiContext
* @param f
* @return
*/
private Field adjustField(Object propertyId, Component uiContext, Field f) {
try {
String caption = Messages.getStringWithException("FieldName." + propertyId,
CompetitionApplication.getCurrentLocale());
f.setCaption(caption);
} catch (MissingResourceException e) {
f.setCaption(createCaptionByPropertyId(propertyId));
}
((AbstractField) f).setImmediate(true);
final String propertyIdString = (String) propertyId;
if (propertyIdString.endsWith("Weight")) { //$NON-NLS-1$
return checkFloat(f);
}
if (propertyIdString.contains("snatch") //$NON-NLS-1$
|| propertyIdString.contains("cleanJerk")) { //$NON-NLS-1$
return checkInteger(f);
}
if (propertyIdString.contains("Time") && (f instanceof DateField)) { //$NON-NLS-1$
return adjustDateHourField((DateField) f);
}
if (propertyIdString.contains("Hour") && (f instanceof DateField)) { //$NON-NLS-1$
Field adjustedHourField = adjustDateHourField((DateField) f);
return adjustedHourField;
}
if (propertyIdString.contains("Date") && (f instanceof DateField)) { //$NON-NLS-1$
return adjustDateField((DateField) f);
}
if (propertyIdString.equals("categories")) { //$NON-NLS-1$
String caption = f.getCaption();
f = new CategorySelect();
f.setCaption(caption);
((CategorySelect) f).setMultiSelect(true);
return f;
}
if (propertyIdString.equals("category")) { //$NON-NLS-1$
String caption = f.getCaption();
f = new CategorySelect();
f.setCaption(caption);
((CategorySelect) f).setMultiSelect(false);
return f;
}
if (propertyIdString.equals("platform")) { //$NON-NLS-1$
String caption = f.getCaption();
f = new PlatformSelect();
f.setCaption(caption);
((PlatformSelect) f).setMultiSelect(false);
return f;
}
if (propertyIdString.contains("competition")) { //$NON-NLS-1$
f.setWidth("25em");
return f;
}
if (propertyIdString.contains("gender")) { //$NON-NLS-1$
f.setWidth("3em");
return f;
}
if (propertyIdString.contains("Name")) { //$NON-NLS-1$
f.setWidth("100%");
return f;
}
if (propertyIdString.contains("name")) { //$NON-NLS-1$
f.setWidth("100%");
return f;
}
if (f instanceof TextField && (uiContext instanceof Form)) {
((TextField) f).setWidth("25em"); //$NON-NLS-1$
}
if (f instanceof TextField && (uiContext instanceof Table)) {
((TextField) f).setWidth("90%"); //$NON-NLS-1$
}
return f;
}
/**
* Override the default.
* @param type
* @return
*/
public static Field createFieldByPropertyType(Class<?> type) {
//logger.debug("creating {}",type);
// Null typed properties can not be edited
if (type == null) {
return null;
}
// Date field
if (Date.class.isAssignableFrom(type)) {
final DateField df = new ISO8601DateField();
df.setResolution(DateField.RESOLUTION_DAY);
return df;
}
// Boolean field
if (Boolean.class.isAssignableFrom(type)) {
return new CheckBox();
}
if (Category.class.isAssignableFrom(type)) {
return new CategorySelect();
}
if (Platform.class.isAssignableFrom(type)) {
return new PlatformSelect();
}
return new TextField();
}
private Field adjustDateField(DateField f) {
f.setDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
f.setResolution(DateField.RESOLUTION_DAY);
return f;
}
private Field adjustDateHourField(DateField f) {
f.setDateFormat("yyyy-MM-dd HH:mm"); //$NON-NLS-1$
f.setResolution(DateField.RESOLUTION_MIN);
return f;
}
@SuppressWarnings("unused")
private InlineDateField adjustHourField(DateField f) {
String caption = f.getCaption();
f = new InlineDateField();
f.setCaption(caption);
f.setDateFormat("HH:mm"); //$NON-NLS-1$
f.setResolution(DateField.RESOLUTION_MIN);
return (InlineDateField) f;
}
/**
* @param f
* @return
*/
private Field checkFloat(final Field f) {
f.setWidth("4em"); //$NON-NLS-1$
f.addValidator(new DoubleValidator(Messages.getString("CommonFieldFactory.badNumberFormat", app.getLocale())) //$NON-NLS-1$
// new Validator() {
// private static final long serialVersionUID =
// -4073378031354132670L;
//
// public boolean isValid(Object value) {
// try {
// System.err.println("validator called");
// Float.parseFloat((String) value);
// return true;
// } catch (Exception e) {
// f.getWindow().showNotification(Messages.getString("CommonFieldFactory.badNumberFormat",app.getLocale())); //$NON-NLS-1$
// f.setValue(0);
// return false;
// }
// }
//
// public void validate(Object value) throws
// InvalidValueException {
// System.err.println("validate called");
// if (!isValid(value)) throw new InvalidValueException(Messages.getString("CommonFieldFactory.badNumberFormat",app.getLocale())); //$NON-NLS-1$
// }
// }
);
return f;
}
/**
* @param f
* @return
*/
private Field checkInteger(final Field f) {
f.setWidth("4em"); //$NON-NLS-1$
f.addValidator(new Validator() {
private static final long serialVersionUID = -4073378031354132670L;
@Override
public boolean isValid(Object value) {
try {
Integer.parseInt((String) value);
return true;
} catch (Exception e) {
f.getWindow().showNotification(
Messages.getString("CommonFieldFactory.badNumberFormat", app.getLocale())); //$NON-NLS-1$
f.setValue(0);
return false;
}
}
@Override
public void validate(Object value) throws InvalidValueException {
if (!isValid(value))
throw new InvalidValueException(Messages.getString(
"CommonFieldFactory.badNumberFormat", app.getLocale())); //$NON-NLS-1$
}
});
return f;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Property;
import com.vaadin.ui.Field;
import com.vaadin.ui.Table;
import com.vaadin.ui.TableFieldFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class FieldTable extends Table {
Logger logger = LoggerFactory.getLogger(FieldTable.class);
DecimalFormat threeDecimals = new DecimalFormat("0.000", new DecimalFormatSymbols(CompetitionApplication.getCurrentLocale()));
DecimalFormat twoDecimals = new DecimalFormat("0.00", new DecimalFormatSymbols(CompetitionApplication.getCurrentLocale()));
/* Always use a field, so that the read-only version is consistent with the editing formatting.
* @see com.vaadin.ui.Table#getPropertyValue(java.lang.Object, java.lang.Object, com.vaadin.data.Property)
*/
@Override
protected Object getPropertyValue(Object rowId, Object colId,
Property property) {
TableFieldFactory tableFieldFactory = getTableFieldFactory();
if ( tableFieldFactory != null) {
final Field f = tableFieldFactory.createField(getContainerDataSource(),
rowId, colId, this);
if (f != null) {
f.setPropertyDataSource(property);
if (isEditable()) {
return f;
} else {
return formatPropertyValue(rowId, colId, property);
}
}
}
return formatPropertyValue(rowId, colId, property);
}
@Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
// Format by property type
if (property.getType() == Double.class) {
Double value = (Double) property.getValue();
if (value == null) value = 0.0;
if (((String)colId).endsWith("inclair")) {
return threeDecimals.format(value);
} else {
return twoDecimals.format(value);
}
}
return super.formatPropertyValue(rowId, colId, property);
}
/* (non-Javadoc)
* @see com.vaadin.ui.Table#getColumnAlignment(java.lang.Object)
*/
@Override
public String getColumnAlignment(Object propertyId) {
// if (this.isEditable()) {
// return ALIGN_CENTER;
// } else {
if (((String)propertyId).endsWith("Name")){
// logger.warn("{} {}",propertyId,"left");
return ALIGN_LEFT;
} else {
// logger.warn("{} {}",propertyId,"right");
return ALIGN_RIGHT;
}
// }
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.utils.ItemAdapter;
import com.vaadin.data.Property;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.CellStyleGenerator;
public class LiftCellStyleGenerator implements CellStyleGenerator {
private static final long serialVersionUID = 698507270413719482L;
private Table table;
public LiftCellStyleGenerator(Table table) {
this.table = table;
}
@Override
public String getStyle(Object itemId, Object propertyId) {
// final Item item = table.getItem(itemId);
// final Property uiProp = item.getItemProperty(propertyIdString);
// System.err.println("table.getValue "+table.getValue()+" itemId"+itemId);
if (itemId.equals(table.getValue())) return null;
if (propertyId == null) {
// no propertyId, styling row
return null;
} else {
final Lifter lifter = (Lifter) ItemAdapter.getObject(table, itemId);
final String propertyIdString = (String) propertyId;
final Property sourceProp = table.getContainerProperty(itemId, propertyIdString);
if (propertyIdString.contains("ActualLift")) { //$NON-NLS-1$
if (sourceProp != null) {
final String value = (String) sourceProp.getValue();
if (value != null) {
int intValue = WeightFormatter.safeParseInt(value);
if (!value.isEmpty()) {
if (intValue > 0) {
return "success"; //$NON-NLS-1$
} else {
return "fail"; //$NON-NLS-1$
}
}
}
} else {
return null;
}
} else if (propertyIdString.equals("total")) { //$NON-NLS-1$
if (sourceProp != null) {
// use the lifter because there is no property.
final Integer value = lifter.getTotal();
if (value != null) {
if (value > 0) {
return "total"; //$NON-NLS-1$
}
}
}
} else if (propertyIdString.contains("Name") || propertyIdString.contains("Requested")) { //$NON-NLS-1$ //$NON-NLS-2$
if (lifter.isCurrentLifter()) return "current"; //$NON-NLS-1$
}
}
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
public class TimeFormatter {
public static String formatAsSeconds(Integer remainingMilliseconds) {
if (remainingMilliseconds == null) return "";
if (remainingMilliseconds < 0){
remainingMilliseconds = 0;
}
int iSecs = getSeconds(remainingMilliseconds);
int iMins = (iSecs / 60);
int rSecs = (iSecs % 60);
return String.format("%1$d:%2$02d", iMins, rSecs); //$NON-NLS-1$
}
/**
* Compute the number of seconds left.
* Note that we go up to the next integer to make sure that when the display
* shows 2:00, 1:30, 0:30 and 0:00 for the first time that is the exact time
* left. If the time left is 0:30.4, we want the clock to say 0:31, not 0:30.
*
* @param remainingMilliseconds
* @return the number of seconds, making sure that zero means "time is up".
*/
public static int getSeconds(int remainingMilliseconds) {
double dSecs = (remainingMilliseconds / 1000.0D);
long roundedSecs = Math.round(dSecs);
int iSecs;
double delta = dSecs - roundedSecs;
if (Math.abs(delta) < 0.001) {
// 4.0009 is 4, not 5, for our purposes. We do not ever want 2:01
// because of rounding errors
iSecs = Math.round((float) dSecs);
} else {
iSecs = (int) Math.ceil(dSecs);
}
return iSecs;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.i18n.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class to pretty print values (for JSP in particular).
*
* @author jflamy
*
*/
public class TryFormatter {
private static Logger logger = LoggerFactory.getLogger(TryFormatter.class);
/**
* @param accessorName
* @param attributeObject
* @return
* @throws RuntimeException
*/
public static String htmlFormatTry(List<Lifter> lifters, Lifter lifter) {
Locale locale = Locale.CANADA_FRENCH;
String suffix = ""; //$NON-NLS-1$
final Lifter firstLifter = lifters.get(0);
if (firstLifter.getAttemptsDone() < 3 && lifter.getAttemptsDone() >= 3) {
// the current lifter is done snatch whereas the top lifter on the
// board is still doing snatch.
suffix = Messages.getString("TryFormatter.shortCleanJerk", locale); //$NON-NLS-1$
}
final int currentTry = 1 + (lifter.getAttemptsDone() >= 3 ? lifter.getCleanJerkAttemptsDone() : lifter
.getSnatchAttemptsDone());
if (currentTry > 3) {
return Messages.getString("TryFormatter.Done", locale); //$NON-NLS-1$
} else {
String tryInfo = currentTry + suffix;
return tryInfo;
}
}
public static String htmlFormatLiftsDone(int number, Locale locale) {
final String formatString = Messages.getString("ResultList.attemptsDone", locale);
logger.debug("lifts done = {} format={}", number, formatString);
return MessageFormat.format(formatString, //$NON-NLS-1$
number);
}
/**
* @param locale
* @param currentTry
* @return
*/
public static String formatTry(Lifter lifter, final Locale locale, final int currentTry) {
String tryInfo = MessageFormat.format(Messages.getString("LifterInfo.tryNumber", locale), //$NON-NLS-1$
currentTry, (lifter.getAttemptsDone() >= 3 ? Messages.getString("Common.shortCleanJerk", locale) //$NON-NLS-1$
: Messages.getString("Common.shortSnatch", locale))); //$NON-NLS-1$
return tryInfo;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
/**
* Utility class to pretty print values.
*
* @author jflamy
*
*/
public class WeightFormatter {
public static String formatWeight(String value) {
value = value.trim();
if (value.isEmpty()) return value;
try {
int intValue = parseInt(value);
return formatWeight(intValue);
} catch (NumberFormatException e) {
return value;
}
}
/**
* @param value
* @param intValue
* @return
*/
public static String formatWeight(Integer intValue) {
if (intValue == 0) return "-"; //$NON-NLS-1$
else if (intValue > 0) return Integer.toString(intValue);
else return "(" + (-intValue) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @param accessorName
* @param attributeObject
* @return
* @throws RuntimeException
*/
public static String htmlFormatWeight(String value) {
value = value.trim();
if (value == null) return "<td class='empty'></td>"; //$NON-NLS-1$
if (value.isEmpty()) return "<td class='empty'></td>"; //$NON-NLS-1$
try {
int intValue = parseInt(value);
if (intValue == 0) return "<td class='fail'>–</td>"; //$NON-NLS-1$
else if (intValue > 0) return "<td class='success'>" + value + "</td>"; //$NON-NLS-1$ //$NON-NLS-2$
else return "<td class='fail'>(" + (-intValue) + ")</td>"; //$NON-NLS-1$ //$NON-NLS-2$
} catch (NumberFormatException e) {
return "<td class='other'>" + value + "</td>"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
static String weightFormat = Messages.getString(
"WeightFormatter.WeightFormat", CompetitionApplication.getDefaultLocale()); //$NON-NLS-1$
static DecimalFormat weightFormatter = new DecimalFormat(weightFormat, new DecimalFormatSymbols(Locale.US));
/**
* @param accessorName
* @param attributeObject
* @return
* @throws RuntimeException
*/
public static String htmlFormatBodyWeight(Double value) {
;
if (value == null) return "<td class='narrow'></td>"; //$NON-NLS-1$
try {
String stringValue = formatBodyWeight(value);
return "<td class='narrow'>" + stringValue + "</td>"; //$NON-NLS-1$ //$NON-NLS-2$
} catch (NumberFormatException e) {
return "<td class='other'>" + value + "</td>"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* @param value
* @return
* @throws NumberFormatException
*/
public static String formatBodyWeight(Double value) throws NumberFormatException {
String stringValue = weightFormatter.format(Math.abs(value));
return stringValue;
}
public static int parseInt(String value) throws NumberFormatException {
if (value.startsWith("(") && value.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$
// accounting style number
return Integer.parseInt(value.substring(1, value.length() - 2));
} else {
if (value.trim().isEmpty()) return 0;
return Integer.parseInt(value);
}
}
public static float parseFloat(String value) throws NumberFormatException {
if (value.startsWith("(") && value.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$
// accounting style number
return Float.parseFloat(value.substring(1, value.length() - 2));
} else {
if (value.trim().isEmpty()) return 0;
return Float.parseFloat(value);
}
}
public static boolean validate(String value) {
try {
if (value.startsWith("(") && value.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$
// accounting style number
Integer.parseInt(value.substring(1, value.length() - 2));
} else {
if (value.trim().isEmpty()) return true;
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
public static int safeParseInt(String value) {
try {
if (value.startsWith("(") && value.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$
// accounting style number
return Integer.parseInt(value.substring(1, value.length() - 2));
} else {
if (value.trim().isEmpty()) return 0;
return Integer.parseInt(value);
}
} catch (NumberFormatException nfe) {
return 0;
}
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui.generators;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryContainer;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.ItemAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.addons.beantuplecontainer.BeanTupleItem;
import org.vaadin.addons.criteriacontainer.CriteriaContainer;
import org.vaadin.addons.criteriacontainer.CriteriaQueryDefinition;
import com.vaadin.Application;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.PropertyFormatter;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Field;
import com.vaadin.ui.Label;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.PopupView;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
/**
* @author jflamy
*
*/
public class CommonColumnGenerator implements Table.ColumnGenerator {
private static final long serialVersionUID = 6573562545694966025L;
private static final Logger logger = LoggerFactory.getLogger(CommonColumnGenerator.class);
private CategoryContainer activeCategories;
private CriteriaContainer<Platform> platforms;
private CriteriaContainer<CompetitionSession> competitionSessions;
private CompetitionApplication app;
public CommonColumnGenerator(Application app) {
activeCategories = new CategoryContainer((EntityManager) app, true);
CriteriaQueryDefinition<Platform> qd = new CriteriaQueryDefinition<Platform>((EntityManager) app,true,100,Platform.class);
platforms = new CriteriaContainer<Platform>(qd);
CriteriaQueryDefinition<CompetitionSession> qd2 = new CriteriaQueryDefinition<CompetitionSession>((EntityManager) app,true,100,CompetitionSession.class);
competitionSessions = new CriteriaContainer<CompetitionSession>(qd2);
this.app = (CompetitionApplication) app;
}
@Override
public Component generateCell(Table table, Object itemId, Object propertyId) {
final Item item = table.getItem(itemId);
final String propertyIdString = (String) propertyId;
final Property uiProp = item.getItemProperty(propertyIdString);
final Property prop = table.getContainerProperty(itemId, propertyIdString);
// System.err.println("generating cell for : "+propertyIdString);
if (propertyIdString.equals("categories")) { //$NON-NLS-1$ //$NON-NLS-2$
return generateCategoriesCell(table, itemId, uiProp, prop);
} else if (propertyIdString.equals("category")) { //$NON-NLS-1$ //$NON-NLS-2$
return generateCategoryCell(table, itemId, item, propertyIdString);
} else if (propertyIdString.equals("registrationCategory")) { //$NON-NLS-1$ //$NON-NLS-2$
return generateRegistrationCategoryCell(table, itemId, uiProp, prop);
} else if (propertyIdString.contains("ActualLift")) { //$NON-NLS-1$ //$NON-NLS-2$
return generateLiftCell(table, itemId, uiProp, prop);
} else if (propertyIdString.equals("total")) { //$NON-NLS-1$
Lifter lifter = getLifter(item);
return new Label(WeightFormatter.formatWeight((lifter.getTotal())));
}
// else if (propertyIdString.contains("Time")) { //$NON-NLS-1$
// return generateTimeCell(prop);
// }
else if (propertyIdString.equals("platform")) { //$NON-NLS-1$
return generatePlatformCell(table, itemId, uiProp, prop);
} else if (propertyIdString.equals("competitionSession")) { //$NON-NLS-1$
return generateGroupCell(table, itemId, uiProp, prop);
}
else if (propertyIdString.equals("totalRank")) { //$NON-NLS-1$
return generateRankCell(prop, table.isEditable());
}
else if (propertyIdString.equals("teamMember")) { //$NON-NLS-1$
return generateBooleanCell(table, itemId, uiProp, prop);
} else if (propertyIdString.equals("qualifyingTotal")) { //$NON-NLS-1$
return generateIntegerCell(table, itemId, uiProp, prop);
} else {
return generateDefaultCell(prop);
}
}
/**
* @param prop
* @return
*/
private Component generateBooleanCell(Table table, Object itemId, final Property uiProp, final Property sourceProp) {
Field msField = new CheckBox();
msField.setCaption("");
msField.setWidth("2ex"); //$NON-NLS-1$
if (sourceProp.getValue() == null) sourceProp.setValue(true);
msField.setPropertyDataSource(sourceProp);
msField.setReadOnly(!table.isEditable());
return msField;
}
/**
* @param table
* @param itemId
* @param uiProp
* @param sourceProp
* @return
*/
private Component generateIntegerCell(Table table, Object itemId, final Property uiProp, final Property sourceProp) {
Field msField = new TextField();
msField.setCaption("");
msField.setWidth("4ex"); //$NON-NLS-1$
if (sourceProp.getValue() == null) sourceProp.setValue(true);
msField.setPropertyDataSource(sourceProp);
msField.setReadOnly(!table.isEditable());
return msField;
}
/**
* @param table
* @param itemId
* @param item
* @param propertyIdString
* @return
*/
private Component generateCategoryCell(Table table, Object itemId, final Item item, final String propertyIdString) {
Component c = null;
if (item instanceof Entity) {
c = dynamicCategoryLabel(table, item, itemId, propertyIdString);
} else {
c = categoryLabel(table, item, itemId, propertyIdString);
}
return c;
}
/**
* @param table
* @param itemId
* @param uiProp
* @param sourceProp
* @return
*/
private Component generateLiftCell(Table table, Object itemId, final Property uiProp, final Property sourceProp) {
final String value = (String) sourceProp.getValue();
if (value != null && value.trim().length() > 0) {
int intValue = WeightFormatter.safeParseInt(value);
final Label label = new Label((WeightFormatter.formatWeight(value)));
if (!value.isEmpty()) {
if (intValue > 0) {
label.addStyleName("success"); //$NON-NLS-1$
} else {
label.addStyleName("fail"); //$NON-NLS-1$
}
return label;
}
}
return new Label(""); //$NON-NLS-1$
}
/**
* @param table
* @param itemId
* @param uiProp
* @param prop
* @return
*/
private Component generatePlatformCell(Table table, Object itemId, final Property uiProp, final Property prop) {
final Object value = uiProp.getValue();
if (!table.isEditable()) {
if (table.getContainerDataSource() instanceof CriteriaContainer<?>) {
if (value == null) return new Label("-"); //$NON-NLS-1$
Platform platformBean = (platforms.getEntity(value));
return new Label(platformBean.getName());
} else {
throw new UnsupportedOperationException(Messages.getString("CommonColumnGenerator.0", app.getLocale())); //$NON-NLS-1$
}
} else {
// Field msField = getPlatformComboboxFor(itemId);
// msField.setPropertyDataSource(prop);
// return msField;
return getPlatformPopUpFor(itemId, uiProp);
}
}
/**
* @param table
* @param itemId
* @param uiProp
* @param prop
* @return
*/
private Component generateGroupCell(Table table, Object itemId, Property uiProp, Property prop) {
final Object value = uiProp.getValue();
if (!table.isEditable()) {
if (table.getContainerDataSource() instanceof CriteriaContainer<?>) {
if (value == null) return new Label("-"); //$NON-NLS-1$
CompetitionSession competitionSession = (competitionSessions.getEntity(value));
return new Label(competitionSession.getName());
} else {
throw new UnsupportedOperationException(Messages.getString("CommonColumnGenerator.0", app.getLocale())); //$NON-NLS-1$
}
} else {
// Field msField = getGroupComboboxFor(itemId);
// msField.setPropertyDataSource(prop);
// return msField;
return getGroupPopUpFor(itemId, uiProp);
}
}
/**
* @param prop
* @return
*/
private Component generateDefaultCell(final Property prop) {
final Object value = prop.getValue();
if (value == null) {
final Label nullItem = new Label(Messages.getString("Common.emptyList", app.getLocale())); //$NON-NLS-1$
return nullItem;
}
return new Label(value.toString());
}
/**
* No longer CommonFieldFactory handles this.
* @param prop
* @return
*/
@SuppressWarnings("unused")
private Component generateTimeCell(final Property prop) {
DateField timeField = new DateField();
timeField.setPropertyDataSource(prop);
return adjustDateField(timeField);
}
@SuppressWarnings("unchecked")
PropertyFormatter propertyFormatter = new PropertyFormatter() {
private static final long serialVersionUID = 1L;
@Override
public String format(Object value) {
if (value == null) return ""; //$NON-NLS-1$
try {
int rank = Integer.valueOf(value.toString());
if (rank == 0) {
return ""; //$NON-NLS-1$
} else if (rank > 0) {
return Integer.toString(rank);
} else return Messages.getString(
"CommonColumnGenerator.InvitedAbbreviation", CompetitionApplication.getCurrentLocale()); //$NON-NLS-1$
} catch (NumberFormatException e) {
return "?"; //$NON-NLS-1$
}
}
@Override
public Object parse(String formattedValue) throws Exception {
if (formattedValue == null) return 0;
if (formattedValue.trim().isEmpty()) {
return 0;
} else {
Integer value = null;
try {
value = Integer.decode(formattedValue);
} catch (NumberFormatException e) {
value = -1;
}
return value;
}
}
};
/**
* @param prop
* @param isEditable
* @return
*/
private Component generateRankCell(final Property prop, boolean isEditable) {
if (isEditable) {
TextField rankField = new TextField();
//rankField.setWidth("3em"); //$NON-NLS-1$
rankField.setReadOnly(true);
rankField.setPropertyDataSource(propertyFormatter);
return rankField;
} else {
return new Label(propertyFormatter.format(prop.getValue()));
}
}
/**
* @param table
* @param itemId
* @param uiProp
* @param prop
* @return
*/
private Component generateRegistrationCategoryCell(Table table, Object itemId, final Property uiProp,
final Property prop) {
if (!table.isEditable()) {
final Object value = prop.getValue();
return new Label(categoryItemDisplayString(value)); //$NON-NLS-1$
} else {
// Field msField = getCategoryComboboxFor(itemId);
Component msField = getCategoryPopUpFor(itemId, uiProp);
//msField.setWidth("12ex"); //$NON-NLS-1$
// msField.setPropertyDataSource(prop);
return msField;
}
}
/**
* @param value
* @param curCategory
* @return
*/
private String categoryItemDisplayString(final Object value) {
Category curCategory = null;
if (value != null) {
if (value instanceof Category) {
curCategory = (Category) value;
} else {
curCategory = activeCategories.getEntity(value);
}
}
return (curCategory != null ? curCategory.getName() : Messages
.getString("Common.noneSelected", app.getLocale()));
}
/**
* @param value
* @param curCategory
* @return
*/
private String groupItemDisplayString(final Object value) {
CompetitionSession curGroup = null;
if (value != null) {
if (value instanceof CompetitionSession) {
curGroup = (CompetitionSession) value;
} else {
curGroup = (CompetitionSession) ItemAdapter.getObject(competitionSessions.getItem(value));
}
}
return (curGroup != null ? curGroup.getName() : Messages.getString("Common.noneSelected", app.getLocale()));
}
/**
* @param table
* @param itemId
* @param uiProp
* @param prop
* @return
*/
@SuppressWarnings("unchecked")
private Component generateCategoriesCell(Table table, Object itemId, final Property uiProp, final Property prop) {
final Object value = uiProp.getValue();
if (!table.isEditable()) {
if (table.getContainerDataSource() instanceof CriteriaContainer) {
return new Label(categorySetToString((Set<Long>) value));
} else {
throw new UnsupportedOperationException(Messages.getString("CommonColumnGenerator.1", app.getLocale())); //$NON-NLS-1$
}
} else {
// Field msField = getCategoriesMultiSelectFor(itemId);
// msField.setPropertyDataSource(prop);
// return msField;
return getCategoriesPopUpFor(itemId, uiProp);
}
}
public Map<Object, ListSelect> groupIdToCategoryList = new HashMap<Object, ListSelect>();
private boolean firstMultiSelect = true;
/**
* Selection list when multiple categories need to be selected (e.g. which
* categories belong to the same group)
*
* @param itemId
* @return
*/
public Field getCategoriesMultiSelectFor(Object itemId) {
ListSelect list = null;
if (itemId != null) {
list = groupIdToCategoryList.get(itemId);
}
if (list == null) {
list = new ListSelect();
setupCategorySelection(list, activeCategories, firstMultiSelect);
if (firstMultiSelect) {
firstMultiSelect = false;
}
list.setMultiSelect(true);
list.setRows(4);
groupIdToCategoryList.put(itemId, list);
}
return list;
}
/**
* Selection when only one category is relevant (e.g. when entering
* registration category for a lifter)
*
* @param itemId
* @param prop
* @return
*/
@SuppressWarnings("serial")
public Component getCategoriesPopUpFor(Object itemId, final Property prop) {
ListSelect categoryListSelect = null;
if (itemId == null) {
categoryListSelect = lifterIdToCategorySelect.get(itemId);
}
if (categoryListSelect == null) {
categoryListSelect = new ListSelect();
setupCategorySelection(categoryListSelect, activeCategories, firstCategoryComboBox);
if (firstCategoryComboBox) {
firstCategoryComboBox = false;
}
//categoryListSelect.setRequiredError(Messages.getString("CommonFieldFactory.youMustListSelectACategory", app.getLocale())); //$NON-NLS-1$
categoryListSelect.setMultiSelect(true);
categoryListSelect.setNullSelectionAllowed(true);
categoryListSelect.setRows(activeCategories.size() + nbRowsForNullValue(categoryListSelect));
lifterIdToCategorySelect.put(itemId, categoryListSelect);
}
categoryListSelect.setPropertyDataSource(prop);
categoryListSelect.setWriteThrough(true);
categoryListSelect.setImmediate(true);
// categoryListSelect.addListener(new ValueChangeListener() {
// @Override
// public void valueChange(ValueChangeEvent event) {
// //System.err.println("getCategoriesPopUpFor selected: "+event.getProperty().toString());
// if (event.getProperty() == null){prop.setValue(null);}
// }
// });
final ListSelect selector = categoryListSelect;
PopupView popup = new PopupView(new PopupView.Content() {
@SuppressWarnings("unchecked")
@Override
public String getMinimizedValueAsHTML() {
final Object value = prop.getValue();
if (value instanceof Long) {
return categoryItemDisplayString((Long) value);
} else {
return categorySetToString((Set<Long>) value);
}
}
@Override
public Component getPopupComponent() {
return selector;
}
});
popup.setHideOnMouseOut(true);
return popup;
}
/**
* Set-up shared behaviour for category combo boxes and multi-selects.
*
* @param categorySelect
* @param categories
* @param first
*/
private void setupCategorySelection(AbstractSelect categorySelect, CategoryContainer categories, boolean first) {
if (first) {
first = false;
}
categorySelect.setWriteThrough(true);
categorySelect.setImmediate(true);
categorySelect.setContainerDataSource(categories);
categorySelect.setItemCaptionPropertyId("name"); //$NON-NLS-1$
categorySelect.setNullSelectionAllowed(true);
categorySelect.setNewItemsAllowed(false);
}
/**
* @param table
* @param item
* @param propertyId
* @param itemId
* @return
*/
private Component dynamicCategoryLabel(Table table, final Item item, Object itemId, Object propertyId) {
final Lifter lifter = getLifter(item);
// default label.
final Category category = lifter.getCategory();
final String unknown = Messages.getString("Common.unknown", app.getLocale()); //$NON-NLS-1$
final Label categoryLabel = new Label(unknown);//$NON-NLS-1$
if (category != null) {
final String name = category.getName();
categoryLabel.setValue(name);
Category regCat = lifter.getRegistrationCategory();
if (!(category.equals(regCat))) {
categoryLabel.addStyleName("wrong"); //$NON-NLS-1$
}
}
// because we don't want to understand the dependencies between the
// various properties
// of a lifter, we let the lifter tell us when it thinks that a
// dependent property has
// changed (in this case, the category depends on body weight and
// gender).
final Lifter.UpdateEventListener listener = new Lifter.UpdateEventListener() {
@Override
public void updateEvent(Lifter.UpdateEvent updateEvent) {
Lifter lifter1 = (Lifter) updateEvent.getSource();
logger.debug("received event for "+lifter1+" update of "+updateEvent.getPropertyIds());
final Category category2 = lifter1.getCategory();
synchronized (app) {
categoryLabel.removeStyleName("wrong"); //$NON-NLS-1$
if (category2 == null) {
categoryLabel.setValue(unknown);
categoryLabel.addStyleName("wrong"); //$NON-NLS-1$
} else {
categoryLabel.setValue(category2.getName());
Category regCat = lifter1.getRegistrationCategory();
if (!(category2.equals(regCat))) {
// System.err.println("setting flag on category for "+lifter.getLastName()
// +" "+System.identityHashCode(this)
// +" update of "+updateEvent.getPropertyIds());
categoryLabel.addStyleName("wrong"); //$NON-NLS-1$
}
}
}
app.push();
}
};
if (categoryLabel.getData() == null) {
lifter.addListener(listener);
categoryLabel.setData(listener);
}
// done
return categoryLabel;
}
/**
* @param table
* @param item
* @param propertyId
* @param itemId
* @return
*/
private Component categoryLabel(Table table, final Item item, Object itemId, Object propertyId) {
final Lifter lifter = getLifter(item);
// default label.
final Category category = lifter.getCategory();
final String unknown = Messages.getString("Common.unknown", app.getLocale()); //$NON-NLS-1$
final Label categoryLabel = new Label(unknown);//$NON-NLS-1$
// if (!table.isEditable()) {
if (category != null) {
final String name = category.getName();
categoryLabel.setValue(name);
}
// }
return categoryLabel;
}
/**
* Return the lifter hidden behind the item.
*
* @param item
* @return a Lifter
*/
private Lifter getLifter(final Item item) {
return (Lifter) ItemAdapter.getObject(item);
}
public String categorySetToString(Set<Long> categoryIds) {
if (categoryIds == null) return Messages.getString("Common.emptyList", app.getLocale()); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
final String separator = Messages.getString("CommonFieldFactory.listSeparator", app.getLocale()); //$NON-NLS-1$
for (Long curCategoryId : categoryIds) {
// Item s = (categories.getItem(curCategoryId));
Category curCategory = (Category) ItemAdapter.getObject(activeCategories.getItem(curCategoryId));
sb.append(curCategory.getName());
sb.append(separator); //$NON-NLS-1$
}
if (sb.length() == 0) {
return Messages.getString("Common.emptyList", app.getLocale()); //$NON-NLS-1$
} else {
return sb.substring(0, sb.length() - separator.length()); // hide
// last
// comma
}
}
private Field adjustDateField(DateField f) {
f.setDateFormat("yyyy-MM-dd HH:mm"); //$NON-NLS-1$
f.setResolution(DateField.RESOLUTION_MIN);
return f;
}
private HashMap<Object, Component> groupIdToPlatformSelect = new HashMap<Object, Component>();
public Field getPlatformComboboxFor(Object platformId) {
ComboBox cb = null;
if (platformId != null) {
cb = (ComboBox) groupIdToPlatformSelect.get(platformId);
}
if (cb == null) {
final ComboBox cb2 = new ComboBox();
cb2.setContainerDataSource(platforms);
cb2.setItemCaptionPropertyId("name"); //$NON-NLS-1$
cb2.setNewItemsAllowed(true);
cb = cb2;
}
return cb;
}
/**
* Selection when only one platform is relevant (e.g. when entering
* registration platform for a lifter)
*
* @param itemId
* @param prop
* @return
*/
@SuppressWarnings("serial")
public Component getPlatformPopUpFor(Object itemId, final Property prop) {
ListSelect platformSelect = null;
if (itemId == null) {
platformSelect = (ListSelect) groupIdToPlatformSelect.get(itemId);
}
if (platformSelect == null) {
platformSelect = new ListSelect();
platformSelect.setContainerDataSource(platforms);
platformSelect.setItemCaptionPropertyId("name"); //$NON-NLS-1$
platformSelect.setNewItemsAllowed(false);
platformSelect.setNullSelectionAllowed(true);
platformSelect.setMultiSelect(false);
platformSelect.setRows(platforms.size() + 1);
if (firstCategoryComboBox) {
firstCategoryComboBox = false;
}
platformSelect.setRequiredError(Messages.getString(
"CommonFieldFactory.youMustSelectAPlatform", app.getLocale())); //$NON-NLS-1$
platformSelect.setRows(platforms.size() + nbRowsForNullValue(platformSelect));
groupIdToPlatformSelect.put(itemId, platformSelect);
}
platformSelect.setPropertyDataSource(prop);
platformSelect.setWriteThrough(true);
platformSelect.setImmediate(true);
final ListSelect selector = platformSelect;
PopupView popup = new PopupView(new PopupView.Content() {
@Override
public String getMinimizedValueAsHTML() {
return platformItemDisplayString(prop.getValue());
}
@Override
public Component getPopupComponent() {
return selector;
}
});
popup.setHideOnMouseOut(true);
return popup;
}
/**
* @param value
* @return
*/
protected String platformItemDisplayString(Object value) {
Platform curPlatform = null;
if (value != null) {
if (value instanceof Platform) {
curPlatform = (Platform) value;
} else {
curPlatform = (Platform) ItemAdapter.getObject(platforms.getItem(value));
}
}
return (curPlatform != null ? curPlatform.getName() : Messages
.getString("Common.noneSelected", app.getLocale())); //$NON-NLS-1$
}
private Map<Object, ListSelect> lifterIdToCategorySelect = new HashMap<Object, ListSelect>();
private boolean firstCategoryComboBox = true;
/**
* Selection when only one category is relevant (e.g. when entering
* registration category for a lifter)
*
* @param itemId
* @return
*/
public Field getCategoryComboboxFor(Object itemId) {
ListSelect categorySelect = null;
if (itemId == null) {
categorySelect = lifterIdToCategorySelect.get(itemId);
}
if (categorySelect == null) {
categorySelect = new ListSelect();
setupCategorySelection(categorySelect, activeCategories, firstCategoryComboBox);
if (firstCategoryComboBox) {
firstCategoryComboBox = false;
}
categorySelect.setRequiredError(Messages.getString(
"CommonFieldFactory.youMustSelectACategory", app.getLocale())); //$NON-NLS-1$
categorySelect.setWriteThrough(true);
categorySelect.setImmediate(true);
lifterIdToCategorySelect.put(itemId, categorySelect);
}
return categorySelect;
}
/**
* Selection when only one category is relevant (e.g. when entering
* registration category for a lifter)
*
* @param itemId
* @param prop
* @return
*/
@SuppressWarnings("serial")
public Component getCategoryPopUpFor(Object itemId, final Property prop) {
ListSelect categorySelect = null;
if (itemId == null) {
categorySelect = lifterIdToCategorySelect.get(itemId);
}
if (categorySelect == null) {
categorySelect = new ListSelect();
setupCategorySelection(categorySelect, activeCategories, firstCategoryComboBox);
if (firstCategoryComboBox) {
firstCategoryComboBox = false;
}
categorySelect.setRequiredError(Messages.getString(
"CommonFieldFactory.youMustSelectACategory", app.getLocale())); //$NON-NLS-1$
categorySelect.setRows(activeCategories.size() + nbRowsForNullValue(categorySelect));
lifterIdToCategorySelect.put(itemId, categorySelect);
}
categorySelect.setPropertyDataSource(prop);
categorySelect.setWriteThrough(true);
categorySelect.setImmediate(true);
categorySelect.setNullSelectionAllowed(true);
final ListSelect selector = categorySelect;
PopupView popup = new PopupView(new PopupView.Content() {
@Override
public String getMinimizedValueAsHTML() {
return categoryItemDisplayString(prop.getValue());
}
@Override
public Component getPopupComponent() {
return selector;
}
});
popup.setHideOnMouseOut(true);
return popup;
}
/**
* @param categorySelect
* @return
*/
private int nbRowsForNullValue(ListSelect categorySelect) {
return (categorySelect.isNullSelectionAllowed() && !categorySelect.isMultiSelect() ? 1 : 0);
}
private HashMap<Object, ListSelect> lifterIdToGroupSelect = new HashMap<Object, ListSelect>();
private boolean firstGroupComboBox = true;
/**
* Selection when only one category is relevant (e.g. when entering
* registration category for a lifter)
*
* @param itemId
* @return
*/
public Field getGroupComboboxFor(Object itemId) {
ListSelect groupSelect = null;
if (itemId == null) {
groupSelect = lifterIdToGroupSelect.get(itemId);
}
if (groupSelect == null) {
groupSelect = new ListSelect();
setupGroupSelection(groupSelect, competitionSessions, firstGroupComboBox);
if (firstGroupComboBox) {
firstGroupComboBox = false;
}
groupSelect.setRequiredError(Messages.getString("CommonFieldFactory.youMustSelectAGroup", app.getLocale())); //$NON-NLS-1$
lifterIdToCategorySelect.put(itemId, groupSelect);
}
return groupSelect;
}
/**
* Selection when only one category is relevant (e.g. when entering
* registration category for a lifter)
*
* @param itemId
* @param prop
* @return
*/
@SuppressWarnings("serial")
public Component getGroupPopUpFor(Object itemId, final Property prop) {
ListSelect groupSelect = null;
if (itemId == null) {
groupSelect = lifterIdToGroupSelect.get(itemId);
}
if (groupSelect == null) {
groupSelect = new ListSelect();
setupGroupSelection(groupSelect, competitionSessions, firstGroupComboBox);
if (firstGroupComboBox) {
firstGroupComboBox = false;
}
groupSelect.setRequiredError(Messages.getString("CommonFieldFactory.youMustSelectAGroup", app.getLocale())); //$NON-NLS-1$
groupSelect.setRows(competitionSessions.size() + nbRowsForNullValue(groupSelect));
lifterIdToCategorySelect.put(itemId, groupSelect);
}
groupSelect.setPropertyDataSource(prop);
final ListSelect selector = groupSelect;
groupSelect.setWriteThrough(true);
groupSelect.setImmediate(true);
groupSelect.setNullSelectionAllowed(true);
final PopupView popup = new PopupView(new PopupView.Content() {
@Override
public String getMinimizedValueAsHTML() {
return groupItemDisplayString(prop.getValue());
}
@Override
public Component getPopupComponent() {
return selector;
}
});
return popup;
}
/**
* Set-up shared behaviour for category combo boxes and multi-selects.
*
* @param groupSelect
* @param competitionSessions
* @param first
*/
private void setupGroupSelection(AbstractSelect groupSelect, HbnContainer<CompetitionSession> competitionSessions, boolean first) {
if (first) {
// groups.addContainerFilter("active", "true", true, false); //$NON-NLS-1$ //$NON-NLS-2$
// groups.setFilteredGetItemIds(true);
first = false;
}
groupSelect.setWriteThrough(true);
groupSelect.setImmediate(true);
groupSelect.setContainerDataSource(competitionSessions);
groupSelect.setItemCaptionPropertyId("name"); //$NON-NLS-1$
groupSelect.setNullSelectionAllowed(true);
groupSelect.setNewItemsAllowed(false);
groupSelect.setWidth("8ex"); //$NON-NLS-1$
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import org.concordiainternational.competition.data.CompetitionSession;
import com.vaadin.terminal.StreamResource;
/**
* This interface defines the actions that are managed by the application
* controller. In principle, all actions that affect more than a single
* application pane should be registered here
*
* @author jflamy
*
*/
public interface UserActions {
public abstract void setPlatformByName(String plaftorm);
public abstract void setCurrentCompetitionSession(CompetitionSession value);
/**
* @param streamSource
* @param filename
*/
public abstract void openSpreadsheet(StreamResource.StreamSource streamSource,
final String filename);
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.decision.Decision;
import org.concordiainternational.competition.decision.IDecisionController;
import org.concordiainternational.competition.decision.JuryDecisionController;
import org.concordiainternational.competition.decision.RefereeDecisionController;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.nec.NECDisplay;
import org.concordiainternational.competition.publicAddress.PublicAddressCountdownTimer;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent.MessageDisplayListener;
import org.concordiainternational.competition.publicAddress.PublicAddressTimerEvent;
import org.concordiainternational.competition.publicAddress.PublicAddressTimerEvent.MessageTimerListener;
import org.concordiainternational.competition.timer.CountdownTimer;
import org.concordiainternational.competition.ui.PlatesInfoEvent.PlatesInfoListener;
import org.concordiainternational.competition.ui.components.DecisionLightsWindow;
import org.concordiainternational.competition.utils.EventHelper;
import org.concordiainternational.competition.utils.IdentitySet;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.concordiainternational.competition.utils.NotificationManager;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import com.github.wolfie.blackboard.Blackboard;
import com.github.wolfie.blackboard.Event;
import com.github.wolfie.blackboard.Listener;
import com.vaadin.data.Item;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
import com.vaadin.event.EventRouter;
import com.vaadin.ui.Component;
/**
* Data about a competition group.
* <p>
* Manages the lifting order, keeps tabs of which lifters have been called, who
* is entitled to two minutes, etc. Also holds the master timer for the group.
* </p>
*
* @author jflamy
*/
public class SessionData implements Lifter.UpdateEventListener, Serializable {
private static final long serialVersionUID = -7621561459948739065L;
private static XLogger logger = XLoggerFactory.getXLogger(SessionData.class);
static final Logger timingLogger = LoggerFactory.getLogger("org.concordiainternational.competition.timer.TimingLogger"); //$NON-NLS-1$
public static final String MASTER_KEY = "GroupData_"; //$NON-NLS-1$
public List<Lifter> lifters;
/**
* list of currently displayed lifters that, if updated, will notify us. We
* use an IdentitySet because the same lifter can appear in two windows, as
* two occurrences that are != but equals.
*/
public Set<Object> notifiers = (new IdentitySet(5));
private List<Lifter> liftTimeOrder;
private List<Lifter> displayOrder;
private List<Lifter> resultOrder;
private CompetitionApplication app;
private CompetitionSession currentSession;
private Lifter currentLifter;
public boolean needToUpdateNEC;
private List<Lifter> currentDisplayOrder;
private List<Lifter> currentLiftingOrder;
private NotificationManager<SessionData, Lifter, Component> notificationManager;
private int timeAllowed;
private int liftsDone;
private RefereeDecisionController refereeDecisionController = null;
private JuryDecisionController juryDecisionController = null;
boolean allowAll = false; // allow null group to mean all lifters.
// will be set to true if the Timekeeping button is pressed.
private boolean timeKeepingInUse = Competition.isMasters();
private Lifter priorLifter;
private Integer priorRequest;
private Integer priorRequestNum;
private boolean needToAnnounce = true;
Blackboard blackBoardEventRouter = new Blackboard();
public int getLiftsDone() {
return liftsDone;
}
private SessionData(String platformName) {
app = CompetitionApplication.getCurrent();
lifters = new ArrayList<Lifter>();
platform = Platform.getByName(platformName);
notificationManager = new NotificationManager<SessionData, Lifter, Component>(this);
refereeDecisionController = new RefereeDecisionController(this);
juryDecisionController = new JuryDecisionController(this);
init();
}
/**
* This constructor is only meant for unit tests.
*
* @param lifters
*/
public SessionData(List<Lifter> lifters) {
app = CompetitionApplication.getCurrent();
this.lifters = lifters;
notificationManager = new NotificationManager<SessionData, Lifter, Component>(this);
refereeDecisionController = new RefereeDecisionController(this);
juryDecisionController = new JuryDecisionController(this);
updateListsForLiftingOrderChange();
init();
}
static private final Map<String, SessionData> platformToSessionData = new HashMap<String, SessionData>();
public static SessionData getSingletonForPlatform(String platformName) {
SessionData groupDataSingleton = platformToSessionData.get(platformName);
if (groupDataSingleton == null) {
groupDataSingleton = new SessionData(platformName);
platformToSessionData.put(platformName, groupDataSingleton);
groupDataSingleton.registerAsMasterData(platformName);
}
logger.debug("groupData = {}", groupDataSingleton); //$NON-NLS-1$
return groupDataSingleton;
}
/**
* @return information about a session, not connected to a platform.
*/
public static SessionData getIndependentInstance() {
SessionData independentData = new SessionData("");
logger.debug("independentData = {}", independentData); //$NON-NLS-1$
return independentData;
}
/**
* @return
*/
private void init() {
blackBoardEventRouter.register(MessageDisplayListener.class, PublicAddressMessageEvent.class);
blackBoardEventRouter.register(MessageTimerListener.class, PublicAddressTimerEvent.class);
blackBoardEventRouter.register(PlatesInfoListener.class, PlatesInfoEvent.class);
}
/**
* This method reloads the underlying data. Beware that only "master" views
* are meant to do this, such as AnnouncerView when mode = ANNOUNCER, or the
* results view to edit results after a group is over.
*
* "slave" views such as the MARSHAL, TIMEKEEPER views should never call this method.
*/
void loadData() {
currentSession = this.getCurrentSession();
if (currentSession == null && !allowAll) {
// make it so we have to select a group
lifters = new ArrayList<Lifter>();
logger.debug("current group is empty"); //$NON-NLS-1$
} else {
logger.debug("loading data for group {}", currentSession); //$NON-NLS-1$
final LifterContainer hbnCont = new LifterContainer(app);
// hbnCont will filter automatically to application.getCurrentGroup
lifters = hbnCont.getAllPojos();
}
}
/**
* @return the lifter who lifted most recently
*/
public Lifter getPreviousLifter() {
if (getLiftTimeOrder() == null) {
setLiftTimeOrder(LifterSorter.LiftTimeOrderCopy(lifters));
}
if (getLiftTimeOrder().size() == 0) return null;
// if (logger.isDebugEnabled())
// System.err.println(AllTests.longDump(liftTimeOrder));
Lifter lifter = getLiftTimeOrder().get(0);
if (lifter.getLastLiftTime() == null) return null;
return lifter;
// // we want the most recent, who will be at the end.
// // skip people who have not lifted.
// Lifter lifter = null;
// for (int index = lifters.size()-1; index >= 0; index--) {
// lifter = liftTimeOrder.get(index);
// if (lifter.getLastLiftTime() != null) break;
// }
// return lifter;
}
/**
* Saves changes made to object to Hibernate Session. Note that run is most
* likely detached due session-per-request patterns so we'll use merge.
* Actual database update will happen by Vaadin's transaction listener in
* the end of request.
*
* If one wanted to make sure that this operation will be successful a
* (Hibernate) transaction commit and error checking ought to be done.
*
* @param object
*/
public void persistPojo(Object object) {
try {
((HbnSessionManager) app).getHbnSession().merge(object);
} catch (StaleObjectStateException e) {
throw new RuntimeException(Messages.getString("SessionData.UserHasBeenDeleted", CompetitionApplication
.getCurrentLocale()));
}
}
/**
* Sort the various lists to reflect new lifting order.
*/
public void updateListsForLiftingOrderChange() {
logger.debug("updateListsForLiftingOrderChange"); //$NON-NLS-1$
sortLists();
publishLists();
notifyListeners();
}
/**
*
*/
private void sortLists() {
logger.debug("sortLists"); //$NON-NLS-1$
displayOrder = LifterSorter.displayOrderCopy(lifters);
setLiftTimeOrder(LifterSorter.LiftTimeOrderCopy(lifters));
setResultOrder(LifterSorter.resultsOrderCopy(lifters, Ranking.TOTAL));
LifterSorter.assignMedals(getResultOrder());
this.liftsDone = LifterSorter.countLiftsDone(lifters);
LifterSorter.liftingOrder(lifters);
this.needToUpdateNEC = false;
currentLifter = LifterSorter.markCurrentLifter(lifters);
Integer currentRequest = (currentLifter != null ? currentLifter.getNextAttemptRequestedWeight() : null);
Integer currentRequestNum = (currentLifter != null ? currentLifter.getAttemptsDone() : null);
logger
.debug("new/old {}/{} {}/{} {}/{}", //$NON-NLS-1$
new Object[] { currentLifter, priorLifter, currentRequest, priorRequest, currentRequestNum,
priorRequestNum });
setNeedToAnnounce(currentLifter != priorLifter || priorRequest != currentRequest
|| priorRequestNum != currentRequestNum);
if (getNeedToAnnounce()) {
// stop the timer if it was running, as if the "Change Weight"
// button had been used
final CountdownTimer timer2 = getTimer();
if (timer2 != null && timer2.isRunning()) {
if (currentLifter == priorLifter) {
timer2.pause(TimeStoppedNotificationReason.CURRENT_LIFTER_CHANGE);
} else {
timer2.pause();
}
} // stop time something is happening.
setTimeAllowed(timeAllowed(currentLifter));
needToUpdateNEC = true;
logger.debug(
"paused time, needToUpdateNec = true, timeAllowed={}, timeRemaining={}", timeAllowed, timer2.getTimeRemaining()); //$NON-NLS-1$
} else {
needToUpdateNEC = false;
logger.debug("needToUpdateNEC = false"); //$NON-NLS-1$
}
if (currentLifter != null) {
// copy values from current lifter.
priorLifter = currentLifter;
priorRequest = (currentLifter != null ? currentLifter.getNextAttemptRequestedWeight() : null);
priorRequestNum = (currentLifter != null ? currentLifter.getAttemptsDone() : null);
} else {
priorLifter = null;
priorRequest = null;
priorRequestNum = null;
}
}
/**
* Notify the listeners that the lifting order has changed.
*/
void notifyListeners() {
// notify listeners to pick up the new information.
final Lifter firstLifter = lifters.size() > 0 ? lifters.get(0) : null;
logger.debug("notifyListeners() firing event, first lifter={}", firstLifter); //$NON-NLS-1$
fireEvent(new UpdateEvent(this, firstLifter));
}
/**
* Make the lists visible to all (including JSPs)
*/
void publishLists() {
// make results available to all (including JSPs)
final CompetitionApplication competitionApplication = (CompetitionApplication) app;
final String platformName = app.getPlatformName();
final CompetitionSession currentGroup = competitionApplication.getCurrentCompetitionSession();
String name = (currentGroup != null ? (String) currentGroup.getName() : null);
ServletContext sCtx = competitionApplication.getServletContext();
if (sCtx != null) {
logger.debug("current group for platformName " + platformName + " = " + name); //$NON-NLS-1$ //$NON-NLS-2$
currentLiftingOrder = getAttemptOrder();
currentDisplayOrder = getDisplayOrder();
sCtx.setAttribute("groupData_" + platformName, this); //$NON-NLS-1$
}
}
public List<Lifter> getLifters() {
return lifters;
}
/**
* @return lifters in standard display order
*/
public List<Lifter> getDisplayOrder() {
return displayOrder;
}
/**
* @return lifters in lifting order
*/
public List<Lifter> getAttemptOrder() {
return lifters;
}
/**
* Check if lifter is following himself, and that no other lifter has been
* announced since (if time starts running for another lifter, then the two
* minute privilege is lost).
*
* @param lifter
*
*/
public int timeAllowed(Lifter lifter) {
final Set<Lifter> calledLifters = getStartedLifters();
logger.trace("timeAllowed start"); //$NON-NLS-1$
// if clock was running for the current lifter, return the remaining
// time.
if (getTimer().getOwner() == lifter) {
logger.trace("timeAllowed current lifter {} was running.", lifter); //$NON-NLS-1$
int timeRemaining = getTimer().getTimeRemaining();
if (timeRemaining < 0) timeRemaining = 0;
// if the decision was not entered, and timer has run to 0, we still
// want to see 0
// if (timeRemaining > 0
// //&& timeRemaining != 60000 && timeRemaining != 120000
// ) {
logger.info("resuming time for lifter {}: {} ms remaining", lifter, timeRemaining); //$NON-NLS-1$
return timeRemaining;
// }
}
logger.trace("not current lifter"); //$NON-NLS-1$
final Lifter previousLifter = getPreviousLifter();
if (previousLifter == null) {
logger.trace("A twoMinutes (not): previousLifter null: calledLifters={} lifter={}", //$NON-NLS-1$
new Object[] { calledLifters, lifter });
return 60000;
} else if (lifter.getAttemptsDone() % 3 == 0) {
// no 2 minutes if starting snatch or starting c-jerk
logger.trace("B twoMinutes (not): first attempt lifter={}", lifter); //$NON-NLS-1$
return 60000;
} else if (calledLifters == null || calledLifters.isEmpty()) {
if (lifter.equals(previousLifter)) {
logger.trace("C twoMinutes : calledLifters={} lifter={} previousLifter={}", //$NON-NLS-1$
new Object[] { calledLifters, lifter, previousLifter });
// setTimerForTwoMinutes(lifter);
return 120000;
} else {
logger.trace("D twoMinutes (not): calledLifters={} lifter={} previousLifter={}", //$NON-NLS-1$
new Object[] { calledLifters, lifter, previousLifter });
return 60000;
}
//} else if (lifter.equals(previousLifter) && (calledLifters.size() == 1 && calledLifters.contains(lifter))) {
} else if (lifter.equals(previousLifter) && (!calledLifters.contains(lifter))) {
// we are the previous lifter, and but were not called.
// we do not lose the two minute privilege
logger.trace("E twoMinutes: calledLifters={} lifter={} previousLifter={}", //$NON-NLS-1$
new Object[] { calledLifters, lifter, previousLifter });
// setTimerForTwoMinutes(lifter);
return 120000;
} else {
logger.trace("F twoMinutes (not) : calledLifters={} lifter={} previousLifter={}", //$NON-NLS-1$
new Object[] { calledLifters, lifter, previousLifter });
return 60000;
}
}
/**
* @param lifter
*/
@SuppressWarnings("unused")
private void setTimerForTwoMinutes(Lifter lifter) {
logger.info("setting timer owner to {}", lifter);
getTimer().stop();
getTimer().setOwner(lifter); // so time is kept for this lifter after
// switcheroo
getTimer().setTimeRemaining(120000);
}
// Set<LifterCall> startedLifterCalls = new HashSet<LifterCall>();
Set<Lifter> startedLifters = new HashSet<Lifter>();
private boolean forcedByTimekeeper = false;
// public class LifterCall {
// public Date callTime;
// public Lifter lifter;
//
// LifterCall(Date callTime, Lifter lifter) {
// this.callTime = callTime;
// this.lifter = lifter;
// }
//
// @Override
// public String toString() {
// return lifter.toString() + "_" + callTime.toString(); //$NON-NLS-1$
// }
// }
public void callLifter(Lifter lifter) {
// beware: must call timeAllowed *before* setLifterAnnounced.
// check if the timekeeper has forced the timer setting for the next
// announce
// if so leave it alone.
final int timeRemaining = getTimer().getTimeRemaining();
if (isForcedByTimekeeper() && (timeRemaining == 120000 || timeRemaining == 60000)) {
setForcedByTimekeeper(true, timeRemaining);
logger.info("call of lifter {} : {}ms FORCED BY TIMEKEEPER", lifter, timeRemaining); //$NON-NLS-1$
} else {
if (!getTimeKeepingInUse()) {
int allowed = getTimeAllowed();
getTimer().setTimeRemaining(allowed);
logger.info("call of lifter {} : {}ms allowed", lifter, allowed); //$NON-NLS-1$
} else {
logger.info("call of lifter {} : {}ms remaining", lifter, timeRemaining); //$NON-NLS-1$
}
setForcedByTimeKeeper(false);
}
displayLifterInfo(lifter);
refereeDecisionController.reset();
juryDecisionController.reset();
if (startTimeAutomatically) {
startTimer(lifter,this,getTimer());
} else if (!getTimeKeepingInUse()) {
setLifterAsHavingStarted(lifter);
logger.info("timekeeping NOT in use, setting lifter {} as owner", lifter);
getTimer().setOwner(lifter);
}
}
/**
* @param lifter
*/
public void setLifterAsHavingStarted(Lifter lifter) {
// startedLifterCalls.add(new LifterCall(new Date(), lifter));
startedLifters.add(lifter);
}
/**
* @param b
*/
private void setForcedByTimeKeeper(boolean b) {
this.forcedByTimekeeper = b;
}
/**
* @param lifter
*/
public void displayLifterInfo(Lifter lifter) {
if (lifter.getAttemptsDone() >= 6) {
displayNothing();
} else {
if (getNECDisplay() != null) getNECDisplay().writeLifterInfo(lifter, false, getPlatform());
}
}
public void displayWeight(Lifter lifter) {
LoggerUtils.logException(logger, new Exception("whocalls")); //$NON-NLS-1$
if (lifter.getAttemptsDone() >= 6) {
displayNothing();
} else {
if (getNECDisplay() != null) getNECDisplay().writeLifterInfo(lifter, true, getPlatform());
}
}
/**
* Clear the LED display
*/
private void displayNothing() {
if (getNECDisplay() != null) try {
getNECDisplay().writeStrings("", "", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} catch (Exception e) {
// nothing to do
}
}
public List<Lifter> getLiftTimeOrder() {
return liftTimeOrder;
}
public void liftDone(Lifter lifter, boolean success) {
logger.debug("lift done: notifiers={}", notifiers); //$NON-NLS-1$
// startedLifterCalls.clear();
startedLifters.clear();
final CountdownTimer timer2 = getTimer();
timer2.setOwner(null);
timer2.stop(); // in case timekeeper has failed to stop it.
timer2.setTimeRemaining(0);
}
// public Set<LifterCall> getStartedLifterCalls() {
// return startedLifterCalls;
// }
public Set<Lifter> getStartedLifters() {
return startedLifters;
}
CountdownTimer timer;
public CountdownTimer getTimer() {
if (timer == null) {
timer = new CountdownTimer();
};
return timer;
}
/**
* @param forcedByTimekeeper
* the forcedByTimekeeper to set
* @param timeRemaining
*/
public void setForcedByTimekeeper(boolean forcedByTimekeeper, int timeRemaining) {
getTimer().forceTimeRemaining(timeRemaining);
setForcedByTimeKeeper(forcedByTimekeeper);
}
/**
* @return the forcedByTimekeeper
*/
public boolean isForcedByTimekeeper() {
return forcedByTimekeeper;
}
public void setStartTimeAutomatically(boolean b) {
// if we start time automatically, announcing a lifter is the same as starting
// the clock
startTimeAutomatically = b;
}
/**
* Remember which view is the current announcer view.
*
* @param announcerView
*/
public void setAnnouncerView(AnnouncerView announcerView) {
this.announcerView = announcerView;
}
public AnnouncerView getAnnouncerView() {
return announcerView;
}
/**
* @return the currentDisplayOrder
*/
public List<Lifter> getCurrentDisplayOrder() {
return currentDisplayOrder;
}
/**
* @return the currentLiftingOrder
*/
public List<Lifter> getCurrentLiftingOrder() {
return currentLiftingOrder;
}
public NECDisplay getNECDisplay() {
if (getPlatform() != null) {
return getPlatform().getNECDisplay();
} else {
return null;
}
}
/* *********************************************************************************
* Interactions with the context.
*/
/**
* Change the underlying session.
* Change the underlying session. When sessionData object has many browsers listening
* to it, it is simpler to change the session than to recreate a new SessionData object.
* This method should only be used by AnnouncerView, when the announcer.
*
* @param newCurrentSession the currentSession to set
*/
void setCurrentSession(CompetitionSession newCurrentSession) {
logger.info("{} setting group to {}", this, newCurrentSession); //$NON-NLS-1$
// do this first, in case we get called us recursively
this.currentSession = newCurrentSession;
if (app.getCurrentCompetitionSession() != newCurrentSession) {
// synchronize with the application (if we were not called from there)
app.setCurrentCompetitionSession(newCurrentSession);
}
loadData();
sortLists();
publishLists();
setTimeKeepingInUse(false); // will switch to true if Start/stop is used.
// tell listeners to refresh.
fireEvent(new UpdateEvent(this, true));
}
/**
* @return the currentSession
*/
public CompetitionSession getCurrentSession() {
if (currentSession != null) {
final String name = currentSession.getName();
MDC.put("currentGroup", ">"+name);
}
return currentSession;
}
public void setMasterApplication(CompetitionApplication app2) {
logger.debug("setting as master application {}", app2);
this.masterApplication = app2;
}
public CompetitionApplication getMasterApplication() {
return masterApplication;
}
public Platform getPlatform() {
return platform;
}
public void setPlatform(Platform platform) {
this.platform = platform;
}
/* *********************************************************************************
* UpdateEvent framework.
*/
private EventRouter eventRouter = new EventRouter();
private boolean startTimeAutomatically = false;
private AnnouncerView announcerView;
private CompetitionApplication masterApplication;
private boolean announcerEnabled = true;
public Item publicAddressItem;
private PublicAddressCountdownTimer publicAddressTimer = new PublicAddressCountdownTimer(this);
private Platform platform;
public boolean getAnnouncerEnabled() {
return announcerEnabled;
}
/**
* SessionData events all derive from this.
*/
public class UpdateEvent extends EventObject {
private static final long serialVersionUID = -126644150054472005L;
private Lifter currentLifter;
private boolean refreshRequest;
/**
* Constructs a new event with a specified source component.
*
* @param source
* the source component of the event.
* @param propertyIds
* that have been updated.
*/
public UpdateEvent(SessionData source, Lifter currentLifter) {
super(source);
this.currentLifter = currentLifter;
}
public UpdateEvent(SessionData source, boolean refreshRequest) {
super(source);
this.refreshRequest = refreshRequest;
}
public Lifter getCurrentLifter() {
return currentLifter;
}
public boolean getForceRefresh() {
return refreshRequest;
}
}
/**
* Listener interface for receiving <code>SessionData.UpdateEvent</code>s.
*/
public interface UpdateEventListener extends java.util.EventListener {
/**
* This method will be invoked when a SessionData.UpdateEvent is fired.
*
* @param updateEvent
* the event that has occured.
*/
public void updateEvent(SessionData.UpdateEvent updateEvent);
}
/**
* This method is the Java object for the method in the Listener interface.
* It allows the framework to know how to pass the event information.
*/
private static final Method LIFTER_EVENT_METHOD = EventHelper.findMethod(UpdateEvent.class, // when
// receiving
// this
// type
// of
// event
UpdateEventListener.class, // an object implementing this interface...
"updateEvent"); // ... will be called with this method. //$NON-NLS-1$;
/**
* Broadcast a SessionData.event to all registered listeners
*
* @param updateEvent
* contains the source (ourself) and the list of properties to be
* refreshed.
*/
protected void fireEvent(UpdateEvent updateEvent) {
// logger.trace("SessionData: firing event from groupData"+System.identityHashCode(this)+" first="+updateEvent.getCurrentLifter()+" eventRouter="+System.identityHashCode(eventRouter));
// logger.trace(" listeners"+eventRouter.dumpListeners(this));
if (eventRouter != null) {
eventRouter.fireEvent(updateEvent);
}
}
/**
* Register a new SessionData.Listener object with a SessionData in order to be
* informed of updates.
*
* @param listener
*/
public void addListener(UpdateEventListener listener) {
logger.debug("group data : add listener {}", listener); //$NON-NLS-1$
getEventRouter().addListener(UpdateEvent.class, listener, LIFTER_EVENT_METHOD);
}
/**
* Remove a specific SessionData.Listener object
*
* @param listener
*/
public void removeListener(UpdateEventListener listener) {
if (eventRouter != null) {
logger.debug("group data : hide listener {}", listener); //$NON-NLS-1$
eventRouter.removeListener(UpdateEvent.class, listener, LIFTER_EVENT_METHOD);
}
}
/*
* General event framework: we implement the
* com.vaadin.event.MethodEventSource interface which defines how a notifier
* can call a method on a listener to signal an event an event occurs, and
* how the listener can register/unregister itself.
*/
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#addListener(java.lang.Class,
* java.lang.Object, java.lang.reflect.Method)
*/
@SuppressWarnings("rawtypes")
public void addListener(Class eventType, Object object, Method method) {
getEventRouter().addListener(eventType, object, method);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#addListener(java.lang.Class,
* java.lang.Object, java.lang.String)
*/
@SuppressWarnings("rawtypes")
public void addListener(Class eventType, Object object, String methodName) {
getEventRouter().addListener(eventType, object, methodName);
}
/**
* @return the object's event router.
*/
private EventRouter getEventRouter() {
if (eventRouter == null) {
eventRouter = new EventRouter();
logger
.trace("new event router for groupData " + System.identityHashCode(this) + " = " + System.identityHashCode(eventRouter)); //$NON-NLS-1$ //$NON-NLS-2$
}
return eventRouter;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#removeListener(java.lang.Class,
* java.lang.Object)
*/
@SuppressWarnings("rawtypes")
public void removeListener(Class eventType, Object target) {
if (eventRouter != null) {
eventRouter.removeListener(eventType, target);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#removeListener(java.lang.Class,
* java.lang.Object, java.lang.reflect.Method)
*/
@SuppressWarnings("rawtypes")
public void removeListener(Class eventType, Object target, Method method) {
if (eventRouter != null) {
eventRouter.removeListener(eventType, target, method);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#removeListener(java.lang.Class,
* java.lang.Object, java.lang.String)
*/
@SuppressWarnings("rawtypes")
public void removeListener(Class eventType, Object target, String methodName) {
if (eventRouter != null) {
eventRouter.removeListener(eventType, target, methodName);
}
}
public void removeAllListeners() {
if (eventRouter != null) {
eventRouter.removeAllListeners();
}
}
/**
* Change who the lift list is listening to, unless the notifier being
* removed is the top in the list.
*
* @param lifter
* @param editor
* @param firstLifter
*/
public void stopListeningTo(final Lifter lifter, Component editor) {
if (lifter == null) return;
notificationManager.removeEditor(lifter, editor);
}
/**
* Change who the lift list is listening to.
*
* @param lifter
* @param editor
*/
public void listenToLifter(final Lifter lifter, Component editor) {
if (lifter == null) return;
notificationManager.addEditor(lifter, editor);
}
/**
* Makes this class visible to other sessions so they can call addListener .
*
* @param platformName
*/
void registerAsMasterData(String platformName) {
// make ourselves visible to other parts of the web application (e.g.
// JSP pages).
final ServletContext servletContext = ((CompetitionApplication) app).getServletContext();
if (servletContext != null) {
servletContext.setAttribute(SessionData.MASTER_KEY + platformName, this);
logger.info("Master data registered for platform {}={}", platformName, this); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Copied from interface. React to lifter changes by recomputing the lists.
*
* @see org.concordiainternational.competition.data.Lifter.UpdateEventListener#updateEvent(org.concordiainternational.competition.data.Lifter.UpdateEvent)
*/
@Override
public void updateEvent(Lifter.UpdateEvent updateEvent) {
logger.debug("lifter {}, changed {}", updateEvent.getSource(), updateEvent.getPropertyIds()); //$NON-NLS-1$
updateListsForLiftingOrderChange();
persistPojo(updateEvent.getSource());
}
public Lifter getCurrentLifter() {
return currentLifter;
}
/**
* @param liftTimeOrder
* the liftTimeOrder to set
*/
void setLiftTimeOrder(List<Lifter> liftTimeOrder) {
this.liftTimeOrder = liftTimeOrder;
}
/**
* @param resultOrder
* the resultOrder to set
*/
void setResultOrder(List<Lifter> resultOrder) {
this.resultOrder = resultOrder;
}
/**
* @return the resultOrder
*/
List<Lifter> getResultOrder() {
return resultOrder;
}
/**
* Register the fact that component comp is now editing newLifter instead of
* previousLifter
*
* @param newLifter
* @param previousLifter
* @param comp
*/
public void trackEditors(Lifter newLifter, Lifter previousLifter, Component comp) {
logger.debug("previousLifter = {}, lifter = {}", previousLifter, newLifter);; //$NON-NLS-1$
if (previousLifter != newLifter) {
// stopListeningTo actually waits until no editor is left to stop
// listening
stopListeningTo(previousLifter, comp);
}
if (newLifter != null) {
listenToLifter(newLifter, comp);
}
}
/**
* @param timeAllowed
* the timeAllowed to set
*/
private void setTimeAllowed(int timeAllowed) {
this.timeAllowed = timeAllowed;
}
/**
* @return the timeAllowed
*/
public int getTimeAllowed() {
return timeAllowed;
}
public int getTimeRemaining() {
if (timer != null) {
return timer.getTimeRemaining();
} else {
return timeAllowed;
}
}
public boolean getAllowAll() {
return allowAll;
}
public void setAllowAll(boolean allowAll) {
this.allowAll = allowAll;
}
public IDecisionController getRefereeDecisionController() {
return refereeDecisionController;
}
public IDecisionController getJuryDecisionController() {
return juryDecisionController;
}
public void majorityDecision(Decision[] refereeDecisions) {
final Lifter currentLifter2 = getCurrentLifter();
int pros = 0;
for (int i = 0; i < refereeDecisions.length; i++) {
if (refereeDecisions[i].accepted) pros++;
}
final boolean success = pros >= 2;
liftDone(currentLifter2, success);
if (success) {
logger.info("Referee decision: GOOD lift");
if (currentLifter2 != null) currentLifter2.successfulLift();
} else {
logger.info("Referee decision: NO lift");
if (currentLifter2 != null) currentLifter2.failedLift();
}
// record the decision.
if (currentLifter2 != null) {
saveLifter(currentLifter2);
} else {
logger.warn("current lifter is null");
}
}
/**
* @param currentLifter2
*/
private void saveLifter(final Lifter currentLifter2) {
Session session = app.getHbnSession();
session.merge(currentLifter2);
session.flush();
try {
session.getTransaction().commit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void downSignal() {
final CountdownDisplay countDownDisplay = (CountdownDisplay)getTimer().getCountdownDisplay();
if (countDownDisplay != null) {
DecisionLightsWindow dl = countDownDisplay.getDecisionLights();
if (dl != null) {
dl.doDown();
} else {
logger.error("decision lights is null");
}
}
timerStoppedByReferee();
}
/**
*
*/
synchronized private void timerStoppedByReferee() {
CountdownTimer timer2 = getTimer();
if (timer2.isRunning()) {
timer2.stop(TimeStoppedNotificationReason.REFEREE_DECISION);
}
}
public void setAnnouncerEnabled(boolean b) {
announcerEnabled = b;
}
/**
* @param timeKeepingInUse
* the timeKeepingInUse to set
*/
public void setTimeKeepingInUse(boolean timeKeepingInUse) {
this.timeKeepingInUse = timeKeepingInUse;
}
/**
* @return the timeKeepingInUse
*/
public boolean getTimeKeepingInUse() {
return timeKeepingInUse;
}
/**
* @param needToAnnounce
* the needToAnnounce to set
*/
public void setNeedToAnnounce(boolean needToAnnounce) {
this.needToAnnounce = needToAnnounce;
}
/**
* @return the needToAnnounce
*/
public boolean getNeedToAnnounce() {
return needToAnnounce;
}
/**
* @return
*/
public boolean getStartTimeAutomatically() {
return startTimeAutomatically;
}
/**
* @param lifter
* @param groupData
*/
public void manageTimerOwner(Lifter lifter, SessionData groupData, CountdownTimer timing) {
// first time we use the timekeeper button or that we announce
// with the automatic start determines that
// there is a timekeeper and that timekeeper runs clock.
groupData.setTimeKeepingInUse(true);
if (lifter != timing.getOwner()) {
if (!isForcedByTimekeeper()) {
final int remaining = groupData.getTimeAllowed();
timing.setTimeRemaining(remaining);
} else {
logger.info("forced by timekeeper: {} remaining",getTimeRemaining());
}
timing.setOwner(lifter); // enforce rule 6.5.15 -- lifter
// only gets 2 minutes if clock did
// not start for someone else
logger.debug("timekeeping in use, setting lifter {} as owner", lifter);
}
}
/**
* @param lifter
* @param groupData
*/
public void startTimer(Lifter lifter, SessionData groupData,CountdownTimer timing) {
manageTimerOwner(lifter,groupData, timing);
timing.restart();
setLifterAsHavingStarted(lifter);
}
public Item getPublicAddressItem() {
return publicAddressItem;
}
public void setPublicAddressItem(Item publicAddressItem) {
this.publicAddressItem = publicAddressItem;
}
public void clearPublicAddressDisplay() {
PublicAddressMessageEvent event = new PublicAddressMessageEvent();
// more intuitive if hiding the display does not stop the timer.
// publicAddressTimer.stop();
event.setHide(true);
fireBlackBoardEvent(event);
}
public void displayPublicAddress() {
PublicAddressCountdownTimer timer1 = (PublicAddressCountdownTimer) publicAddressItem.getItemProperty("remainingSeconds").getValue();
int remainingMilliseconds = timer1.getRemainingMilliseconds();
// tell the registered browsers to pop-up the message area
PublicAddressMessageEvent messageEvent = new PublicAddressMessageEvent();
messageEvent.setHide(false);
messageEvent.setTitle((String) publicAddressItem.getItemProperty("title").getValue());
messageEvent.setMessage((String) publicAddressItem.getItemProperty("message").getValue());
messageEvent.setRemainingMilliseconds(remainingMilliseconds);
fireBlackBoardEvent(messageEvent);
// tell the message areas to display the initial time
PublicAddressTimerEvent timerEvent = new PublicAddressTimerEvent();
timerEvent.setRemainingMilliseconds(remainingMilliseconds);
fireBlackBoardEvent(timerEvent);
}
/**
* @param event
*/
public void fireBlackBoardEvent(Event event) {
blackBoardEventRouter.fire(event);
}
public void addBlackBoardListener(Listener listener) {
blackBoardEventRouter.addListener(listener);
}
public void removeBlackBoardListener(Listener listener) {
blackBoardEventRouter.removeListener(listener);
}
public PublicAddressCountdownTimer getPublicAddressTimer() {
return publicAddressTimer;
}
void noCurrentLifter() {
// most likely completely obsolete.
//getTimer().removeAllListeners();
}
public void refresh(boolean isMaster) {
setCurrentSession(this.getCurrentSession());
if (isMaster) {
// get current platform back from database
// TODO: switch to JPA and use entity refresh
Platform curPlatform = this.getPlatform();
if (curPlatform != null) {
String platformName = curPlatform.getName();
Platform refreshedPlatform = Platform.getByName(platformName);
// setPlatform forces the audio to switch
this.setPlatform(refreshedPlatform);
}
}
}
public int getDisplayTime() {
if (currentLifter != timer.getOwner()) {
return getTimeAllowed();
} else {
return getTimeRemaining();
}
}
public void startUpdateModel() {
final CountdownTimer timer1 = this.getTimer();
final Lifter lifter = getCurrentLifter();
manageTimerOwner(lifter, this, timer1);
final boolean running = timer1.isRunning();
timingLogger.debug("start timer.isRunning()={}", running); //$NON-NLS-1$
timer1.restart();
setLifterAsHavingStarted(lifter);
getRefereeDecisionController().setBlocked(false);
}
public void stopUpdateModel() {
getTimer().pause(); // pause() does not clear the associated lifter
}
public void oneMinuteUpdateModel() {
if (getTimer().isRunning()) {
timer.forceTimeRemaining(60000); // pause() does not clear the associated lifter
}
setForcedByTimekeeper(true, 60000);
}
public void twoMinuteUpdateModel() {
if (getTimer().isRunning()) {
timer.forceTimeRemaining(120000); // pause() does not clear the associated lifter
}
setForcedByTimekeeper(true, 120000);
}
public void okLiftUpdateModel() {
Lifter currentLifter2 = getCurrentLifter();
liftDone(currentLifter2, true);
currentLifter2.successfulLift();
}
public void failedListUpdateModel() {
Lifter currentLifter2 = getCurrentLifter();
liftDone(currentLifter2, false);
currentLifter2.failedLift();
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.CompetitionSessionLookup;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.spreadsheet.JXLSJurySheet;
import org.concordiainternational.competition.spreadsheet.JXLSLifterCard;
import org.concordiainternational.competition.spreadsheet.JXLSStartingList;
import org.concordiainternational.competition.spreadsheet.JXLSWeighInSheet;
import org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.SessionSelect;
import org.concordiainternational.competition.ui.generators.CommonColumnGenerator;
import org.concordiainternational.competition.ui.generators.LiftCellStyleGenerator;
import org.concordiainternational.competition.ui.list.LifterHbnList;
import org.concordiainternational.competition.utils.ItemAdapter;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.SystemError;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class WeighInList extends LifterHbnList implements ApplicationView, Bookmarkable {
private static final long serialVersionUID = -6455130090728823622L;
private boolean admin = false;
private String viewName;
private SessionSelect sessionSelect;
public WeighInList(boolean initFromFragment, String viewName, boolean admin) {
super(CompetitionApplication.getCurrent(), Messages.getString(
"WeighInList.title", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.admin = admin;
init();
if (admin) {
this.setTableCaption(Messages.getString("WeighInList.adminTitle", app.getLocale())); //$NON-NLS-1$
Component newToolbar = this.createTableToolbar();
this.setTableToolbar(newToolbar);
} else {
table.removeGeneratedColumn("actions"); //$NON-NLS-1$
}
CompetitionApplication.getCurrent().getUriFragmentUtility().setFragment(getFragment(), false);
}
@Override
protected void addGeneratedColumns() {
super.addGeneratedColumns();
table.addGeneratedColumn("category", new CommonColumnGenerator(app)); //$NON-NLS-1$
table.addGeneratedColumn("registrationCategory", new CommonColumnGenerator(app)); //$NON-NLS-1$
table.addGeneratedColumn("competitionSession", new CommonColumnGenerator(app)); //$NON-NLS-1$
table.addGeneratedColumn("teamMember", new CommonColumnGenerator(app)); //$NON-NLS-1$
table.addGeneratedColumn("qualifyingTotal", new CommonColumnGenerator(app)); //$NON-NLS-1$
setExpandRatios();
}
/**
* Load container content to Table
*/
@Override
protected void loadData() {
// load all lifters
final LifterContainer cont = new LifterContainer((CompetitionApplication) app, false);
// cont.sort(new String[]{"registrationCategory","lotNumber"}, new
// boolean[]{true,true});
table.setContainerDataSource(cont);
}
@Override
public void clearCache() {
((LifterContainer) table.getContainerDataSource()).clearCache();
}
@Override
protected void createToolbarButtons(HorizontalLayout tableToolbar1) {
sessionSelect = new SessionSelect((CompetitionApplication) app, app.getLocale(), this);
tableToolbar1.addComponent(sessionSelect);
super.createToolbarButtons(tableToolbar1);
final Locale locale = app.getLocale();
if (this.admin) {
addRowButton = new Button(Messages.getString("Common.addRow", app.getLocale()), this, "newItem"); //$NON-NLS-1$ //$NON-NLS-2$
tableToolbar1.addComponent(addRowButton);
// draw lot numbers
final Button drawLotsButton = new Button(Messages.getString("WeighInList.drawLots", locale)); //$NON-NLS-1$
final Button.ClickListener drawLotsListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
drawLotsButton.setComponentError(null);
drawLots();
}
};
drawLotsButton.addListener(drawLotsListener);
tableToolbar1.addComponent(drawLotsButton);
// produce start list for technical meeting, includes all lifters.
// false = show unweighed lifters
final Button startListButton = startListButton(locale, false);
tableToolbar1.addComponent(startListButton);
// produce start list for technical meeting, includes all lifters.
// false = show unweighed lifters
final Button lifterCardsButton = lifterCardsButton(locale, false);
tableToolbar1.addComponent(lifterCardsButton);
// clear all lifters.
final Button clearAllButton = new Button(Messages.getString("WeighInList.deleteLifters", locale)); //$NON-NLS-1$
final Button.ClickListener clearAllListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
clearAllButton.setComponentError(null);
clearAllLifters();
}
};
clearAllButton.addListener(clearAllListener);
tableToolbar1.addComponent(clearAllButton);
} else {
// produce list of lifters that were actually weighed-in.
// true = exclude unweighed lifters
final Button weighInListButton = weighInListButton(locale, true);
tableToolbar1.addComponent(weighInListButton);
// produce list of lifters that were actually weighed-in.
// true = exclude unweighed lifters
final Button juryListButton = juryListButton(locale, true);
tableToolbar1.addComponent(juryListButton);
final Button editButton = new Button(Messages.getString("ResultList.edit", locale)); //$NON-NLS-1$
final Button.ClickListener editClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 7744958942977063130L;
@Override
public void buttonClick(ClickEvent event) {
editCompetitionSession(sessionSelect.getSelectedId(),sessionSelect.getSelectedItem());
}
};
editButton.addListener(editClickListener);
tableToolbar1.addComponent(editButton);
}
final Button refreshButton = new Button(Messages.getString("ResultList.Refresh", locale)); //$NON-NLS-1$
final Button.ClickListener refreshClickListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 7744958942977063130L;
@Override
public void buttonClick(ClickEvent event) {
CategoryLookup.getSharedInstance().reload();
populateAndConfigureTable();
}
};
refreshButton.addListener(refreshClickListener);
tableToolbar1.addComponent(refreshButton);
}
/**
* @param locale
* @return
*/
private Button lifterCardsButton(final Locale locale, final boolean excludeNotWeighed) {
final Button lifterCardsButton = new Button(Messages.getString("WeighInList.LifterCardsButton", locale)); //$NON-NLS-1$
final Button.ClickListener listener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
lifterCardsButton.setComponentError(null);
final JXLSWorkbookStreamSource streamSource = new JXLSLifterCard();
// final OutputSheetStreamSource<LifterCardSheet> streamSource = new OutputSheetStreamSource<LifterCardSheet>(
// LifterCardSheet.class, (CompetitionApplication) app, excludeNotWeighed);
if (streamSource.size() == 0) {
lifterCardsButton.setComponentError(new SystemError(Messages.getString(
"WeighInList.NoLifters", locale))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("WeighInList.NoLifters", locale)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()); //$NON-NLS-1$
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("WeighInList.CardsPrefix", locale) + now); //$NON-NLS-1$
}
};
lifterCardsButton.addListener(listener);
return lifterCardsButton;
}
/**
* @param locale
* @return
*/
private Button weighInListButton(final Locale locale, final boolean excludeNotWeighed) {
final Button weighInListButton = new Button(Messages.getString("WeighInList.StartingWeightSheet", locale)); //$NON-NLS-1$
final Button.ClickListener listener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
weighInListButton.setComponentError(null);
final JXLSWorkbookStreamSource streamSource = new JXLSWeighInSheet(excludeNotWeighed);
// final OutputSheetStreamSource<WeighInSheet> streamSource = new OutputSheetStreamSource<WeighInSheet>(
// WeighInSheet.class, (CompetitionApplication) app, excludeNotWeighed);
if (streamSource.size() == 0) {
weighInListButton.setComponentError(new SystemError(Messages.getString(
"WeighInList.NoLifters", locale))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("WeighInList.NoLifters", locale)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()); //$NON-NLS-1$
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("WeighInList.WeighInPrefix", locale) + now); //$NON-NLS-1$
}
};
weighInListButton.addListener(listener);
return weighInListButton;
}
/**
* @param locale
* @return
*/
private Button juryListButton(final Locale locale, final boolean excludeNotWeighed) {
final Button juryListButton = new Button(Messages.getString("JuryList.JurySheet", locale)); //$NON-NLS-1$
final Button.ClickListener listener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
juryListButton.setComponentError(null);
final JXLSWorkbookStreamSource streamSource = new JXLSJurySheet(excludeNotWeighed);
// final OutputSheetStreamSource<JurySheet> streamSource = new OutputSheetStreamSource<JurySheet>(
// JurySheet.class, (CompetitionApplication) app, excludeNotWeighed);
if (streamSource.size() == 0) {
juryListButton.setComponentError(new SystemError(Messages
.getString("WeighInList.NoLifters", locale))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("WeighInList.NoLifters", locale)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()); //$NON-NLS-1$
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("WeighInList.JuryPrefix", locale) + now); //$NON-NLS-1$
}
};
juryListButton.addListener(listener);
return juryListButton;
}
/**
* @param locale
* @return
*/
private Button startListButton(final Locale locale, final boolean excludeNotWeighed) {
final Button startListButton = new Button(Messages.getString("WeighInList.StartSheet", locale)); //$NON-NLS-1$
final Button.ClickListener listener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -8473648982746209221L;
@Override
public void buttonClick(ClickEvent event) {
startListButton.setComponentError(null);
final JXLSWorkbookStreamSource streamSource = new JXLSStartingList();
// final OutputSheetStreamSource<StartList> streamSource = new OutputSheetStreamSource<StartList>(
// StartList.class, (CompetitionApplication) app, false);
if (streamSource.size() == 0) {
startListButton.setComponentError(new SystemError(Messages.getString(
"WeighInList.NoLifters", locale))); //$NON-NLS-1$
throw new RuntimeException(Messages.getString("WeighInList.NoLifters", locale)); //$NON-NLS-1$
}
String now = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date()); //$NON-NLS-1$
((UserActions) app).openSpreadsheet(streamSource, Messages.getString("WeighInList.StartListPrefix", locale) + now); //$NON-NLS-1$
}
};
startListButton.addListener(listener);
return startListButton;
}
/**
* Draw lot numbers for all lifters.
*/
protected void drawLots() {
final List<Lifter> list = allLifters(false);
LifterSorter.drawLots(list);
this.refresh();
}
/**
* Delete lifters from current group (all lifters if no current group)
*/
protected void clearAllLifters() {
final Session session = CompetitionApplication.getCurrent().getHbnSession();
final List<Lifter> list = allLifters(true);
for (Lifter curLifter : list) {
session.delete(curLifter);
}
this.refresh();
}
@SuppressWarnings("unchecked")
protected List<Lifter> allLifters(boolean restrictToCurrentGroup) {
final CompetitionApplication compApp = (CompetitionApplication) app;
final Session session = compApp.getHbnSession();
Criteria crit = session.createCriteria(Lifter.class);
final CompetitionSession currentGroup = compApp.getCurrentCompetitionSession();
final String name = (currentGroup != null ? (String) currentGroup.getName() : null);
if (restrictToCurrentGroup && currentGroup != null) {
crit.createCriteria("competitionSession").add( //$NON-NLS-1$
Restrictions.eq("name", name)); //$NON-NLS-1$
}
return (List<Lifter>) crit.list();
}
private String[] NATURAL_COL_ORDER = null;
private String[] COL_HEADERS = null;
private String platformName;
private String groupName;
/**
* @return Natural property order for Category bean. Used in tables and
* forms.
*/
@Override
protected String[] getColOrder() {
if (NATURAL_COL_ORDER != null) return NATURAL_COL_ORDER;
if (admin) {
NATURAL_COL_ORDER = new String[] { "membership", //$NON-NLS-1$
"lotNumber", //$NON-NLS-1$
"lastName", //$NON-NLS-1$
"firstName", //$NON-NLS-1$
"gender", //$NON-NLS-1$
"birthDate", //$NON-NLS-1$
"club", //$NON-NLS-1$
"registrationCategory", //$NON-NLS-1$
"competitionSession", //$NON-NLS-1$
"qualifyingTotal", //$NON-NLS-1$
"teamMember", //$NON-NLS-1$
"actions" // in table mode, actions come last. //$NON-NLS-1$
};
} else {
NATURAL_COL_ORDER = new String[] { "membership", //$NON-NLS-1$
"lotNumber", //$NON-NLS-1$
"lastName", //$NON-NLS-1$
"firstName", //$NON-NLS-1$
"gender", //$NON-NLS-1$
"birthDate", //$NON-NLS-1$
"club", //$NON-NLS-1$
"registrationCategory", //$NON-NLS-1$
"category", //$NON-NLS-1$
"bodyWeight", //$NON-NLS-1$
"snatch1Declaration", //$NON-NLS-1$
"cleanJerk1Declaration", //$NON-NLS-1$
"competitionSession", //$NON-NLS-1$
"actions" // in table mode, actions come last. //$NON-NLS-1$
};
}
return NATURAL_COL_ORDER;
}
/**
* @return Localized captions for properties in same order as in
* {@link #getColOrder()}
*/
@Override
protected String[] getColHeaders() {
final Locale locale = app.getLocale();
if (COL_HEADERS != null) return COL_HEADERS;
if (admin) {
COL_HEADERS = new String[] { Messages.getString("Lifter.membership", locale), //$NON-NLS-1$
Messages.getString("Lifter.lotNumber", locale), //$NON-NLS-1$
Messages.getString("Lifter.lastName", locale), //$NON-NLS-1$
Messages.getString("Lifter.firstName", locale), //$NON-NLS-1$
Messages.getString("Lifter.gender", locale), //$NON-NLS-1$
Messages.getString("Lifter.birthDate", locale), //$NON-NLS-1$
Messages.getString("Lifter.club", locale), //$NON-NLS-1$
Messages.getString("Lifter.registrationCategory", locale), //$NON-NLS-1$
Messages.getString("Lifter.group", locale), //$NON-NLS-1$
Messages.getString("Lifter.qualifyingTotal", locale), //$NON-NLS-1$
Messages.getString("Lifter.teamMember", locale), //$NON-NLS-1$
Messages.getString("Common.actions", locale), //$NON-NLS-1$
};
} else {
COL_HEADERS = new String[] { Messages.getString("Lifter.membership", locale), //$NON-NLS-1$
Messages.getString("Lifter.lotNumber", locale), //$NON-NLS-1$
Messages.getString("Lifter.lastName", locale), //$NON-NLS-1$
Messages.getString("Lifter.firstName", locale), //$NON-NLS-1$
Messages.getString("Lifter.gender", locale), //$NON-NLS-1$
Messages.getString("Lifter.birthDate", locale), //$NON-NLS-1$
Messages.getString("Lifter.club", locale), //$NON-NLS-1$
Messages.getString("Lifter.registrationCategory", locale), //$NON-NLS-1$
Messages.getString("Lifter.category", locale), //$NON-NLS-1$
Messages.getString("Lifter.bodyWeight", locale), //$NON-NLS-1$
Messages.getString("Lifter.snatch1Declaration", locale), //$NON-NLS-1$
Messages.getString("Lifter.cleanJerk1Declaration", locale), //$NON-NLS-1$
Messages.getString("Lifter.group", locale), //$NON-NLS-1$
Messages.getString("Common.actions", locale), //$NON-NLS-1$
};
}
return COL_HEADERS;
}
@Override
protected void populateAndConfigureTable() {
super.populateAndConfigureTable();
table.setColumnExpandRatio("lastName",100F);
table.setColumnExpandRatio("firstName",100F);
if (table.size() > 0) {
// set styling;
table.setCellStyleGenerator(new LiftCellStyleGenerator(table));
}
}
/**
* Make sure that if the table is editable its actions are visible.
*/
@Override
protected void setDefaultActions() {
if (table != null) {
if (!table.isEditable()) {
table.removeGeneratedColumn("actions"); //$NON-NLS-1$
table.setSizeFull();
} else {
if (admin) this.addDefaultActions();
}
}
}
/*
* Add a new item with correct default values.
*
* @see org.concordiainternational.competition.ui.list.GenericList#newItem()
*/
@Override
public Object newItem() {
Object itemId = super.newItem();
final CompetitionSession currentGroup = CompetitionApplication.getCurrent().getCurrentCompetitionSession();
if (currentGroup != null) {
Lifter lifter = (Lifter) ItemAdapter.getObject(table, itemId);
lifter.setCompetitionSession(currentGroup);
lifter.setBodyWeight(0.0D);
lifter.setSnatch1Declaration(""); //$NON-NLS-1$
lifter.setCleanJerk1Declaration(""); //$NON-NLS-1$
lifter.setLotNumber(99);
}
refresh();
table.setEditable(true);
table.setValue(itemId);
setButtonVisibility();
return itemId;
}
@Override
public void refresh() {
super.refresh();
setButtonVisibility();
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return true;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.Bookmarkable#getFragment()
*/
@Override
public String getFragment() {
CompetitionSession session = CompetitionApplication.getCurrent().getCurrentCompetitionSession();
String sessionName = null;
if (session != null) {
sessionName = session.getName();
}
return viewName+"/"+(platformName == null ? "" : platformName)+"/"+(sessionName == null ? "" : sessionName);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
if (params.length >= 2) {
platformName = params[1];
} else {
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (params.length >= 3) {
groupName = params[2];
final CompetitionApplication cApp = (CompetitionApplication)app;
cApp.setCurrentCompetitionSession(new CompetitionSessionLookup(cApp).lookup(groupName));
} else {
groupName = null;
}
}
@Override
public void registerAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void unregisterAsListener() {
app.getMainWindow().addListener((CloseListener) this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.weelayout.WeeLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;
public class LoadImage extends WeeLayout {
@SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(LoadImage.class);
private static final long serialVersionUID = 8340222363211435843L;
private int weight;
private Window parentWindow;
public LoadImage() {
super(Direction.HORIZONTAL);
addStyleName("loadChart");
setMargin(false);
}
public LoadImage(Window parentWindow) {
this();
this.parentWindow = parentWindow;
}
public void computeImageArea(SessionData masterData, Platform platform) {
final Lifter currentLifter = masterData.getCurrentLifter();
final Integer barWeight = computeBarWeight(masterData, platform);
if (currentLifter == null) {
setCaption("");
return;
}
weight = currentLifter.getNextAttemptRequestedWeight();
final String caption = weight + "kg";
createImageArea(platform, barWeight, caption);
}
/**
* @param platform
* @param barWeight
* @param caption
*/
private void createImageArea(Platform platform, final Integer barWeight, final String caption) {
this.removeAllComponents();
setCaption(caption);
if (weight == 0) return;
// compute the bar and collar first.
addPlates(1, "bar", barWeight);
addPlates(1, "barInner", 0);
final Integer collarAvailable = platform.getNbC_2_5();
boolean useCollar = collarAvailable > 0;
if (weight >= 25) {
if (useCollar) {
// we only take off the collar weight because we need to
// wait before showing the collar.
weight -= 5;
}
// use large plates first
addPlates(platform.getNbL_25(), "L_25", 2 * 25);
addPlates(platform.getNbL_20(), "L_20", 2 * 20);
addPlates(platform.getNbL_15(), "L_15", 2 * 15);
addPlates(platform.getNbL_10(), "L_10", 2 * 10);
} else {
int nonBarWeight = weight;
// make sure that large 5 and large 2.5 are only used when warranted
// (must not require manual intervention if they are available)
if (platform.getNbL_2_5() > 0 && nonBarWeight < 10 ||
platform.getNbL_5() > 0 && nonBarWeight < 15 ) {
useCollar = false;
}
if (useCollar) {
// we take off the collar weight because we need to
// wait before showing the collar.
weight -= 5;
nonBarWeight -= 5;
}
addPlates(platform.getNbL_10(), "L_10", 2 * 10);
addPlates(platform.getNbL_5(), "L_5", 2 * 5);
if (nonBarWeight < 10) {
addPlates(platform.getNbL_2_5(), "L_2_5", 2 * 2.5);
}
}
// add the small plates
addPlates(platform.getNbS_5(), "S_5", 2 * 5);
addPlates(platform.getNbS_2_5(), "S_2_5", 2 * 2.5);
// collar is depicted here
if (useCollar) {
// we add back the collar weight we took off above
weight += 5;
addPlates(collarAvailable, "C_2_5", 2 * 2.5);
}
// remainder of small plates
addPlates(platform.getNbS_2(), "S_2", 2 * 2);
addPlates(platform.getNbS_1_5(), "S_1_5", 2 * 1.5);
addPlates(platform.getNbS_1(), "S_1", 2 * 1);
addPlates(platform.getNbS_0_5(), "S_0_5", 2 * 0.5);
addPlates(1, "barOuter", 0);
}
/**
* @param availablePlates
* @param style
* @param plateWeight
* @return
*/
private int addPlates(Integer availablePlates, String style, double plateWeight) {
int subtractedWeight = 0;
while (availablePlates > 0 && weight >= plateWeight) {
Label plate = new Label();
plate.setSizeUndefined();
plate.addStyleName(style);
if (!style.startsWith("bar")) {
plate.addStyleName("plate");
}
this.addComponent(plate);
this.setComponentAlignment(plate, Alignment.MIDDLE_CENTER);
final long delta = Math.round(plateWeight);
weight -= delta;
subtractedWeight += delta;
availablePlates--;
}
return subtractedWeight;
}
private Integer computeBarWeight(SessionData masterData, Platform platform) {
if (platform.getLightBar() > 0) {
return platform.getLightBar();
} else {
return computeOfficialBarWeight(masterData, platform);
}
}
/**
* @return
*/
private Integer computeOfficialBarWeight(SessionData masterData, Platform platform) {
final Lifter currentLifter = masterData.getCurrentLifter();
String gender = "M";
if (currentLifter != null) {
gender = currentLifter.getGender();
}
final int expectedBarWeight = "M".equals(gender) ? 20 : 15;
return expectedBarWeight;
}
@Override
public void setCaption(String caption) {
if (parentWindow == null) {
super.setCaption(caption);
} else {
parentWindow.setCaption(caption);
}
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import java.util.Locale;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.timer.CountdownTimer;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.CustomTextField;
import org.concordiainternational.competition.ui.generators.WeightFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.MethodProperty;
import com.vaadin.data.validator.IntegerValidator;
import com.vaadin.event.Action;
import com.vaadin.event.Action.Handler;
import com.vaadin.event.ShortcutAction;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window.CloseEvent;
public class LifterCardEditor extends Panel implements
Property.ValueChangeListener, // listen to changes within the editor
Handler, // handle keyboard shortcuts
ApplicationView
{
private static final long serialVersionUID = -216488484306113727L;
private static final Logger logger = LoggerFactory.getLogger(LifterCardEditor.class);
private Button save = null;
private Button delete = null;
private GridLayout grid = null;
private EditableList liftList;
LifterInfo lifterCardIdentification;
private Lifter lifter = null;
boolean ignoreChanges;
private EditingView parentView;
public LifterCardEditor(EditableList announcerList, EditingView parentView) {
super();
this.parentView = parentView;
final Locale locale = CompetitionApplication.getCurrent().getLocale();
this.liftList = announcerList;
HorizontalLayout root = new HorizontalLayout();
this.addComponent(root);
this.setSizeFull();
root.setMargin(false);
// left hand side lifter id
lifterCardIdentification = new LifterInfo("bottom part", liftList.getGroupData(), null, parentView); //$NON-NLS-1$
lifterCardIdentification.setWidth(6.0F, Sizeable.UNITS_CM); //$NON-NLS-1$
lifterCardIdentification.setMargin(false);
lifterCardIdentification.addStyleName("currentLifterSmallSummary"); //$NON-NLS-1$
root.addComponent(lifterCardIdentification);
root.setComponentAlignment(lifterCardIdentification, Alignment.TOP_LEFT);
// lifter card
Form liftGrid = createLifterGrid(locale);
root.addComponent(liftGrid);
// right-hand side
FormLayout rightHandSide = createRightHandSide(locale);
rightHandSide.setMargin(true);
root.addComponent(rightHandSide);
addActionHandler(this);
}
private Boolean sticky = false;
public Boolean getSticky() {
return sticky;
}
public void setSticky(Boolean sticky) {
this.sticky = sticky;
}
private Item item;
private Button forceAsCurrent;
private FormLayout createRightHandSide(Locale locale) {
setSticky(parentView.isStickyEditor());
FormLayout rightHandSide = new FormLayout();
Button okButton = new Button();
okButton.setCaption(Messages.getString("LifterCardEditor.ok", locale)); //$NON-NLS-1$
okButton.addListener(new Button.ClickListener() {
private static final long serialVersionUID = 2180734041886293420L;
@Override
public void buttonClick(ClickEvent event) {
logger.info("OK button pushed.");
parentView.setStickyEditor(false);
setSticky(false);
}
});
forceAsCurrent = new Button();
forceAsCurrent.setCaption(Messages.getString("LifterInfo.ForceAsCurrent", locale)); //$NON-NLS-1$
forceAsCurrent.addListener(new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 5693610077500773431L;
@Override
public void buttonClick(ClickEvent event) {
// next statement no longer needed as we are currently
// listening to the lifter
// and once setForceAsCurrent fires, the various new
// editors will register themselves
// liftList.getGroupData().trackEditors(lifter,
// previousLifter, editor);
logger.info("FORCE AS CURRENT button pushed.");
final CountdownTimer timer = liftList.getGroupData().getTimer();
if (timer != null) timer.pause(TimeStoppedNotificationReason.FORCE_AS_CURRENT);
lifter.setForcedAsCurrent(true); // this will trigger an
// update event on the
// lift list.
}
});
Button withdraw = new Button();
withdraw.setCaption(Messages.getString("LifterInfo.Withdraw", locale)); //$NON-NLS-1$
withdraw.addListener(new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 5693610077500773431L;
@Override
public void buttonClick(ClickEvent event) {
logger.info("WITHDRAW button pushed.");
final CountdownTimer timer = liftList.getGroupData().getTimer();
if (timer != null) timer.pause(TimeStoppedNotificationReason.LIFTER_WITHDRAWAL);
lifter.withdraw(); // this will trigger an update event on the lift list.
}
});
rightHandSide.setWidth("50ex"); //$NON-NLS-1$
rightHandSide.addComponent(okButton);
rightHandSide.addComponent(forceAsCurrent);
rightHandSide.addComponent(withdraw);
setButtonVisibility();
return rightHandSide;
}
/**
* @param firstLifter
* @param forceAsCurrent
*/
private void setButtonVisibility() {
final Lifter firstLifter = liftList.getFirstLifter();
forceAsCurrent.setVisible(lifter != firstLifter);
}
public void buttonClick(ClickEvent event) {
if (event.getButton() == delete) {
liftList.deleteItem(lifter.getId());
} else if (event.getButton() == save) {
liftList.getGroupData().persistPojo(lifter);
}
}
/**
* Create the lifter grid to mimic the layout of a standard lifter card used
* by announcers.
*
* @param app
* @param locale
* @return
*/
private Form createLifterGrid(Locale locale) {
grid = new GridLayout(7, 7); // grid is 6x5 plus header row and header
// column
Form liftGrid = new Form(grid);
liftGrid.setSizeUndefined();
createGridHeaders(locale);
populateEmptyGrid(locale);
liftGrid.setWriteThrough(true);
grid.setSpacing(false);
grid.setStyleName("lifterGrid");
return liftGrid;
}
/**
* Create the header row and the header column.
*
* @param locale
*/
private void createGridHeaders(Locale locale) {
// first row
grid.addComponent(new Label("")); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.snatch1", locale))); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.snatch2", locale))); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.snatch3", locale))); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.cleanJerk1", locale))); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.cleanJerk2", locale))); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.cleanJerk3", locale))); //$NON-NLS-1$
// first column
grid.addComponent(new Label(Messages.getString("Lifter.automaticProgression", locale)), 0, 1); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.declaration", locale)), 0, 2); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.change1", locale)), 0, 3); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.change2", locale)), 0, 4); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.actualLift", locale)), 0, 5); //$NON-NLS-1$
grid.addComponent(new Label(Messages.getString("Lifter.liftTime", locale)), 0, 6); //$NON-NLS-1$
// 20 characters wide.
grid.getComponent(0, 0).setWidth("25ex"); //$NON-NLS-1$
}
/**
* Create empty fields for all the cells.
*
* @param app
*/
private void populateEmptyGrid(Locale locale) {
for (int column = 1; column < grid.getColumns(); column++) {
for (int row = 1; row < grid.getRows(); row++) {
Field field = null;
if (row < grid.getRows() - 1) {
field = new CustomTextField();
((TextField) field).setWidth("8.5ex"); //$NON-NLS-1$
if (row > 1) {
field.addValidator(new IntegerValidator(Messages.getString(
"LifterCardEditor.integerExpected", locale) //$NON-NLS-1$
));
}
} else {
// last row gets time fields
field = createTimeField(null);
}
grid.addComponent(field, column, row);
}
}
makeGridFieldsReactImmediately();
}
/**
* Display the time of day portion of a date.
*
* @param tableCaption
* Human-readable label shown with the field.
*/
private DateField createTimeField(String caption) {
final DateField timeField = new DateField(caption);
timeField.setDateFormat("HH:mm:ss"); //$NON-NLS-1$
timeField.setIcon(null);
timeField.setWidth("9.5ex"); //$NON-NLS-1$
timeField.addStyleName("timeField"); //$NON-NLS-1$
return timeField;
}
/**
* Connect the lifter in the bottom part to the indicated item in the lift
* list. By binding to the items in the editor grid to the same property
* datasource as in the lift list, updates are automatic and instantaneous.
*
* @param lifter1
* @param item1
*/
public void loadLifter(Lifter lifter1, Item item1) {
logger.debug("announcerView={} loading {} previousLifter {}", //$NON-NLS-1$
new Object[] { parentView, lifter1, this.lifter }); //$NON-NLS-1$
// LoggerUtils.logException(logger, new Exception("whoCalls"));
final SessionData groupData = liftList.getGroupData();
if (lifter1 == null) {
logger.debug("case 1, lifter = null"); //$NON-NLS-1$
// we leave the current lifter as is
setFocus(this.lifter, this.item);
return;
} else if ((parentView.isStickyEditor() && lifter1 != this.lifter)) {
logger.debug("Case 2, sticky editor and lifter change"); //$NON-NLS-1$
// we are sticky and the current lifter is not ourselves
// we leave the current lifter as is, but the focus may need to
// change.
setFocus(this.lifter, this.item);
setButtonVisibility();
return;
} else {
logger.debug("case 3: not sticky, or reloading same lifter"); //$NON-NLS-1$
ignoreChanges = true;
groupData.trackEditors(lifter1, this.lifter, this);
lifterCardIdentification.loadLifter(lifter1, liftList.getGroupData());
int column = 1;
int row = 1;
bindGridCell(column, row++, item1, "snatch1AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch1Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch1Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch1Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch1ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch1LiftTime"); //$NON-NLS-1$
column++;
row = 1;
bindGridCell(column, row++, item1, "snatch2AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch2Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch2Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch2Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch2ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch2LiftTime"); //$NON-NLS-1$
column++;
row = 1;
bindGridCell(column, row++, item1, "snatch3AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch3Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch3Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch3Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch3ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "snatch3LiftTime"); //$NON-NLS-1$
column++;
row = 1;
bindGridCell(column, row++, item1, "cleanJerk1AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk1Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk1Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk1Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk1ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk1LiftTime"); //$NON-NLS-1$
column++;
row = 1;
bindGridCell(column, row++, item1, "cleanJerk2AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk2Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk2Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk2Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk2ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk2LiftTime"); //$NON-NLS-1$
column++;
row = 1;
bindGridCell(column, row++, item1, "cleanJerk3AutomaticProgression"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk3Declaration"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk3Change1"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk3Change2"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk3ActualLift"); //$NON-NLS-1$
bindGridCell(column, row++, item1, "cleanJerk3LiftTime"); //$NON-NLS-1$
logger.debug("LifterCardEditor.loadLifter() end: {} ", lifter1.getLastName()); //$NON-NLS-1$
logger.debug("*** setting lifter to {}", lifter1); //$NON-NLS-1$
this.lifter = lifter1;
this.item = item1;
// set the focus in the best location
logger.debug("before setFocus"); //$NON-NLS-1$
setFocus(lifter1, item1);
logger.debug("before setButtonVisibility"); //$NON-NLS-1$
setButtonVisibility();
logger.debug(("before setButtonVisibility")); //$NON-NLS-1$
ignoreChanges = false;
}
}
private void setFocus(Lifter lifter, Item item) {
ignoreChanges = true;
clearFocus();
int targetColumn = lifter.getAttemptsDone() + 1;
if (targetColumn > 6) {
Component selectedComponent = grid.getComponent(6, 5);
Field f = (Field) selectedComponent;
f.focus();
} else {
int row = 5;
while (row > 0) {
Component proposed = grid.getComponent(targetColumn, row);
final Field f = (Field) proposed;
final String value = (String) f.getValue();
if (value == null || value.isEmpty()) {
row--;
} else {
setStyle(f, "current"); //$NON-NLS-1$
row++; // we backed up one row too far
Component focus = grid.getComponent(targetColumn, row);
final Field focusField = (Field) focus;
if (focusField != null) {
// logger.trace("setting focus at column {} row {}",targetColumn,row);
focusField.focus();
setStyle(focusField, "hfocus"); //$NON-NLS-1$
}
break;
}
}
}
int row = 5;
for (int curColumn = 1; curColumn < targetColumn; curColumn++) {
Component proposed = grid.getComponent(curColumn, row);
final Field f = (Field) proposed;
final String value = (String) f.getValue();
// logger.trace("value = {} column={} row={}", new
// Object[]{value,curColumn,row});
if (value == null) break;
if (value.isEmpty()) break;
final int intValue = WeightFormatter.safeParseInt(value);
if (intValue > 0) {
setStyle(f, "success"); //$NON-NLS-1$
} else {
setStyle(f, "fail"); //$NON-NLS-1$
}
}
ignoreChanges = false;
}
/**
* @param f
*/
private void setStyle(final Field f, String style) {
ignoreChanges = true;
if (!f.getStyleName().equals(style)) {
f.setStyleName(style);
}
ignoreChanges = false;
}
private void clearFocus() {
ignoreChanges = true;
for (int column = 1; column < grid.getColumns(); column++) {
for (int row = 1; row < grid.getRows(); row++) {
Field field = (Field) grid.getComponent(column, row);
if (!field.getStyleName().isEmpty()) field.setStyleName(""); //$NON-NLS-1$
}
}
ignoreChanges = false;
}
/**
* Utility routine to associate a grid cell with a Pojo field through a
* property.
*
* @param column
* @param row
* @param item1
* @param propertyId
*/
private void bindGridCell(int column, int row, Item item1, Object propertyId) {
final Field component = (Field) grid.getComponent(column, row);
component.setPropertyDataSource(item1.getItemProperty(propertyId));
}
/**
* Add value change listeners on relevant grids fields. Also make them write
* through and immediate. Exclude grid fields that are computed, otherwise
* infinite loop happens.
*/
private void makeGridFieldsReactImmediately() {
for (int column = 1; column <= 6; column++) {
for (int row = 1; row <= 6; row++) {
Component component = grid.getComponent(column, row);
if (row == 1 || row == 6) {
// we skip the first row (automatic progressions) which are
// computed.
// same for last row.
component.setReadOnly(true);
} else {
if (component instanceof Field) {
final Field field = (Field) component;
// System.err.println("row "+row+"column "+column+" id="+System.identityHashCode(field));
field.addListener((ValueChangeListener) this);
field.setWriteThrough(true);
((TextField) field).setImmediate(true);
}
}
}
}
}
/*
* Event received when any of the cells in the form has changed. We need to
* recompute the dependent cells (non-Javadoc)
*
* @see
* com.vaadin.data.Property.ValueChangeListener#valueChange(com.vaadin.data
* .Property.ValueChangeEvent)
*/
@Override
public void valueChange(Property.ValueChangeEvent event) {
// prevent triggering if called recursively or during initial display
// prior to editing.
if (ignoreChanges) return;
ignoreChanges = true;
// this means that an editable property has changed in the form; refresh
// all the computed ones.
if (event != null) logger.debug(event.getProperty().toString());
// if (! (event.getProperty() instanceof MethodProperty)) return;
// new
// Exception("LifterCardEditor.valueChange() whocalls ").printStackTrace();
// System.err.println("LifterCardEditor.valueChange()"+event.getProperty().getClass()+System.identityHashCode(event.getProperty())+" value="+event.getProperty().getValue()+" type="+event.getProperty().getType());
// refresh the automatic progressions
refreshGridCell(2, 1);
refreshGridCell(3, 1);
refreshGridCell(5, 1);
refreshGridCell(6, 1);
// refresh the lift times
refreshGridCell(1, 6);
refreshGridCell(2, 6);
refreshGridCell(3, 6);
refreshGridCell(4, 6);
refreshGridCell(5, 6);
refreshGridCell(6, 6);
// tell our container to update the lifter. This will propagate to the
// lift list.
// Not necessary to call persistPojo if connected to group data: group
// data already got an update.
if (!(parentView instanceof AnnouncerView)) {
this.liftList.getGroupData().persistPojo(lifter);
}
// at this point we have finished processing our screen update. we tell
// the lift
// list to clear its selection.
this.liftList.clearSelection();
ignoreChanges = false;
}
/**
* Update the gridCell with the underlying value
*
* @param column
* @param row
* @param newValue
*/
private void refreshGridCell(int column, int row) {
Field field = (Field) this.grid.getComponent(column, row);
refreshField(field);
}
/**
* Update the field with the current value of the underlying data source,
* which may have changed. If a MethodProperty is used, and the setter on
* the bean is called, the Property does not know of this change, and does
* not broacast. Likewise, if a getter computes from other fields, there is
* no broadcast when the other fields change.
*
* @param field
* the field that needs updating.
*/
private void refreshField(Field field) {
Property dataSource = ((MethodProperty<?>) field.getPropertyDataSource());
// this will fire a value change if the value has in fact changed.
field.setPropertyDataSource(dataSource);
}
// Have the unmodified Enter key cause an event
Action action_ok = new ShortcutAction("Default key", //$NON-NLS-1$
ShortcutAction.KeyCode.ENTER, null);
/**
* Retrieve actions for a specific component. This method will be called for
* each object that has a handler; in this example just for login panel. The
* returned action list might as well be static list.
*/
@Override
public Action[] getActions(Object target, Object sender) {
return new Action[] { action_ok };
}
/**
* Handle actions received from keyboard. This simply directs the actions to
* the same listener methods that are called with ButtonClick events.
*/
@Override
public void handleAction(Action action, Object sender, Object target) {
if (action == action_ok) {
okHandler();
}
}
public void okHandler() {
// we don't know field changed, but it doesn't matter since the sort
// order is global.
valueChange(null);
}
public Lifter getLifter() {
return lifter;
}
@Override
public void registerAsListener() {
}
@Override
public void unregisterAsListener() {
if (lifterCardIdentification != null) {
lifterCardIdentification.unregisterAsListener();
}
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
logger.trace("registering listeners");
// called on refresh
registerAsListener();
return null;
}
@Override
public void refresh() {
}
@Override
public boolean needsMenu() {
return false;
}
@Override
public void setParametersFromFragment() {
}
@Override
public String getFragment() {
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.util.Locale;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.PlatesInfoEvent.PlatesInfoListener;
import org.concordiainternational.competition.ui.SessionData.UpdateEvent;
import org.concordiainternational.competition.ui.SessionData.UpdateEventListener;
import org.concordiainternational.competition.ui.components.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.validator.IntegerValidator;
import com.vaadin.incubator.dashlayout.ui.HorDashLayout;
import com.vaadin.incubator.dashlayout.ui.VerDashLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
public class LoadWindow extends Window implements Property.ValueChangeListener,
Window.CloseListener, PlatesInfoListener {
private static final long serialVersionUID = 4907861433698426676L;
private static final Logger logger = LoggerFactory.getLogger(LoadWindow.class);
private GridLayout grid = null;
LifterInfo lifterCardIdentification;
boolean ignoreChanges;
private Item availablePlates;
private SessionData masterData;
private LoadImage imageArea;
private UpdateEventListener groupDataListener;
private Menu menu;
CompetitionApplication app;
public LoadWindow(Menu menu) {
super();
this.menu = menu;
final Locale locale = CompetitionApplication.getCurrentLocale();
app = CompetitionApplication.getCurrent();
masterData = app.getMasterData();
display(locale);
position();
registerAsListener(locale);
logger.debug("window {} created",this);
}
private void position() {
setPositionX(600);
setPositionY(100);
}
/**
* @param resizeButton
*/
private void resize(final Button resizeButton) {
if (grid.isVisible()) {
resizeButton.setCaption("-");
setWidth("45em");
setHeight("63ex");
} else {
resizeButton.setCaption("+");
setWidth("30em");
setHeight("38ex");
}
}
/**
* Listen to various events.
* {@link #unregisterAsListener()} undoes the registrations.
* @param locale
*/
private void registerAsListener(final Locale locale) {
// subwindow closes
addListener((CloseListener)this);
// main window closes
app.getMainWindow().addListener((CloseListener)this);
// changes to current lifter
groupDataListener = new SessionData.UpdateEventListener() {
@Override
public void updateEvent(UpdateEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
display(locale);
}
}).start();
}
};
masterData.addListener(groupDataListener);
// changes to plates available
masterData.addBlackBoardListener(this);
}
/**
* Clean-up listener registrations.
* Removes all listeners registered by {@link #registerAsListener(Locale)}
*/
public void unregisterAsListener() {
masterData.removeListener(groupDataListener);
CompetitionApplication.getCurrent().getMainWindow().removeListener((CloseListener)this);
masterData.removeBlackBoardListener(this);
menu.setLoadComputerWindow(null);
}
/**
* @param locale
*/
@SuppressWarnings("serial")
private void display(final Locale locale) {
CompetitionApplication app1 = CompetitionApplication.getCurrent();
Platform platform = masterData.getPlatform();
logger.debug("diplaying platform {} {}",platform.getName(),platform);
availablePlates = new BeanItem<Platform>(platform);
synchronized (app1) {
boolean gridIsVisible = (grid == null ? false : grid.isVisible());
removeAllComponents();
final int expectedBarWeight = computeOfficialBarWeight();
this.setSizeFull();
VerticalLayout root = new VerDashLayout();
HorizontalLayout top = new HorDashLayout();
imageArea = new LoadImage(this);
final Button resizeButton = new Button();
resizeButton.addListener(new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
grid.setVisible(!grid.isVisible());
resize(resizeButton);
}
});
Form liftGrid = createGrid(locale, expectedBarWeight);
grid.setVisible(gridIsVisible);
grid.setMargin(false);
root.addComponent(top);
root.addComponent(liftGrid);
imageArea.computeImageArea(masterData, platform);
resize(resizeButton);
top.setSizeFull();
top.addComponent(imageArea);
top.setComponentAlignment(imageArea, Alignment.MIDDLE_CENTER);
top.addComponent(resizeButton);
top.setComponentAlignment(resizeButton, Alignment.BOTTOM_LEFT);
top.setExpandRatio(resizeButton, 0);
top.setMargin(true);
top.setExpandRatio(imageArea, 100);
this.addComponent(root);
this.addStyleName("light");
this.addStyleName("platesPopup");
}
app1.push();
}
@Override
public void close() {
super.close();
unregisterAsListener();
}
/**
* Create the grid where the number of available plates is shown.
*
* @param locale
* @param expectedBarWeight
* @return
*/
private Form createGrid(Locale locale, int expectedBarWeight) {
grid = new GridLayout(10, 5);
Form liftGrid = new Form(grid);
createGridContents(locale, expectedBarWeight);
liftGrid.setWriteThrough(true);
grid.setSpacing(true);
return liftGrid;
}
/**
* Create the header row and the header column.
*
* @param locale
* @param expectedBarWeight
*/
private void createGridContents(Locale locale, int expectedBarWeight) {
// first row
int column = 1;
int row = 0;
addLabel(new Label("0,5"), column++, row); //$NON-NLS-1$
addLabel(new Label("1"), column++, row); //$NON-NLS-1$
addLabel(new Label("1,5"), column++, row); //$NON-NLS-1$
addLabel(new Label("2"), column++, row); //$NON-NLS-1$
addLabel(new Label("2.5"), column++, row); //$NON-NLS-1$
addLabel(new Label("5"), column++, row); //$NON-NLS-1$
addLabel(new Label(Messages.getString("LoadComputer.Collar", locale)), column++, row); //$NON-NLS-1$
// second row
column = 1;
row = 1;
// metal plates
bindGridCell("nbS_0_5", column++, row); //$NON-NLS-1$
bindGridCell("nbS_1", column++, row); //$NON-NLS-1$
bindGridCell("nbS_1_5", column++, row); //$NON-NLS-1$
bindGridCell("nbS_2", column++, row); //$NON-NLS-1$
bindGridCell("nbS_2_5", column++, row); //$NON-NLS-1$
bindGridCell("nbS_5", column++, row); //$NON-NLS-1$
// collar
bindGridCell("nbC_2_5", column++, row); //$NON-NLS-1$
// third row
column = 1;
row = 2;
addLabel(new Label("2,5"), column++, row); //$NON-NLS-1$
addLabel(new Label("5"), column++, row); //$NON-NLS-1$
addLabel(new Label("10"), column++, row); //$NON-NLS-1$
addLabel(new Label("15"), column++, row); //$NON-NLS-1$
addLabel(new Label("20"), column++, row); //$NON-NLS-1$
addLabel(new Label("25"), column++, row); //$NON-NLS-1$
addLabel(new Label(Messages.getString("LoadComputer.Bar", locale)), column++, row); //$NON-NLS-1$
addLabel(new Label(Messages.getString("LoadComputer.NonStandardBar", locale)), column++, row); //$NON-NLS-1$
// bumper plates
column = 1;
row = 3;
bindGridCell("nbL_2_5", column++, row); //$NON-NLS-1$
bindGridCell("nbL_5", column++, row); //$NON-NLS-1$
bindGridCell("nbL_10", column++, row); //$NON-NLS-1$
bindGridCell("nbL_15", column++, row); //$NON-NLS-1$
bindGridCell("nbL_20", column++, row); //$NON-NLS-1$
bindGridCell("nbL_25", column++, row); //$NON-NLS-1$
// bar
Field officialBar = bindGridCell("officialBar", column++, row); //$NON-NLS-1$
Field lightBar = bindGridCell("lightBar", column++, row); //$NON-NLS-1
if (Integer.parseInt((String) lightBar.getValue()) > 0) {
officialBar.setValue("0");
} else {
officialBar.setValue(Integer.toString(expectedBarWeight));
}
// first column
addLabel(new Label(Messages.getString("LoadComputer.MetalPlates", locale)), 0, 1); //$NON-NLS-1$
addLabel(new Label(Messages.getString("LoadComputer.BumperPlates", locale)), 0, 3); //$NON-NLS-1$
// 15 characters wide.
addLabel(new Label(), 0, 0);
grid.getComponent(0, 0).setWidth("15ex"); //$NON-NLS-1$
}
private void addLabel(Label label, int column, int row) {
grid.addComponent(label, column, row);
}
/**
* Create empty fields for all the cells.
*
* @param app
*/
private Field createIntegerField(int column, int row, Locale locale) {
Field field = null;
field = new TextField();
((TextField) field).setWidth("2.5em"); //$NON-NLS-1$
field.addValidator(new IntegerValidator(Messages.getString("LifterCardEditor.integerExpected", locale) //$NON-NLS-1$
));
grid.addComponent(field, column, row);
return field;
}
/**
* Utility routine to associate a grid cell with an availablePlates field through a
* property.
*
* @param propertyId
* @param column
* @param row
*/
private Field bindGridCell(Object propertyId, int column, int row) {
Field component = (Field) grid.getComponent(column, row);
if (component == null) {
component = createIntegerField(column, row, CompetitionApplication.getCurrentLocale());
}
component.setPropertyDataSource(availablePlates.getItemProperty(propertyId));
component.addListener((ValueChangeListener) this);
component.setWriteThrough(true);
component.setReadOnly(false);
((TextField) component).setImmediate(true);
return component;
}
/*
* Event received when any of the cells in the form has changed. We need to
* recompute the dependent cells (non-Javadoc)
*
* @see
* com.vaadin.data.Property.ValueChangeListener#valueChange(com.vaadin.data
* .Property.ValueChangeEvent)
*/
@Override
public void valueChange(Property.ValueChangeEvent event) {
// prevent triggering if called recursively or during initial display
// prior to editing.
if (ignoreChanges) {
logger.debug("listener in window {} ignoring event",this);
return;
}
boolean prevIgnoreChanges = ignoreChanges;
try {
logger.debug("listener in window {} notified",this);
ignoreChanges = true;
// this means that an editable property has changed in the form; refresh
// all the computed ones.
if (event != null) logger.debug(event.getProperty().toString());
// manage field interdependencies.
final Integer lightBar = (Integer) availablePlates.getItemProperty("lightBar").getValue();
if (lightBar != 0) {
availablePlates.getItemProperty("officialBar").setValue("0");
} else {
availablePlates.getItemProperty("officialBar").setValue(computeOfficialBarWeight());
}
CompetitionApplication.getCurrent().getHbnSession().merge(masterData.getPlatform());
//logger.debug("value change, after merge, collars: {}",masterData.getPlatform().getNbC_2_5());
imageArea.computeImageArea(masterData, masterData.getPlatform());
masterData.fireBlackBoardEvent(new PlatesInfoEvent(this));
} finally {
ignoreChanges = prevIgnoreChanges;
}
}
/**
* @return
*/
private Integer computeOfficialBarWeight() {
final Lifter currentLifter = masterData.getCurrentLifter();
String gender = "M";
if (currentLifter != null) {
gender = currentLifter.getGender();
}
final int expectedBarWeight = "M".equals(gender) ? 20 : 15;
return expectedBarWeight;
}
@Override
public void windowClose(CloseEvent e) {
logger.debug("plates subwindow closed");
if (e.getWindow() == this) {
unregisterAsListener();
}
}
/* Refresh when someone has updated plate loading information in another window.
* @see org.concordiainternational.competition.ui.PlatesInfoEvent.PlatesInfoListener#plateLoadingUpdate(org.concordiainternational.competition.ui.PlatesInfoEvent)
*/
@Override
public void plateLoadingUpdate(PlatesInfoEvent event) {
if (event.source != this) {
logger.debug("event from {} received in {}",event.source,this);
boolean prevIgnoreChanges = ignoreChanges;
try {
ignoreChanges = true;
display(app.getLocale());
} finally {
ignoreChanges = prevIgnoreChanges;
}
} else {
logger.debug("event from {} ignored by self.",event.source);
}
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.DecisionLightsWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class RefereeTesting extends VerticalSplitPanel implements ApplicationView, CloseListener, URIHandler {
private static final String CELL_WIDTH = "8em";
private static final long serialVersionUID = 1L;
GridLayout bottom;
SessionData masterData;
CompetitionApplication app = CompetitionApplication.getCurrent();
@SuppressWarnings("unused")
private Logger logger = LoggerFactory.getLogger(RefereeTesting.class);
private String platformName;
private String viewName;
private DecisionLightsWindow decisionArea;
RefereeTesting(boolean initFromFragment, String viewName, boolean juryMode, boolean publicFacing) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.app = CompetitionApplication.getCurrent();
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
createLights();
HorizontalLayout top = new HorizontalLayout();
top.setSizeFull();
top.setStyleName("decisionLightsWindow");
top.addComponent(decisionArea);
this.setFirstComponent(top);
bottom = createDecisionButtons();
this.setSecondComponent(bottom);
setSplitPosition(75);
resetBottom();
// URI handler must remain, so is not part of the register/unRegister paire
app.getMainWindow().addURIHandler(this);
registerAsListener();
}
/**
*
*/
private void createLights() {
masterData = app.getMasterData(platformName);
decisionArea = new DecisionLightsWindow(false, true);
masterData.getRefereeDecisionController().addListener(decisionArea);
decisionArea.setSizeFull(); //$NON-NLS-1$
//decisionArea.setHeight("35em");
}
private GridLayout createDecisionButtons() {
GridLayout bottom1 = new GridLayout(3, 3);
bottom1.setMargin(true);
bottom1.setSpacing(true);
createLabel(bottom1, refereeLabel(0));
createLabel(bottom1, refereeLabel(1));
createLabel(bottom1, refereeLabel(2));
for (int i = 0; i < 3; i++) {
final int j = i;
final NativeButton yesButton = new NativeButton("oui", new ClickListener() {
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
masterData.getRefereeDecisionController().decisionMade(j, true);
}
});
yesButton.addStyleName("referee"); //$NON-NLS-1$
yesButton.addStyleName("yesButton"); //$NON-NLS-1$
yesButton.setWidth(CELL_WIDTH);
bottom1.addComponent(yesButton);
}
for (int i = 0; i < 3; i++) {
final int j = i;
final NativeButton noButton = new NativeButton("non", new ClickListener() {
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
masterData.getRefereeDecisionController().decisionMade(j, false);
}
});
noButton.addStyleName("referee"); //$NON-NLS-1$
noButton.addStyleName("noButton"); //$NON-NLS-1$
noButton.setWidth(CELL_WIDTH);
bottom1.addComponent(noButton);
}
return bottom1;
}
/**
* @param bottom1
* @param width
*/
private void createLabel(GridLayout bottom1, String caption) {
final Label ref1Label = new Label("");
ref1Label.setCaption(caption);
ref1Label.setWidth(CELL_WIDTH);
ref1Label.addStyleName("refereeButtonLabel");
bottom1.addComponent(ref1Label);
}
private void resetBottom() {
synchronized (app) {
for (int i = 0; i < 3; i++) {
((Label) bottom.getComponent(i, 0)).setValue(" ");
}
}
app.push();
}
@Override
public void refresh() {
}
/**
* @param refereeIndex2
* @return
*/
private String refereeLabel(int refereeIndex2) {
return Messages.getString("RefereeConsole.Referee", CompetitionApplication.getCurrentLocale()) + " "
+ (refereeIndex2 + 1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+(platformName == null ? "" : platformName);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
@Override
public void setParametersFromFragment() {
String frag = CompetitionApplication.getCurrent().getUriFragmentUtility().getFragment();
String[] params = frag.split("/");
if (params.length >= 1) {
viewName = params[0];
} else {
throw new RuleViolationException("Error.ViewNameIsMissing");
}
if (params.length >= 2) {
platformName = params[1];
} else {
platformName = CompetitionApplicationComponents.initPlatformName();
}
}
@Override
public void registerAsListener() {
masterData.getRefereeDecisionController().addListener(decisionArea);
}
@Override
public void unregisterAsListener() {
masterData.getRefereeDecisionController().removeListener(decisionArea);
}
/* Unregister listeners when window is closed.
* @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window.CloseEvent)
*/
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
//logger.debug("re-registering handlers for {} {}",this,relativeUri);
registerAsListener();
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Locale;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import org.concordiainternational.competition.decision.Sound;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.timer.CountdownTimer;
import org.concordiainternational.competition.timer.CountdownTimerListener;
import org.concordiainternational.competition.ui.AnnouncerView.Mode;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.TimerControls;
import org.concordiainternational.competition.ui.generators.TimeFormatter;
import org.concordiainternational.competition.ui.generators.TryFormatter;
import org.concordiainternational.competition.webapp.WebApplicationConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.notifique.Notifique;
import org.vaadin.notifique.Notifique.Message;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.MethodProperty;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.Resource;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
/**
* Display information regarding the current lifter
*
* REFACTOR This class badly needs refactoring, as it is used in 6 different settings (3
* announcer views, the result editing page, the lifter display, the lifter card
* editor).
*
* @author jflamy
*
*/
public class LifterInfo extends VerticalLayout implements
CountdownTimerListener,
DecisionEventListener,
ApplicationView
{
static final Logger logger = LoggerFactory.getLogger(LifterInfo.class);
static final Logger timingLogger = LoggerFactory
.getLogger("org.concordiainternational.competition.timer.TimingLogger"); //$NON-NLS-1$
private static final long serialVersionUID = -3687013148334708795L;
public Locale locale;
public String identifier;
private SessionData groupData;
private Label timerDisplay;
private CompetitionApplication app;
private Mode mode;
private CheckBox actAsTimekeeper = new CheckBox();
private CheckBox automaticStartTime = new CheckBox(); //$NON-NLS-1$
private Boolean showTimerControls = false;
private Boolean startTimeAutomatically = false;
private Component parentView;
private Lifter lifter = null;
private Lifter prevLifter = null;
private Integer prevAttempt = null;
private Integer prevWeight = null;
private long lastOkButtonClick = 0L;
private long lastFailedButtonClick = 0L;
private SessionData sessionData;
protected DecisionEvent prevEvent;
@SuppressWarnings("serial")
public LifterInfo(String identifier, final SessionData groupData, AnnouncerView.Mode mode, Component parentView) {
final CompetitionApplication currentApp = CompetitionApplication.getCurrent();
this.app = currentApp;
this.locale = currentApp.getLocale();
this.identifier = identifier;
this.groupData = groupData;
this.parentView = parentView;
this.mode = mode;
this.sessionData = groupData;
this.addListener(new LayoutClickListener() {
@Override
public void layoutClick(LayoutClickEvent event) {
// if the announcer clicks on the name, then send again to NEC
// display
// test for announcer view done in updateDisplayBoard.
Component child = event.getChildComponent();
if (child != null && child instanceof Label && "lifter".equals(((AbstractComponent) child).getData())) {
updateDisplayBoard(lifter, groupData);
}
}
});
// URI handler must remain, so is not part of the register/unRegister pair
app.getMainWindow().addURIHandler(this);
registerAsListener();
}
@Override
public String toString() {
return identifier + "_" + System.identityHashCode(this); //$NON-NLS-1$
}
/**
* Display the information about the lifter Also displays the buttons to
* manage timer.
*
* @param lifter1
* @param groupData1
*/
public void loadLifter(final Lifter lifter1, final SessionData groupData1) {
logger.debug("LifterInfo.loadLifter() begin: newLifter = {} previousLifter = {}", lifter1, prevLifter); //$NON-NLS-1$
synchronized (app) {
// make sure that groupData listens to changes relating to the lifter
// since the buttons trigger changes within the data (e.g.
// successfulLift)
if (parentView instanceof AnnouncerView) {
if ((((AnnouncerView) parentView).mode == Mode.ANNOUNCER && isTop())) { //$NON-NLS-1$
groupData1.trackEditors(lifter1, this.lifter, this);
}
}
// don't work for nothing, avoid stutter on the screen.
// we have to compare the attributes as last displayed.
if (lifter1 != null) {
if (lifter1 == prevLifter
&& lifter1.getAttemptsDone() == prevAttempt
&& lifter1.getNextAttemptRequestedWeight() == prevWeight) {
return; // we are already showing correct information.
}
prevLifter = lifter1;
prevAttempt = lifter1.getAttemptsDone();
prevWeight = lifter1.getNextAttemptRequestedWeight();
}
// prepare new display.
this.removeAllComponents();
if (lifter1 == null)
return;
updateDisplayBoard(lifter1, groupData1);
StringBuilder sb = new StringBuilder();
boolean done = getHTMLLifterInfo(lifter1,
isBottom(), sb); //$NON-NLS-1$
final Label label = new Label(sb.toString(), Label.CONTENT_XHTML);
label.addStyleName("zoomable");
label.setData("lifter");
this.addComponent(label);
this.setSpacing(true);
if (isBottom()) {
bottomDisplayOptions(lifter1, groupData1);
}
if (done)
return; // lifter has already performed all lifts.
if (lifter1.isCurrentLifter() && isTop()) { //$NON-NLS-1$
topDisplayOptions(lifter1, groupData1);
} else if (isDisplay()) { //$NON-NLS-1$
currentLifterDisplayOptions(lifter1, groupData1);
}
}
app.push();
this.lifter = lifter1;
logger.debug("LifterInfo.loadLifter() end: " + lifter1.getLastName()); //$NON-NLS-1$
}
/**
* @param sb
* @return
*/
public boolean getHTMLLifterInfo(Lifter lifter1, boolean alwaysShowName, StringBuilder sb) {
final int currentTry = 1 + (lifter1.getAttemptsDone() >= 3 ? lifter1.getCleanJerkAttemptsDone() : lifter1.getSnatchAttemptsDone());
boolean done = currentTry > 3;
// display requested weight
if (done) {
appendDiv(sb, "break", " "); //$NON-NLS-1$ //$NON-NLS-2$
done = true;
} else {
appendDiv(sb, "weight", lifter1.getNextAttemptRequestedWeight() + Messages.getString("Common.kg", locale)); //$NON-NLS-1$ //$NON-NLS-2$
}
appendDiv(sb, "break", " "); //$NON-NLS-1$ //$NON-NLS-2$
// display lifter name and affiliation
if (!done || alwaysShowName) {
appendDiv(sb, lifter1.getLastName().toUpperCase());
appendDiv(sb, lifter1.getFirstName());
appendDiv(sb, lifter1.getClub());
appendDiv(sb, "break", " "); //$NON-NLS-1$ //$NON-NLS-2$
}
// display current attempt number
if (done) {
CompetitionSession currentSession = sessionData.getCurrentSession();
if (currentSession != null) {
// we're done, write a "finished" message and return.
appendDiv(sb, MessageFormat.format(Messages.getString("LifterInfo.Done", locale),currentSession.getName() )); //$NON-NLS-1$
} else {
// do nothing.
}
} else {
//appendDiv(sb, lifter.getNextAttemptRequestedWeight()+Messages.getString("Common.kg",locale)); //$NON-NLS-1$
String tryInfo = TryFormatter.formatTry(lifter1, locale, currentTry);
appendDiv(sb, tryInfo);
}
return done;
}
/**
* @param lifter1
* @param groupData1
*/
private void updateDisplayBoard(final Lifter lifter1, final SessionData groupData1) {
logger.trace("loadLifter prior to updateNEC {} {} {} ", new Object[] { identifier, parentView, mode }); //$NON-NLS-1$
if (isTop() && parentView == groupData1.getAnnouncerView() && mode == Mode.ANNOUNCER) { //$NON-NLS-1$
updateNECOnWeightChange(lifter1, groupData1);
}
logger.trace("loadLifter after updateNEC"); //$NON-NLS-1$
}
/**
* Update the NEC Display.
*
* Changed weight.
*
* @param lifter1
* @param groupData1
*/
private void updateNECOnWeightChange(final Lifter lifter1, final SessionData groupData1) {
// top part of announcer view drives electronic display
if (groupData1.needToUpdateNEC) {
if (WebApplicationConfiguration.NECShowsLifterImmediately) {
groupData1.displayLifterInfo(lifter1);
} else {
final Lifter currentLifter = groupData1.getNECDisplay().getCurrentLifter();
logger.trace("lifter = {} currentLifter={}", lifter1, currentLifter); //$NON-NLS-1$
if (currentLifter != null && currentLifter.equals(lifter1)) {
groupData1.displayLifterInfo(lifter1);
} else {
groupData1.displayWeight(lifter1);
}
}
}
}
private FormLayout timekeeperOptions() {
actAsTimekeeper.setCaption(Messages.getString("LifterInfo.actAsTimeKeeper", locale)); //$NON-NLS-1$
automaticStartTime.setCaption(Messages.getString("LifterInfo.automaticStartTime", locale)); //$NON-NLS-1$
automaticStartTime.setValue(groupData.getStartTimeAutomatically());
actAsTimekeeper.setValue(showTimerControls);
FormLayout options = new FormLayout();
actAsTimekeeper.setImmediate(true);
automaticStartTime.setImmediate(true);
automaticStartTime.setVisible(showTimerControls);
actAsTimekeeper.addListener(new ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
showTimerControls = (Boolean) event.getProperty().getValue();
if (showTimerControls) {
automaticStartTime.setValue(false);
automaticStartTime.setVisible(showTimerControls);
timerControls.showTimerControls(groupData.getTimer().isRunning());
} else {
automaticStartTime.setVisible(false);
timerControls.hideTimerControls();
groupData.setStartTimeAutomatically(false);
}
}
});
automaticStartTime.addListener(new ValueChangeListener() {
private static final long serialVersionUID = 1L;
@Override
public void valueChange(ValueChangeEvent event) {
startTimeAutomatically = (Boolean) event.getProperty().getValue();
if (startTimeAutomatically) {
groupData.setStartTimeAutomatically(true);
} else {
groupData.setStartTimeAutomatically(false);
}
}
});
options.setWidth("30ex"); //$NON-NLS-1$
options.addComponent(actAsTimekeeper);
options.addComponent(automaticStartTime);
return options;
}
TimerControls timerControls;
private boolean blocked = true;
/**
* Display remaining time and timer controls
*
* @param lifter1
* @param groupData1
*/
private void topDisplayOptions(final Lifter lifter1, final SessionData groupData1) {
createTimerDisplay(groupData1);
if (timerControls != null) timerControls.unregisterListeners();
timerControls = new TimerControls(lifter1, groupData1, true, mode, this, showTimerControls, app);
this.addComponent(new Label());
this.addComponent(timerControls);
if (mode == Mode.ANNOUNCER) {
FormLayout timekeeperOptions = timekeeperOptions();
this.addComponent(timekeeperOptions);
}
}
/**
* Additional things to display in the lifter editor.
*
* @param groupData1
*/
@SuppressWarnings("serial")
private void bottomDisplayOptions(final Lifter lifter1, final SessionData groupData1) {
if (parentView instanceof ResultView) {
FormLayout customScoreFL = new FormLayout();
TextField field = new TextField(Messages.getString("LifterInfo.customScore",CompetitionApplication.getCurrentLocale()));
field.setWidth("5em");
customScoreFL.addComponent(field);
field.setPropertyDataSource(new MethodProperty<Lifter>(lifter1, "customScore"));
field.setImmediate(true);
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
((ResultView)parentView).getResultList().getGroupData().persistPojo(lifter1);
}
});
this.addComponent(customScoreFL);
}
}
/**
* Display remaining time
*
* @param lifter2
* @param groupData2
*/
private void currentLifterDisplayOptions(Lifter lifter2, SessionData groupData2) {
createTimerDisplay(groupData2);
}
/**
* @param groupData1
*/
private void createTimerDisplay(final SessionData groupData1) {
timerDisplay = new Label();
timerDisplay.addStyleName("zoomable");
timerDisplay.addStyleName("timerDisplay");
// we set the value to the time allowed for the current lifter as
// computed by groupData
int timeAllowed = groupData1.getDisplayTime(); // was getTimeAllowed();
final CountdownTimer timer = groupData1.getTimer();
final boolean running = timer.isRunning();
logger.debug("timeAllowed={} timer.isRunning()={}", timeAllowed, running); //$NON-NLS-1$
if (!running) {
timerDisplay.setValue(TimeFormatter.formatAsSeconds(timeAllowed));
timerDisplay.setEnabled(false); // greyed out.
}
this.addComponent(timerDisplay);
}
int prevTimeRemaining = 0;
protected boolean shown;
@Override
public void normalTick(int timeRemaining) {
if (timerDisplay == null) {
setBlocked(false);
return;
} else if (TimeFormatter.getSeconds(prevTimeRemaining) == TimeFormatter.getSeconds(timeRemaining)) {
prevTimeRemaining = timeRemaining;
setBlocked(false);
return;
} else {
prevTimeRemaining = timeRemaining;
}
synchronized (app) {
if (!isBlocked()) {
timerDisplay.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
timerDisplay.setEnabled(true);
}
setBlocked(false);
}
app.push();
}
@Override
public void finalWarning(int remaining) {
SessionData masterData = app.getMasterData(app.getPlatformName());
logger.trace("final warning, {}", isMasterConsole(masterData));
if (timerDisplay == null) return;
prevTimeRemaining = remaining;
synchronized (app) {
if (!isBlocked()) {
timerDisplay.setValue(TimeFormatter.formatAsSeconds(remaining));
// final ClassResource resource = new ClassResource("/sounds/finalWarning.mp3", app); //$NON-NLS-1$
// playSound(resource);
playSound("/sounds/finalWarning2.wav");
}
setBlocked(false);
}
app.push();
}
@Override
public void initialWarning(int remaining) {
if (timerDisplay == null) return;
prevTimeRemaining = remaining;
synchronized (app) {
if (!isBlocked()) {
timerDisplay.setValue(TimeFormatter.formatAsSeconds(remaining));
// final ClassResource resource = new ClassResource("/sounds/initialWarning.mp3", app); //$NON-NLS-1$
// playSound(resource);
playSound("/sounds/initialWarning2.wav");
}
setBlocked(false);
}
app.push();
}
// /**
// * @param resource
// */
// @SuppressWarnings("unused")
// private void playSound(final ClassResource resource) {
// SessionData masterData = app.getMasterData(app.getPlatformName());
// if (isMasterConsole(masterData)) {
// // we are not the master application; do not play
// app.getBuzzer().play(resource);
// logger.debug("! {} is master, playing sound", app); //$NON-NLS-1$
// } else {
// logger.debug("- {} not master, not playing sound", app); //$NON-NLS-1$
// }
//
// }
private void playSound(String soundName) {
SessionData masterData = app.getMasterData(app.getPlatformName());
if (isMasterConsole(masterData)) {
new Sound(masterData.getPlatform().getMixer(),soundName).emit();
logger.debug("! {} is master, playing sound", app); //$NON-NLS-1$
} else {
// we are not the master application; do not play
logger.debug("- {} not master, not playing sound", app); //$NON-NLS-1$
}
}
/**
* @param masterData
* @return
*/
private boolean isMasterConsole(SessionData masterData) {
return app == masterData.getMasterApplication();
}
@Override
public void noTimeLeft(int remaining) {
if (timerDisplay == null) return;
prevTimeRemaining = remaining;
synchronized (app) {
if (!isBlocked()) {
timerDisplay.setValue(TimeFormatter.formatAsSeconds(remaining));
// final ClassResource resource = new ClassResource("/sounds/timeOver.mp3", app); //$NON-NLS-1$
// playSound(resource);
playSound("/sounds/timeOver2.wav");
if (timerDisplay != null) {
timerDisplay.setEnabled(false);
}
}
setBlocked(false);
}
app.push();
}
@Override
public void forceTimeRemaining(int remaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
if (timerDisplay == null) return;
prevTimeRemaining = remaining;
synchronized (app) {
timerDisplay.setEnabled(false); // show that timer has stopped.
timerDisplay.setValue(TimeFormatter.formatAsSeconds(remaining));
timerControls.enableStopStart(false);
setBlocked(false);
}
showNotification(originatingApp, reason);
app.push();
}
@Override
public void pause(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
setBlocked(true); // don't process the next update from the timer.
synchronized (app) {
if (timerControls != null) {
timerControls.enableStopStart(false);
}
if (timerDisplay != null) {
timerDisplay.setEnabled(false);
}
}
showNotification(originatingApp, reason);
app.push();
}
/**
* Show a notification on other consoles.
* Notification is shown for actors other than the time keeper (when the announcer or marshall stops the time
* through a weight change).
*
* @param originatingApp
* @param reason
*/
private void showNotification(CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
if (isTop() && app != originatingApp) {
CompetitionApplication receivingApp = app;
// defensive
String originatingPlatformName = originatingApp.components.getPlatformName();
String receivingPlatformName = receivingApp.components.getPlatformName();
if (! originatingPlatformName.equals(receivingPlatformName)) {
logger.error("event from platform {} sent to {}",originatingPlatformName, receivingPlatformName);
traceBack(originatingApp);
}
if (receivingApp.components.currentView instanceof AnnouncerView && reason != TimeStoppedNotificationReason.UNKNOWN) {
AnnouncerView receivingView = (AnnouncerView) receivingApp.components.currentView;
ApplicationView originatingAppView = originatingApp.components.currentView;
if (originatingAppView instanceof AnnouncerView) {
AnnouncerView originatingView = (AnnouncerView)originatingAppView;
if (originatingView.mode != receivingView.mode
&& originatingView.mode != Mode.TIMEKEEPER) {
traceBack(originatingApp);
receivingView.displayNotification(originatingView.mode,reason);
}
} else {
traceBack(originatingApp);
receivingView.displayNotification(null,reason);
}
}
}
}
/**
* @param originatingApp
*/
private void traceBack(CompetitionApplication originatingApp) {
// logger.trace("showNotification in {} from {}",app,originatingApp);
// LoggerUtils.logException(logger, new Exception("where"));
}
@Override
public void start(int timeRemaining) {
setBlocked(false);
synchronized (app) {
if (timerControls != null) timerControls.enableStopStart(true);
if (timerDisplay != null) {
timerDisplay.setEnabled(true);
}
}
app.push();
}
@Override
public void stop(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
setBlocked(true); // don't process the next update from the timer.
synchronized (app) {
if (timerControls != null) timerControls.enableStopStart(false);
if (timerDisplay != null) {
timerDisplay.setEnabled(false);
}
}
showNotification(originatingApp, reason);
app.push();
}
/**
* Prevent the timer listeners from updating the timer and emitting sounds;
* Called by the timer controls as soon as the user clicks. This is because
* of race conditions: - there is a delay in propagating the events - the
* timer update can occur after the updateList() routine has updated the
* remaining time - the bell could ring just after the timekeeper has
* clicked to stop.
*
* @param blocked
* if true, stop paying attention to timer
*/
public void setBlocked(boolean blocked) {
if (blocked != this.blocked) {
this.blocked = blocked;
// logger.trace("app {} blocked={}",app,blocked);
}
}
/**
* @return the blocked
*/
private boolean isBlocked() {
return blocked;
}
/**
* @param lastOkButtonClick
* the lastOkButtonClick to set
*/
public void setLastOkButtonClick(long lastOkButtonClick) {
this.lastOkButtonClick = lastOkButtonClick;
}
/**
* @return the lastOkButtonClick
*/
public long getLastOkButtonClick() {
return lastOkButtonClick;
}
/**
* @param lastFailedButtonClick
* the lastFailedButtonClick to set
*/
public void setLastFailedButtonClick(long lastFailedButtonClick) {
this.lastFailedButtonClick = lastFailedButtonClick;
}
/**
* @return the lastFailedButtonClick
*/
public long getLastFailedButtonClick() {
return lastFailedButtonClick;
}
private void appendDiv(StringBuilder sb, String string) {
sb.append("<div>") //$NON-NLS-1$
.append(string).append("</div>"); //$NON-NLS-1$
}
private void appendDiv(StringBuilder sb, String cssClass, String string) {
sb.append("<div class='" + cssClass + "'>") //$NON-NLS-1$ //$NON-NLS-2$
.append(string).append("</div>"); //$NON-NLS-1$
}
/**
* Display referee decisions
* @see org.concordiainternational.competition.decision.DecisionEventListener#updateEvent(org.concordiainternational.competition.decision.DecisionEvent)
*/
@Override
public void updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
// show a notification
// only the master console is registered for these events.
logger.trace("received event {}",updateEvent);
switch (updateEvent.getType()) {
case SHOW:
shown = true;
displayNotification(updateEvent);
if (timerControls != null) { timerControls.hideLiftControls(); }
break;
// go on to UPDATE;
case UPDATE:
if (shown) {
displayNotification(updateEvent);
}
break;
case RESET:
shown = false;
prevEvent = null;
if (timerControls != null) { timerControls.showLiftControls(); }
break;
}
}
/**
* @param newEvent
*/
protected void displayNotification(final DecisionEvent newEvent) {
synchronized (app) {
final ApplicationView currentView = app.components.currentView;
if (currentView instanceof AnnouncerView) {
if (stutteringEvent(newEvent,prevEvent)) {
prevEvent = newEvent;
logger.trace("A NO notification for {}",newEvent);
logger.trace("A prevEvent={}",prevEvent);
return;
}
prevEvent = newEvent;
logger.trace("B prevEvent={}",prevEvent);
final AnnouncerView announcerView = (AnnouncerView)currentView;
Notifique notifications = announcerView.getNotifications();
String style;
String message;
final Boolean accepted = newEvent.isAccepted();
logger.trace("B YES notification for {} accepted={}",newEvent,accepted);
if (accepted != null) {
final Lifter lifter2 = newEvent.getLifter();
final String name = (lifter2 != null ?lifter2.getLastName().toUpperCase()+" "+lifter2.getFirstName() : "_");
if (accepted) {
style = "owlcms-white";
message = MessageFormat.format(Messages.getString("Decision.lift", locale),name);
} else {
style = "owlcms-red";
message = MessageFormat.format(Messages.getString("Decision.noLift", locale),name);
}
final Message addedMessage = notifications.add((Resource)null,message,true,style,true);
announcerView.scheduleMessageRemoval(addedMessage, 10000);
}
}
}
app.push();
}
/**
* @param curEvent
* @param prevEvent1
* @return true if the two events concern the same lifter and the same attempt and give the same decision
*/
private boolean stutteringEvent(DecisionEvent curEvent,
DecisionEvent prevEvent1) {
logger.trace("curEvent={} prevEvent={}",curEvent,prevEvent1);
if (curEvent != null && prevEvent1 != null) {
Lifter cur = updateEvent.getLifter();
Lifter prev = prevEvent1.getLifter();
if (cur != null && prev != null) {
if (cur != prev) {
return false;
}
logger.trace("same lifter");
Integer curAtt = cur.getAttemptsDone();
Integer prevAtt = cur.getAttemptsDone();
if (curAtt != null && prevAtt != null) {
if (!curAtt.equals(prevAtt)){
return false;
}
logger.trace("same attempt");
Boolean prevDecision = prevEvent1.isAccepted();
Boolean curDecision = curEvent.isAccepted();
if (prevDecision != null && curDecision != null) {
logger.trace("prevDecision={} curDecision={}",prevDecision,curDecision);
return prevDecision.equals(curDecision);
} else {
final boolean b = prevDecision == null && curDecision == null;
logger.trace("either decision is null prevDecision={} curDecision={}",prevDecision,curDecision);
return b;
}
} else {
final boolean b = curAtt == null && prevAtt == null;
logger.trace("either attempt is null prevAtt={} curAtt={}",prevAtt,curAtt);
return b;
}
} else {
final boolean b = cur == null && prev == null;
logger.trace("either lifter is null prev={} cur={}",prev,cur);
return b;
}
} else {
final boolean b = curEvent == null && prevEvent1 == null;
logger.trace("either event is null prevEvent1={} curEvent={}",prevEvent1,curEvent);
return b;
}
}
}).start();
}
/**
* @return
*/
private boolean isTop() {
return identifier.startsWith("top");
}
/**
* @return
*/
private boolean isBottom() {
return identifier.startsWith("bottom");
}
/**
* @return
*/
private boolean isDisplay() {
return identifier.startsWith("display");
}
/**
* Register as listener to various events.
*/
@Override
public void registerAsListener() {
// window close
final Window mainWindow = app.getMainWindow();
logger.debug("window: {} register for {} {}",
new Object[]{mainWindow,identifier,this});
mainWindow.addListener(this);
final CompetitionApplication masterApplication = groupData.getMasterApplication();
CountdownTimer timer = groupData.getTimer();
// if several instances of lifter information are shown on page, only top one buzzes.
if (masterApplication == app && isTop()) {
// down signal (for buzzer)
groupData.getRefereeDecisionController().addListener(this);
// timer will buzz on this console
// TODO: now obsolete? - javax.sound is used from server
if (timer != null) timer.setMasterBuzzer(this);
}
// timer countdown events; bottom information does not show timer.
// if already master buzzer, do not register twice.
if (timer != null && ! isBottom() && !(timer.getMasterBuzzer() == this)) {
timer.addListener(this);
}
}
@Override
public void unregisterAsListener() {
// window close
final Window mainWindow = app.getMainWindow();
logger.debug("window: {} UNregister for {} {}",
new Object[]{mainWindow,identifier,this});
mainWindow.removeListener(this);
// cleanup referee decision listening.
CountdownTimer timer = groupData.getTimer();
groupData.getRefereeDecisionController().removeListener(this);
if (timer != null && timer.getMasterBuzzer() == this) timer.setMasterBuzzer(null);
// timer countdown events
if (timer != null) timer.removeListener(this);
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
logger.trace("registering listeners");
// called on refresh
registerAsListener();
return null;
}
@Override
public void refresh() {
}
@Override
public boolean needsMenu() {
return false;
}
@Override
public void setParametersFromFragment() {
}
@Override
public String getFragment() {
return null;
}
}
| Java |
/*
* Copyright 2009-2012, Jean-François Lamy
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.concordiainternational.competition.ui;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.mobile.IRefereeConsole;
import org.concordiainternational.competition.mobile.MJuryConsole;
import org.concordiainternational.competition.mobile.MPlatesInfoView;
import org.concordiainternational.competition.mobile.MRefereeConsole;
import org.concordiainternational.competition.mobile.RefereeDecisions;
import org.concordiainternational.competition.spreadsheet.SpreadsheetUploader;
import org.concordiainternational.competition.ui.AnnouncerView.Mode;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.components.Menu;
import org.concordiainternational.competition.ui.components.ResultFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.SystemError;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window;
public class CompetitionApplicationComponents {
public static final String ANNOUNCER_VIEW = "announcerView"; //$NON-NLS-1$
public static final String SUMMARY_LIFT_ORDER_VIEW = "summaryLiftOrderView"; //$NON-NLS-1$
public static final String CATEGORY_LIST = "categoryList"; //$NON-NLS-1$
public static final String CHANGES_VIEW = "changesView"; //$NON-NLS-1$
public static final String COMPETITION_EDITOR = "competitionEditor"; //$NON-NLS-1$
public static final String GROUP_LIST = "groupList"; //$NON-NLS-1$
public static final String PUBLIC_ATTEMPT_BOARD_VIEW = "publicAttemptBoard"; //$NON-NLS-1$
public static final String LIFTER_ATTEMPT_BOARD_VIEW = "lifterAttemptBoard"; //$NON-NLS-1$
public static final String LIFT_ORDER_VIEW = "liftOrderBoard"; //$NON-NLS-1$
public static final String PLATFORM_LIST = "platformList"; //$NON-NLS-1$
public static final String REGISTRATION_LIST = "registrationList"; //$NON-NLS-1$
public static final String RESULT_BOARD = "resultBoard"; //$NON-NLS-1$
public static final String OREFEREE_CONSOLE = "oRefereeConsole"; //$NON-NLS-1$
public static final String MREFEREE_CONSOLE = "refereeConsole"; //$NON-NLS-1$
public static final String OJURY_CONSOLE = "oJuryConsole"; //$NON-NLS-1$
public static final String MJURY_CONSOLE = "juryConsole"; //$NON-NLS-1$
public static final String MPLATES_INFO = "platesInfo"; //$NON-NLS-1$
public static final String SIMPLE_RESULT_BOARD = "simpleResultBoard"; //$NON-NLS-1$
public static final String RESULT_VIEW = "resultView"; //$NON-NLS-1$
public static final String TIMEKEEPER_VIEW = "timekeeperView"; //$NON-NLS-1$
public static final String UPLOAD_VIEW = "uploadView"; //$NON-NLS-1$
public static final String WEIGH_IN_LIST = "weighInList"; //$NON-NLS-1$
public static final String REFEREE_TESTING = "decisionLights"; //$NON-NLS-1$
public static final String JURY_LIGHTS = "juryLights"; //$NON-NLS-1$
public static final String COUNTDOWN_DISPLAY = "countdownDisplay"; //$NON-NLS-1$
public static final String SPREADSHEET_UPLOADER = "spreadsheetUpload";
public static final String HOME = ""; // empty fragment //$NON-NLS-1$
public Panel mainPanel;
public Menu menu;
public Window mainWindow;
public ApplicationView currentView;
private Map<String, CompetitionApplicationComponent> urlFragmentToView = new HashMap<String, CompetitionApplicationComponent>();
private Platform platform;
private Logger logger = LoggerFactory.getLogger(CompetitionApplicationComponents.class);
public CompetitionApplicationComponents(Panel mainPanel, Menu menu, String platformName) {
this.mainPanel = mainPanel;
this.menu = menu;
this.setPlatformByName(platformName);
urlFragmentToView.put(HOME, new EmptyComponent());
urlFragmentToView.put(ANNOUNCER_VIEW, new AnnouncerViewComponent());
urlFragmentToView.put(SUMMARY_LIFT_ORDER_VIEW, new SummaryLiftOrderViewComponent());
urlFragmentToView.put(CATEGORY_LIST, new CategoryListComponent());
urlFragmentToView.put(CHANGES_VIEW, new ChangesViewComponent());
urlFragmentToView.put(COMPETITION_EDITOR, new CompetitionEditorComponent());
urlFragmentToView.put(COUNTDOWN_DISPLAY, new CountdownDisplayComponent());
urlFragmentToView.put(REFEREE_TESTING, new RefereeTestingComponent());
urlFragmentToView.put(JURY_LIGHTS, new JuryLightsComponent());
urlFragmentToView.put(GROUP_LIST, new GroupListComponent());
urlFragmentToView.put(PUBLIC_ATTEMPT_BOARD_VIEW, new PublicAttemptBoardComponent());
urlFragmentToView.put(LIFTER_ATTEMPT_BOARD_VIEW, new LifterAttemptBoardComponent());
urlFragmentToView.put(LIFT_ORDER_VIEW, new LifterBoardComponent());
urlFragmentToView.put(PLATFORM_LIST, new PlatformListComponent());
urlFragmentToView.put(REGISTRATION_LIST, new RegistrationListComponent());
urlFragmentToView.put(RESULT_BOARD, new ResultBoardComponent());
urlFragmentToView.put(SIMPLE_RESULT_BOARD, new SimpleResultBoardComponent());
urlFragmentToView.put(RESULT_VIEW, new ResultViewComponent());
urlFragmentToView.put(OREFEREE_CONSOLE, new RefereeConsoleComponent(false));
urlFragmentToView.put(MREFEREE_CONSOLE, new RefereeConsoleComponent(true));
urlFragmentToView.put(OJURY_CONSOLE, new JuryConsoleComponent(false));
urlFragmentToView.put(MJURY_CONSOLE, new JuryConsoleComponent(true));
urlFragmentToView.put(MPLATES_INFO, new PlatesInfoComponent());
urlFragmentToView.put(TIMEKEEPER_VIEW, new TimekeeperViewComponent());
urlFragmentToView.put(UPLOAD_VIEW, new SpreadsheetUploaderComponent());
urlFragmentToView.put(WEIGH_IN_LIST, new WeighInListComponent());
}
/**
* Lazy factory for application components.
*
*/
private interface CompetitionApplicationComponent {
ApplicationView get(boolean initFromFragment, String viewName) ;
}
/**
* Lazy builder for competition editor.
*/
private class CompetitionEditorComponent implements CompetitionApplicationComponent {
private CompetitionEditor competitionEditor = null;
@Override
public CompetitionEditor get(boolean initFromFragment, String viewName) {
competitionEditor = (new CompetitionEditor(initFromFragment, viewName));
return competitionEditor;
}
}
/**
* Lazy builder for platformName list.
*/
private class PlatformListComponent implements CompetitionApplicationComponent {
private PlatformList platformList = null;
@Override
public PlatformList get(boolean initFromFragment, String viewName) {
this.platformList = (new PlatformList(initFromFragment, viewName));
return platformList;
}
}
/**
* Lazy builder for category list.
*/
private class CategoryListComponent implements CompetitionApplicationComponent {
private CategoryList categoryList = null;
@Override
public CategoryList get(boolean initFromFragment, String viewName) {
this.categoryList = (new CategoryList(initFromFragment, viewName));
return categoryList;
}
}
/**
* Lazy builder for group list.
*/
private class GroupListComponent implements CompetitionApplicationComponent {
private SessionList groupList = null;
@Override
public SessionList get(boolean initFromFragment, String viewName) {
this.groupList = (new SessionList(initFromFragment, viewName));
return groupList;
}
}
/**
* Lazy builder for weigh-in list.
*/
private class WeighInListComponent implements CompetitionApplicationComponent {
private WeighInList weighInList = null;
@Override
public WeighInList get(boolean initFromFragment, String viewName) {
this.weighInList = (new WeighInList(initFromFragment, viewName, false));
return weighInList;
}
}
/**
* Lazy builder for Countdown
*/
private class CountdownDisplayComponent implements CompetitionApplicationComponent {
private CountdownDisplay countdownDisplay = null;
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
this.countdownDisplay = (new CountdownDisplay(initFromFragment, viewName));
return countdownDisplay;
}
}
/**
* Lazy builder for Decision Lights
*/
private class RefereeTestingComponent implements CompetitionApplicationComponent {
private RefereeTesting decisionLights = null;
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
this.decisionLights = (new RefereeTesting(initFromFragment, viewName, false, false));
return decisionLights;
}
}
/**
* Lazy builder for Jury Lights
*/
private class JuryLightsComponent implements CompetitionApplicationComponent {
private RefereeDecisions juryLights = null;
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
this.juryLights = (new RefereeDecisions(initFromFragment, viewName, false, true));
return juryLights;
}
}
/**
* Lazy builder for Referee buttons
*/
private class RefereeConsoleComponent implements CompetitionApplicationComponent {
private IRefereeConsole refereeConsole = null;
private boolean mobile;
public RefereeConsoleComponent(boolean mobile) {
this.mobile = mobile;
}
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
if (mobile) {
this.refereeConsole = (new MRefereeConsole(initFromFragment, viewName));
} else {
this.refereeConsole = (new ORefereeConsole(initFromFragment, viewName));
}
return (ApplicationView)refereeConsole;
}
}
/**
* Lazy builder for Jury Decision display
*/
private class JuryConsoleComponent implements CompetitionApplicationComponent {
private IRefereeConsole juryConsole = null;
private boolean mobile;
public JuryConsoleComponent(boolean mobile) {
this.mobile = mobile;
}
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
if (mobile) {
this.juryConsole = (new MJuryConsole(initFromFragment, viewName));
} else {
this.juryConsole = (new OJuryConsole(initFromFragment, viewName));
}
return (ApplicationView)juryConsole;
}
}
/**
* Lazy builder for Referee buttons
*/
private class PlatesInfoComponent implements CompetitionApplicationComponent {
private MPlatesInfoView platesInfoConsole = null;
@Override
public ApplicationView get(boolean initFromFragment, String viewName) {
this.platesInfoConsole = (new MPlatesInfoView(initFromFragment, viewName));
return (ApplicationView)platesInfoConsole;
}
}
/**
* Lazy builder for registration list.
*/
private class RegistrationListComponent implements CompetitionApplicationComponent {
private WeighInList weighInList = null;
@Override
public WeighInList get(boolean initFromFragment, String viewName) {
this.weighInList = (new WeighInList(initFromFragment, viewName,true));
return weighInList;
}
}
/**
* Lazy builder for spreadsheet upload page.
*/
private class SpreadsheetUploaderComponent implements CompetitionApplicationComponent {
private SpreadsheetUploader spreadsheetUploader = null;
@Override
public SpreadsheetUploader get(boolean initFromFragment, String viewName) {
this.spreadsheetUploader = (new SpreadsheetUploader(initFromFragment, viewName));
return spreadsheetUploader;
}
}
/**
* Lazy builder for announcer view.
*/
private class AnnouncerViewComponent implements CompetitionApplicationComponent {
private AnnouncerView announcerView = null;
@Override
public AnnouncerView get(boolean initFromFragment, String viewName) {
announcerView = (new AnnouncerView(initFromFragment, viewName, Mode.ANNOUNCER));
announcerView.adjustSplitBarLocation();
return announcerView;
}
}
/**
* Lazy builder for change management (marshal) view.
*/
private class ChangesViewComponent implements CompetitionApplicationComponent {
private AnnouncerView changesView = null;
@Override
public AnnouncerView get(boolean initFromFragment, String viewName) {
changesView = (new AnnouncerView(initFromFragment, viewName,Mode.MARSHALL));
changesView.adjustSplitBarLocation();
return changesView;
}
}
/**
* Lazy builder for time keeper view.
*/
private class TimekeeperViewComponent implements CompetitionApplicationComponent {
private AnnouncerView timekeeperView = null;
@Override
public AnnouncerView get(boolean initFromFragment, String viewName) {
timekeeperView = (new AnnouncerView(initFromFragment, viewName, Mode.TIMEKEEPER));
timekeeperView.adjustSplitBarLocation();
return timekeeperView;
}
}
/**
* Lazy builder for registration list.
*/
private class ResultViewComponent implements CompetitionApplicationComponent {
private ResultView resultView = null;
@Override
public ResultView get(boolean initFromFragment, String viewName) {
this.resultView = (new ResultView(initFromFragment, viewName));
return resultView;
}
}
/**
* Lazy builder for main result board.
*/
private class ResultBoardComponent implements CompetitionApplicationComponent {
private ResultFrame resultBoard = null;
@Override
public ResultFrame get(boolean initFromFragment, String viewName) {
try {
Locale locale = CompetitionApplication.getCurrentLocale();
String localeSuffix = "";
if ("en".equals(locale.getLanguage())) {
localeSuffix = "-en";
}
resultBoard = (new ResultFrame(initFromFragment, viewName,"jsp/resultBoard"+localeSuffix+".jsp?platformName=")); //$NON-NLS-1$
} catch (MalformedURLException e) {
throw new SystemError(e);
}
return resultBoard;
}
}
/**
* Lazy builder for main result board.
*/
private class SimpleResultBoardComponent implements CompetitionApplicationComponent {
private ResultFrame resultBoard = null;
@Override
public ResultFrame get(boolean initFromFragment, String viewName) {
try {
Locale locale = CompetitionApplication.getCurrentLocale();
String localeSuffix = "";
if ("en".equals(locale.getLanguage())) {
localeSuffix = "-en";
}
resultBoard = (new ResultFrame(initFromFragment, viewName,"jsp/simpleResultBoard"+localeSuffix+".jsp?platformName=")); //$NON-NLS-1$
} catch (MalformedURLException e) {
throw new SystemError(e);
}
return resultBoard;
}
}
/**
* Lazy builder for lift order board.
*/
private class LifterBoardComponent implements CompetitionApplicationComponent {
private ResultFrame liftOrderBoard = null;
@Override
public ResultFrame get(boolean initFromFragment, String viewName) {
try {
Locale locale = CompetitionApplication.getCurrentLocale();
String localeSuffix = "";
if ("en".equals(locale.getLanguage())) {
localeSuffix = "-en";
}
liftOrderBoard = (new ResultFrame(initFromFragment, viewName,"jsp/warmupRoom"+localeSuffix+".jsp?platformName=")); //$NON-NLS-1$
} catch (MalformedURLException e) {
throw new SystemError(e);
}
return liftOrderBoard;
}
}
/**
* Lazy builder for lift order board.
*/
private class SummaryLiftOrderViewComponent implements CompetitionApplicationComponent {
private ResultFrame summaryLifterView = null;
@Override
public ResultFrame get(boolean initFromFragment, String viewName) {
try {
Locale locale = CompetitionApplication.getCurrentLocale();
String localeSuffix = "";
if ("en".equals(locale.getLanguage())) {
localeSuffix = "-en";
}
summaryLifterView = (new ResultFrame(initFromFragment, viewName, "jsp/liftingOrder"+localeSuffix+".jsp?platformName=")); //$NON-NLS-1$
} catch (MalformedURLException e) {
throw new SystemError(e);
}
return summaryLifterView;
}
}
/**
* Lazy builder for current lifter information
*/
private class PublicAttemptBoardComponent implements CompetitionApplicationComponent {
// private ResultFrame currentLifterPanel = null;
@Override
public AttemptBoardView get(boolean initFromFragment, String viewName) {
return new AttemptBoardView(initFromFragment, viewName, true);
}
}
/**
* Lazy builder for current lifter information
*/
private class LifterAttemptBoardComponent implements CompetitionApplicationComponent {
// private ResultFrame currentLifterPanel = null;
@Override
public AttemptBoardView get(boolean initFromFragment, String viewName) {
return new AttemptBoardView(initFromFragment, viewName, false);
}
}
/**
* Lazy builder for competition editor.
*/
private class EmptyComponent implements CompetitionApplicationComponent {
private EmptyView emptyView = null;
@Override
public EmptyView get(boolean initFromFragment, String viewName) {
emptyView = (new EmptyView());
return emptyView;
}
}
public ApplicationView getViewByName(String fragment, boolean initFromFragment) {
int where = fragment.indexOf("/");
String viewName = fragment;
if (where != -1) {
viewName = fragment.substring(0,where);
}
final CompetitionApplicationComponent component = urlFragmentToView.get(viewName);
if (component != null) {
final ApplicationView applicationView = component.get(initFromFragment,viewName);
// LoggerUtils.logException(logger, new Exception("fragment "+fragment));
// logger.debug("getViewByName returning {}",applicationView);
return applicationView;
} else {
throw new RuntimeException(Messages.getString(
"CompetitionApplicationComponents.ViewNotFound", CompetitionApplication.getCurrentLocale()) + viewName); //$NON-NLS-1$
}
}
public void setPlatform(Platform platform) {
this.platform = platform;
}
public Platform getPlatform() {
return platform;
}
/**
* @param platformName
* the platformName to set
*/
public void setPlatformByName(String platformName) {
logger.debug("enter +++++"); //$NON-NLS-1$
if (platformName == null) {
setPlatform(null);
return;
}
final Platform platform1 = Platform.getByName(platformName);
if (platform1 != null) {
final CompetitionApplication app = CompetitionApplication.getCurrent();
SessionData masterData = app.getMasterData(platformName);
final CompetitionSession currentGroup = masterData.getCurrentSession();
logger.debug("new current group {}", currentGroup); //$NON-NLS-1$
setPlatform(platform1);
if (currentView instanceof EditingView) {
((EditingView) currentView).setSessionData(masterData);
}
app.setCurrentCompetitionSession(currentGroup);
} else {
logger.error(Messages.getString(
"CompetitionApplicationComponents.PlatformNotFound", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
logger.debug("finish +++++"); //$NON-NLS-1$
}
/**
* @return the platformName
*/
public String getPlatformName() {
if (platform != null) {
logger.debug("{}", platform.getName()); //$NON-NLS-1$
return platform.getName();
} else {
logger.debug("getPlatformName platform=null"); //$NON-NLS-1$
return null;
}
}
/**
* @return
* @throws RuleViolationException
*/
public static String initPlatformName() throws RuleViolationException {
final CompetitionApplication app = CompetitionApplication.getCurrent();
String platformName = app.getPlatformName();
if (platformName == null) {
List<Platform> platforms = Platform.getAll();
if (platforms.size() == 1) {
app.components.setPlatform(platforms.get(0));
platformName = app.getPlatformName();
} else {
throw new RuleViolationException(CompetitionApplication.getCurrent().getLocale(),"AnnouncerView.selectPlatformFirst"); //$NON-NLS-1$
}
}
return platformName;
}
/**
* @return
* @throws RuleViolationException
*/
public static String firstPlatformName() throws RuleViolationException {
final CompetitionApplication app = CompetitionApplication.getCurrent();
String platformName = app.getPlatformName();
if (platformName == null) {
List<Platform> platforms = Platform.getAll();
if (platforms.size() >= 1) {
app.components.setPlatform(platforms.get(0));
platformName = app.getPlatformName();
} else {
throw new RuleViolationException(
Messages
.getString(
"CompetitionApplicationComponents.MustDefineAtLeastOnePlatform", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
}
return platformName;
}
}
| Java |
/*
* Copyright ©2009 Jean-François Lamy
*
* Licensed under the Open Software Licence, Version 3.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.opensource.org/licenses/osl-3.0.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.hibernate.event.def;
import java.io.Serializable;
import java.util.Map;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.StaleObjectStateException;
import org.hibernate.WrongClassException;
import org.hibernate.engine.EntityEntry;
import org.hibernate.engine.EntityKey;
import org.hibernate.event.EventSource;
import org.hibernate.event.MergeEvent;
import org.hibernate.intercept.FieldInterceptionHelper;
import org.hibernate.intercept.FieldInterceptor;
import org.hibernate.persister.entity.EntityPersister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class OverrideMergeEventListener extends DefaultMergeEventListener {
private static final Logger log = LoggerFactory.getLogger(DefaultMergeEventListener.class);
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected void entityIsDetached(MergeEvent event, Map copyCache) {
log.trace("merging detached instance");
final Object entity = event.getEntity();
final EventSource source = event.getSession();
final EntityPersister persister = source.getEntityPersister(event.getEntityName(), entity);
final String entityName = persister.getEntityName();
Serializable id = event.getRequestedId();
if (id == null) {
id = persister.getIdentifier(entity, source.getEntityMode());
} else {
// check that entity id = requestedId
Serializable entityId = persister.getIdentifier(entity, source.getEntityMode());
if (!persister.getIdentifierType().isEqual(id, entityId, source.getEntityMode(), source.getFactory())) {
throw new HibernateException("merge requested with id not matching id of passed entity");
}
}
String previousFetchProfile = source.getFetchProfile();
source.setFetchProfile("merge");
// we must clone embedded composite identifiers, or
// we will get back the same instance that we pass in
final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType().deepCopy(id,
source.getEntityMode(), source.getFactory());
final Object result = source.get(entityName, clonedIdentifier);
source.setFetchProfile(previousFetchProfile);
if (result == null) {
// this is in an attempt to fix the fact that if someone deletes a
// lifter
// who is currently lifting, there will be clones in the database.
// we should throw an exception if we really *know* for sure
// that this is a detached instance, rather than just assuming
throw new StaleObjectStateException(entityName, id);
// we got here because we assumed that an instance
// with an assigned id was detached, when it was
// really persistent
// entityIsTransient(event, copyCache);
} else {
copyCache.put(entity, result); // before cascade!
final Object target = source.getPersistenceContext().unproxy(result);
if (target == entity) {
throw new AssertionFailure("entity was not detached");
} else if (!source.getEntityName(target).equals(entityName)) {
throw new WrongClassException("class of the given object did not match class of persistent copy", event
.getRequestedId(), entityName);
} else if (isVersionChanged(entity, source, persister, target)) {
if (source.getFactory().getStatistics().isStatisticsEnabled()) {
source.getFactory().getStatisticsImplementor().optimisticFailure(entityName);
}
throw new StaleObjectStateException(entityName, id);
}
// cascade first, so that all unsaved objects get their
// copy created before we actually copy
cascadeOnMerge(source, persister, entity, copyCache);
copyValues(persister, entity, target, source, copyCache);
// copyValues works by reflection, so explicitly mark the entity
// instance dirty
markInterceptorDirty(entity, target);
event.setResult(result);
}
}
private void markInterceptorDirty(final Object entity, final Object target) {
if (FieldInterceptionHelper.isInstrumented(entity)) {
FieldInterceptor interceptor = FieldInterceptionHelper.extractFieldInterceptor(target);
if (interceptor != null) {
interceptor.dirty();
}
}
}
private boolean isVersionChanged(Object entity, EventSource source, EntityPersister persister, Object target) {
if (!persister.isVersioned()) {
return false;
}
// for merging of versioned entities, we consider the version having
// been changed only when:
// 1) the two version values are different;
// *AND*
// 2) The target actually represents database state!
//
// This second condition is a special case which allows
// an entity to be merged during the same transaction
// (though during a seperate operation) in which it was
// originally persisted/saved
boolean changed = !persister.getVersionType().isSame(persister.getVersion(target, source.getEntityMode()),
persister.getVersion(entity, source.getEntityMode()), source.getEntityMode());
// perhaps we should additionally require that the incoming
// entity version be equivalent to the defined unsaved-value?
return changed && existsInDatabase(target, source, persister);
}
private boolean existsInDatabase(Object entity, EventSource source, EntityPersister persister) {
EntityEntry entry = source.getPersistenceContext().getEntry(entity);
if (entry == null) {
Serializable id = persister.getIdentifier(entity, source.getEntityMode());
if (id != null) {
EntityKey key = new EntityKey(id, persister, source.getEntityMode());
Object managedEntity = source.getPersistenceContext().getEntity(key);
entry = source.getPersistenceContext().getEntry(managedEntity);
}
}
if (entry == null) {
// perhaps this should be an exception since it is only ever used
// in the above method?
return false;
} else {
return entry.isExistsInDatabase();
}
}
}
| Java |
package com.github.wolfie.blackboard;
public interface Event {
}
| Java |
package com.github.wolfie.blackboard;
public interface Listener {
}
| Java |
package com.github.wolfie.blackboard;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.github.wolfie.blackboard.annotation.ListenerMethod;
import com.github.wolfie.blackboard.exception.DuplicateListenerMethodException;
import com.github.wolfie.blackboard.exception.DuplicateRegistrationException;
import com.github.wolfie.blackboard.exception.EventNotRegisteredException;
import com.github.wolfie.blackboard.exception.IncompatibleListenerMethodException;
import com.github.wolfie.blackboard.exception.NoListenerMethodFoundException;
import com.github.wolfie.blackboard.exception.NoMatchingRegistrationFoundException;
/**
* <p>
* A global event handler
* </p>
*
* <p>
* Blackboard is a <a href="http://en.wikipedia.org/wiki/Blackboard_system">
* blackboard system</a>-based event handler. {@link Listener Listeners} can add
* themselves as listeners for a certain {@link Event}.
* </p>
*
* <p>
* To avoid cross-application message leaking, the {@link Blackboard} is an
* instance, not a static util class. This means, the client code must handle
* making the instance available to the application globally, if that is
* desired. The nïve way would be to create it as a static instance in the
* application, but that is not thread safe (which, in some cases, might be
* okay).
* </p>
*
* <p>
* Using the ThreadLocal pattern<sup><a
* href="http://vaadin.com/wiki/-/wiki/Main/ThreadLocal%20Pattern">[1]</a>,<a
* href="http://en.wikipedia.org/wiki/Thread-local_storage">[2]</a></sup> is
* highly encouraged in multithreaded applications.
* </p>
*
* <p>
* Any method in this class may throw a {@link NullPointerException} upon passed
* <code>null</code> arguments.
* </p>
*
* @author Henrik Paul
*/
public class Blackboard {
private static class Registration {
private final Class<? extends Listener> listener;
private final Class<? extends Event> event;
private final Method method;
public Registration(final Class<? extends Listener> listener,
final Class<? extends Event> event)
throws DuplicateListenerMethodException {
if (!listener.isInterface()) {
throw new IllegalArgumentException(
"Unexpected non-interface argument: " + listener);
} else if (event.isInterface()
|| Modifier.isAbstract(event.getModifiers())) {
throw new IllegalArgumentException(
"Unexpected interface or abstract class argument: " + event);
}
Method listenerMethod = null;
for (final Method candidateMethod : listener.getMethods()) {
final ListenerMethod annotation = candidateMethod
.getAnnotation(ListenerMethod.class);
if (annotation != null) {
if (listenerMethod == null) {
listenerMethod = candidateMethod;
} else {
throw new DuplicateListenerMethodException(listener,
candidateMethod, listenerMethod);
}
}
}
if (listenerMethod != null) {
final Class<?>[] parameterTypes = listenerMethod.getParameterTypes();
if (parameterTypes.length != 1 || !parameterTypes[0].equals(event)) {
throw new IncompatibleListenerMethodException(listener,
listenerMethod, event);
}
} else {
throw new NoListenerMethodFoundException(listener);
}
Log.log(String.format("Registering %s.%s() to %s", listener.getName(),
listenerMethod.getName(), event.getName()));
Log.logEmptyLine();
method = listenerMethod;
this.listener = listener;
this.event = event;
}
public Class<? extends Listener> getListener() {
return listener;
}
public Class<? extends Event> getEvent() {
return event;
}
public Method getMethod() {
return method;
}
}
private final Map<Class<? extends Event>, Registration> registrationsByEvent = new HashMap<Class<? extends Event>, Blackboard.Registration>();
private final Map<Class<? extends Listener>, Set<Listener>> listeners;
public Blackboard() {
listeners = new ConcurrentHashMap<Class<? extends Listener>, Set<Listener>>();
}
/**
* <p>
* Register a unique listener/event combination with Blackboard.
* </p>
*
* <p>
* Whenever an {@link Event} of type <tt>event</tt> is fired, all
* {@link Listener Listeners} of type <tt>Listener</tt> are triggered.
* </p>
*
* @param listener
* The {@link Listener} interface to register with <tt>event</tt>.
* @param event
* The {@link Event} interface to register with <tt>listener</tt>.
* @throws DuplicateRegistrationException
* if <tt>listener</tt> and/or <tt>event</tt> is already previously
* registered.
* @throws DuplicateListenerMethodException
* if <tt>listener</tt> has more than one public method annotated
* with {@link ListenerMethod}.
* @throws NoListenerMethodFoundException
* if <tt>listener</tt> has no public methods annotated with
* {@link ListenerMethod}.
* @throws IncompatibleListenerMethodException
* if the method annotated with {@link ListenerMethod} doesn't have
* exactly one argument, it being of type <tt>event</tt>.
* @throws IllegalArgumentException
* if <tt>listener</tt> is a non-interface class, and/or
* <tt>event</tt> is a interface or an abstract class object.
*/
public void register(final Class<? extends Listener> listener,
final Class<? extends Event> event) {
assertNotNull(listener, event);
for (final Registration registration : registrationsByEvent.values()) {
final Class<? extends Listener> existingListener = registration
.getListener();
final Class<? extends Event> existingEvent = registration.getEvent();
if (existingListener.equals(listener) || existingEvent.equals(event)) {
throw new DuplicateRegistrationException(listener, event,
existingListener, existingEvent);
}
}
registrationsByEvent.put(event, new Registration(listener, event));
}
/**
* <p>
* Register a {@link Listener} with Blackboard.
* </p>
*
* <p>
* The <tt>Listener</tt> will receive all {@link Event Events} of a certain
* type, according to any prior {@link #register(Class, Class) registrations}.
* Each <tt>Listener</tt> object needs to be added only once, even if it
* implements several Listener-interfaces.
* </p>
*
* <p>
* <em>Note:</em> By design, no listener order is preserved. This means, the
* order in which the listeners are added is not guaranteed to be the same as
* in which the listeners are triggered.
* </p>
*
* @param listener
* The Listener to register.
*/
public void addListener(final Listener listener) {
assertNotNull(listener);
Log.log("Adding " + listener + " for the following listeners:");
final Class<? extends Listener> listenerClass = listener.getClass();
final Collection<Class<? extends Listener>> registeredListenerClasses = getRegisteredListenerClasses(listenerClass);
if (registeredListenerClasses.isEmpty()) {
throw new NoMatchingRegistrationFoundException(listenerClass);
}
for (final Class<? extends Listener> registeredListenerClass : registeredListenerClasses) {
Set<Listener> listenersForClass = listeners.get(registeredListenerClass);
if (listenersForClass == null) {
listenersForClass = new HashSet<Listener>();
listeners.put(registeredListenerClass, listenersForClass);
}
listenersForClass.add(listener);
Log.log(" ...listening to " + registeredListenerClass);
}
Log.logEmptyLine();
}
private Collection<Class<? extends Listener>> getRegisteredListenerClasses(
final Class<? extends Listener> listenerClass) {
final Collection<Class<? extends Listener>> listeners1 = new HashSet<Class<? extends Listener>>();
for (final Registration registration : registrationsByEvent.values()) {
final Class<? extends Listener> registeredListenerClass = registration
.getListener();
if (registeredListenerClass.isAssignableFrom(listenerClass)) {
listeners1.add(registeredListenerClass);
}
}
return listeners1;
}
/**
* Remove a {@link Listener} from Blackboard.
*
* @param listener
* The Listener to remove.
* @return <code>true</code> iff <tt>listener</tt> was found and removed.
*/
public boolean removeListener(final Listener listener) {
assertNotNull(listener);
Log.log("Removing " + listener);
final Class<? extends Listener> listenerClass = listener.getClass();
final Collection<Class<? extends Listener>> registeredListenerClasses = getRegisteredListenerClasses(listenerClass);
boolean success = false;
for (final Class<? extends Listener> registeredListenerClass : registeredListenerClasses) {
final Set<Listener> listenersOfClass = listeners
.get(registeredListenerClass);
if (listenersOfClass != null) {
final boolean intermediateSuccess = listenersOfClass.remove(listener);
Log.log(" ...removing it from " + registeredListenerClass);
if (!success) {
success = intermediateSuccess;
}
}
}
Log.logEmptyLine();
return success;
}
/**
* <p>
* Fire an {@link Event}
* </p>
*
* <p>
* All {@link Listener Listeners} registered to listen to the given Event will
* be notified.
* </p>
*
* @param event
* The Event to fire.
* @throws EventNotRegisteredException
* if <tt>event</tt>'s type wasn't previously registered with
* Blackboard.
* @see #register(Class, Class)
*/
public void fire(final Event event) {
assertNotNull(event);
Log.log("Firing " + event);
final Registration registration = registrationsByEvent
.get(event.getClass());
if (registration == null) {
throw new EventNotRegisteredException(event.getClass());
}
final Class<? extends Listener> listenerClass = registration.getListener();
final Method listenerMethod = registration.getMethod();
final Set<Listener> listenersForClass = listeners.get(listenerClass);
if (listenersForClass == null) {
return;
}
// copy listenersForClass, so that if the invoked method adds or removes listeners
// the list being iterated on is not affected. the newly added/removed listeners will
// be taken into account when the next event fires.
HashSet<Listener> iterationListeners = new HashSet<Listener>(listenersForClass);
for (final Listener listener : iterationListeners) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.log(" triggering " + listener);
listenerMethod.invoke(listener, event);
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final InvocationTargetException e) {
e.printStackTrace();
}
}
}).start();
}
Log.logEmptyLine();
}
/**
* Assert that no arguments are <code>null</code>
*
* @param args
* the arguments to check.
* @throws NullPointerException
* if any of <tt>args</tt> is <code>null</code>.
*/
private void assertNotNull(final Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
throw new NullPointerException("Argument with index " + i
+ " was null.");
}
}
}
public void enableLogging() {
Log.setLogging(true);
}
public void disableLogging() {
Log.setLogging(false);
}
}
| Java |
package com.github.wolfie.blackboard.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.github.wolfie.blackboard.Event;
import com.github.wolfie.blackboard.Listener;
/**
* <p>
* The annotation that marks that this is the method to call in a
* {@link Listener}, when a matching {@link Event} has been fired.
* </p>
*
* <p>
* One, and only one public method must be annotated per {@link Listener}.
* Non-public methods are ignored.
* </p>
*
* @author Henrik Paul
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ListenerMethod {
}
| Java |
package com.github.wolfie.blackboard.exception;
import java.lang.reflect.Method;
import com.github.wolfie.blackboard.Listener;
public class DuplicateListenerMethodException extends RuntimeException {
private static final long serialVersionUID = 2699631613035288301L;
public DuplicateListenerMethodException(
final Class<? extends Listener> listener, final Method duplicateMethod,
final Method listenerMethod) {
super("Class " + listener.getName()
+ " has multiple listener method declarations. "
+ listenerMethod.getName()
+ " was already accepted as the method, but "
+ duplicateMethod.getName() + " was found also.");
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import com.github.wolfie.blackboard.Event;
public class EventNotRegisteredException extends RuntimeException {
private static final long serialVersionUID = 3715484742311180580L;
public EventNotRegisteredException(final Class<? extends Event> event) {
super(event.getName() + " was not registered.");
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import java.lang.reflect.Method;
import com.github.wolfie.blackboard.Event;
import com.github.wolfie.blackboard.Listener;
public class IncompatibleListenerMethodException extends RuntimeException {
private static final long serialVersionUID = 4404069292505802332L;
public IncompatibleListenerMethodException(final Class<? extends Listener> listener,
final Method listenerMethod, final Class<? extends Event> event) {
super("Listener method " + listenerMethod.getName() + " in class "
+ listener.getName() + " should have exactly one parameter of type "
+ event.getName());
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import com.github.wolfie.blackboard.Listener;
public class NoMatchingListenerRegistered extends RuntimeException {
private static final long serialVersionUID = -8143162070880780841L;
public NoMatchingListenerRegistered(final Class<? extends Listener> listener) {
super(String
.format("Cannot register %s since "
+ "no matching Listener was previously registered.", listener
.getName()));
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import com.github.wolfie.blackboard.Listener;
public class NoMatchingRegistrationFoundException extends RuntimeException {
private static final long serialVersionUID = 1639067602385701335L;
public NoMatchingRegistrationFoundException(
final Class<? extends Listener> class1) {
super(class1.getName() + " or any of its superclasses or "
+ "interfaces were not previously registered as Listener.");
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import com.github.wolfie.blackboard.Listener;
import com.github.wolfie.blackboard.annotation.ListenerMethod;
public class NoListenerMethodFoundException extends RuntimeException {
private static final long serialVersionUID = 2145403658103285993L;
public NoListenerMethodFoundException(final Class<? extends Listener> listener) {
super("No annotated methods found in " + listener
+ ". Make sure you have exactly one method annotated with "
+ ListenerMethod.class.getName());
}
}
| Java |
package com.github.wolfie.blackboard.exception;
import com.github.wolfie.blackboard.Event;
import com.github.wolfie.blackboard.Listener;
public class DuplicateRegistrationException extends RuntimeException {
private static final long serialVersionUID = 1710988524955675742L;
public DuplicateRegistrationException(
final Class<? extends Listener> listener,
final Class<? extends Event> event,
final Class<? extends Listener> existingListener,
final Class<? extends Event> existingEvent) {
super(
String
.format(
"Duplicate listener/event registration. Tried to register %s and %s, collides with %s and/or %s",
listener, event, existingListener, existingEvent));
}
}
| Java |
package com.github.wolfie.blackboard;
import java.io.PrintStream;
class Log {
private static boolean logging = false;
private static PrintStream logTo = System.out;
private Log() {
// not instantiable
}
static void logTo(final PrintStream printWriter) {
logTo = printWriter;
}
static void setLogging(final boolean enableLogging) {
logging = enableLogging;
}
static void log(final String string) {
if (logging) {
logTo.println("[BB] " + string);
}
}
static void logEmptyLine() {
log("");
}
}
| Java |
package com.felight;
import java.awt.List;
import java.util.*;
public class benchmark {
public static void main(String[] args) {
ArrayList<String> arLst = new ArrayList<String>();
LinkedList<String> lnLst = new LinkedList<String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
int pos = 9000;
arLst.add("anita");
}
System.out.println("Array list: "+Long.toString(System.currentTimeMillis()-start));
start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
int pos = 9000;
lnLst.add("anita");
}
System.out.println("Linked list: "+Long.toString(System.currentTimeMillis()-start));
}
}
| Java |
package com.felight;
public class testthread {
public static void main(String[] Felight){
System.out.println("Before creating a Thread");
A objA = new A();
objA.start();
System.out.println("After creating a Thread");
}
}
| Java |
package com.felight;
public class Employee implements Comparable<Employee> {
int id;
private String name;
private String Address;
public int getId(){
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public Employee(int id, String name, String Address){
this.id = id;
this.name = name;
this.Address = Address;
}
public Employee(int i, String string) {
// TODO Auto-generated constructor stub
}
public String toString(){
return this.name;
}
public int compareTo(Employee o){
return name.compareTo(o.getName());
}
}
| Java |
class test{
public static void main(String[] Felight){
employee A = new employee();
A.id=1;
A.name="asd";
A.address="werrr";
A.salary=100000000;
System.out.println("A.id:" +A.id);
System.out.println("A.name:" +A.name);
System.out.println("A.address:" +A.address);
System.out.println("A.salary:" +A.salary);
employee B = new employee();
B.id=2;
B.name="ABC";
B.address="werr";
B.salary=20000000;
System.out.println("B.id:" +B.id);
System.out.println("B.name:" +B.name);
System.out.println("B.address:" +B.address);
System.out.println("B.salary:" +B.salary);
employee C = new employee();
C.id=3;
C.name="XYZ";
C.address="XCVB";
C.salary=300000;
System.out.println("C.id:" +C.id);
System.out.println("C.name:" +C.name);
System.out.println("C.address:" +C.address);
System.out.println("C.salary:" +C.salary);
employee D = new employee();
D.id=4;
D.name="ASBC";
D.address="XSDF";
D.salary=400000;
System.out.println("D.id:" +D.id);
System.out.println("D.name:" +D.name);
System.out.println("D.address:" +D.address);
System.out.println("D.salary:" +D.salary);
employee E = new employee();
E.id=5;
E.name="ANIT";
E.address="BJP";
E.salary=500000000;
System.out.println("E.id:" +E.id);
System.out.println("E.name:" +E.name);
System.out.println("E.address:" +E.address);
System.out.println("E.salary:" +E.salary);
}
} | Java |
class Calculator1{
boolean bln;
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
String str;
} | Java |
import java.io.*;
public class test{
public String[] readFile(File f) throws Exception{
//String line=null;
String[] str= new String[5];
FileReader fr=null;
BufferedReader br=null;
try{
fr= new FileReader(f);
br=new BufferedReader(fr);
if((br.readLine())!=null){
for(int i=0;i<str.length;i++){
str[i]=br.readLine();
//System.out.println(str[i]);
}
return str;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally{
try {
br.close();
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public String[] filter(String[] s,String p){
String[] str=new String[5];
boolean t;
for(int i=0;i<s.length;i++){
if(s[i]!=null)
if((t=s[i].contains(p))){
str[i]=s[i];
//System.out.println(s[i]);
}
}
return str;
}
public void writeFile(String[] s,File f){
//String[] str= new String[5];
FileWriter fr=null;
BufferedWriter br=null;
try{
fr= new FileWriter(f);
br=new BufferedWriter(fr);
for(int i=0;i<s.length;i++){
if((s[i])!=null){
br.write(s[i]);
br.newLine();
//System.out.println(str[i]);
}
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally{
try {
br.close();
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void print(String[] s){
for(int i=0;i<s.length;i++)
System.out.println(s[i]);
}
public static void main(String[]ags) throws Exception{
File f =new File("mails.txt");
File f1=new File("gururaj.txt");
test t=new test();
test t1=new test();
test t2=new test();
System.out.println("before filter \n");
String[] s=t.readFile(f);
t.print(s);
System.out.println();
System.out.println("After filter \n");
String[] s1=t1.filter(s,"yahoo");
t1.print(s1);
t2.writeFile(s1,f1);
}
} | Java |
package com.felight;
public class test {
private static int[] array;
public static void main(String[] Felight){
calculator c1=new calculator();
int[] arr=c1.generateFibonacci(6);
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
int res=c1.ADD(10,20);
System.out.println(res);
int[] result={2,4,6,8,5};
int sum=c1.arrsum(result, result);
System.out.println(sum);
boolean prim = calculator.isPrime(19);
System.out.println(prim);
int[] rand = calculator.randomInt(100);
int num = 0;
for(int i = 0; i<num; i++)
{
System.out.println(rand);
}
char[] resul = c1.
| Java |
package com.felight;
import java.util.ArrayList;
import java.util.List;
public class collection {
public static void main(String[] Felight){
List<String> listOfStrings = new ArrayList<String>();
String str = "Hello";
listOfStrings.add(str);
listOfStrings.add("felight");
listOfStrings.add(str+str);
System.out.println(listOfStrings.size());
System.out.println(listOfStrings.contains(1));
System.out.println(listOfStrings.contains("felight"));
System.out.println(listOfStrings.remove("Hell"));
System.out.println(listOfStrings.size());
}
} | Java |
package com.felight;
public class C extends Thread{
public void run(){
System.out.println("Class C Thread running with the Thread Name:"
+Thread.currentThread().getName());
}
}
class D implements Runnable{
public void run(){
System.out.println("Class D Thread runbning with the Thread name:"
+Thread.currentThread().getName());
}
} | Java |
package com.felight;
public class calculator {
public static int[] randomInt(int d)
{
int[] a = new int[d];
for(int i = 0; i<d; i++)
a[i]=(int) (Math.random()*100);
return a;
}
public static double[] randomDouble(int num)
{
double[] a = new double[num];
for(int i = 0; i<num; i++)
a[i]=Math.random()*100;
return a;
}
public static char[] randomChar(int num)
{
char temp;
char[] a = new char[num];
int i=0;
while(i<num)
{
temp = (char) (Math.random()*100);
if((temp >='a' && temp <= 'z' )||(temp >= 'A' && temp <= 'Z'))
a[i++]=temp;
}
return a;
}
public static void printInt(int[] array)
{
for(int i=0;i<array.length;i++)
System.out.print(array[i] + ",");
}
public static void printDouble(double[] array)
{
for(int i=0;i<array.length;i++)
System.out.print(array[i] + ",");
}
public static void printChar(char[] array)
{
for(int i=0;i<array.length;i++)
System.out.print(array[i] + ",");
}
public static int maxArray(int[] array)
{
int max=0;
for(int i=0;i<array.length;i++)
if(max<array[i])
max = array[i];
return max;
}
public int[] revInt(int[] array)
{
int[] rev = new int[array.length];
for(int i=0;i<array.length;i++)
rev[array.length-i-1] = array[i];
return rev;
}
public static char[] revChar(char[] array)
{
char[] rev = new char[array.length];
for(int i=0;i<array.length;i++)
rev[array.length-i-1] = array[i];
return rev;
}
public static int countVowel(char[] array)
{
int count=0;
for(int i=0;i<array.length;i++)
if(array[i]=='a'||array[i]=='e'||array[i]=='i'||array[i]=='o'||array[i]=='u'||
array[i]=='A'||array[i]=='E'||array[i]=='I'||array[i]=='O'||array[i]=='U')
count++;
return count;
}
public static int[] generateEven(int num1,int num2)
{
int[] array = new int[50];
for(int i=num1,j=0;i<=num2;i++,j++)
if(i%2==0)
array[j]=i;
else
j--;
return array;
}
public static int[] generateOdd(int num1,int num2)
{
int[] array= new int[50];
for(int i=num1,j=0;i<=num2;i++,j++)
if(!(i%2==0))
array[j]=i;
else
j--;
return array;
}
public static int[] generatePrime(int num1,int num2)
{
int[] array = new int[50];
for(int i=num1,j=0;i<=num2;i++,j++)
if(isPrime(i))
array[j]=i;
else
j--;
return array;
}
public static boolean isPrime(long num)
{
boolean result = false;
long count = 0;
long i=2;
while(i <= num/2) {
if(num%i == 0)
count++;
i++;
}
if(count == 0 && num != 1 && num != 0)
result = true;
return result;
}
public int[] generateFibonacci(int num)
{
int[] fib=new int[num];
fib[0] = 0;
fib[1] = 1;
for(int i=2;i<fib.length;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
return (fib);
}
public static int[][] generateRandomMatrix(int row , int col)
{
int[][] matrix = new int[row][col];
int a;
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++)
{
a = (int)(Math.random()*100);
if(a>0&&a<10)
matrix[i][j] = a;
else
j--;
}
}
return matrix;
}
public static void printMatrix(int[][] matrix)
{
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++)
System.out.print(matrix[i][j]+" ");
System.out.println();
}
}
public static int[][] addMatrix(int[][] matA , int[][] matB)
{
int[][] result = new int[matA.length][matA[0].length];
for(int i=0;i<matA.length;i++)
for(int j=0;j<matB[i].length;j++)
result[i][j] = matA[i][j] + matB[i][j];
return result;
}
public static int[][] multiMatrix(int[][] matA , int[][] matB)
{
int[][] result = new int[matA.length][matB[0].length];
int sum=0;
for(int i=0;i< matA.length;i++)
for(int j=0;j<matB[0].length;j++)
for(int k=0 ; k < matB.length ;k++)
result[i][j] = result[i][j] + (matA[i][k] * matB[k][j]);
return result;
}
public static long sumMatrix(int[][] matrix)
{
long sum = 0;
for(int i=0;i<matrix.length;i++)
for(int j=0;j<matrix[i].length;j++)
sum = sum + matrix[i][j];
return sum;
}
public static int[] sumRow(int[][] matrix)
{
int sum[] = new int[matrix.length];
for(int i=0;i<matrix.length;i++)
for(int j=0;j<matrix[i].length;j++)
sum[i] = sum[i] + matrix[i][j];
return sum;
}
public static int[] sumCol(int[][] matrix)
{
int sum[] = new int[matrix[0].length];
for(int i=0;i<matrix.length;i++)
for(int j=0;j<matrix[i].length;j++)
sum[j] = sum[j] + matrix[i][j];
return sum;
}
public static void bubbleSort(int[] matrix)
{
for(int i = 0; i < matrix.length; i++)
for(int j = i+1 ; j < matrix.length;j++)
if(matrix[i]>matrix[j])
{
int temp = matrix[i];
matrix[i] = matrix[j];
matrix[j] = temp;
}
}
public static void selectionSort(int[] matrix)
{
int pos = -1;
for(int i = 0; i < matrix.length; i++)
{
pos = i;
for(int j = i+1 ;j < matrix.length; j++)
if(matrix[j]<matrix[pos])
pos = j;
int temp = matrix[pos];
matrix[pos] = matrix[i];
matrix[i] = temp;
}
}
public static int[] generateRandomMatrix(int size)
{
int[] matrix = new int[size];
int a;
for(int i=0;i<matrix.length;i++)
{
a = (int)(Math.random()*100);
if(a>0&&a<10)
matrix[i] = a;
else
i--;
}
return matrix;
}
public static void printMatrix(int[] mat)
{
for(int i = 0 ; i < mat.length ; i++ )
{
System.out.print(mat[i]+",");
}
}
public int arrsum(int[] result, int[] a) {
int sum = 0 ;
for(int i=0;i<a.length;i++)
sum = sum + a[i];
return sum;
}
public int ADD(int i, int j) {
int ADD = i + j;
return ADD;
}
}
| Java |
package com.felight;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class queue {
public static void main(String[] Felight){
Queue<String> queue = new LinkedList<String>();
queue.add("iphone 3GS");
queue.add("iphone 4");
queue.add("iphone 4S");
queue.add("iphone 5");
queue.add("iphone 5S");
System.out.println("Size of queue" +queue.size());
Iterator queueIterator = queue.iterator();
while(queueIterator.hasNext()){
System.out.println(" " +queueIterator.next());
}
queue.remove();queue.remove();queue.remove();
System.out.println("\nSize of Queue" +queue.size());
queueIterator = queue.iterator();
while(queueIterator.hasNext()){
System.out.println(" " +queueIterator.next());
}
}
}
| Java |
package com.felight;
public class A extends Thread{
public void run(){
this.doSomething();
}
public void doSomething(){
System.out.println("Thread A is running");
}
} | Java |
package com.felight;
import java.util.Comparator;
public class AddressSort implements Comparator<Employee> {
public int compare(Employee obj1,Employee obj2){
return obj1.getAddress().compareTo(obj2.getAddress());
}
}
| Java |
package com.felight;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class emplist {
public static void main(String[] Felight){
ArrayList<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(10, "aaa"));
empList.add(new Employee(11, "aba"));
empList.add(new Employee(12, "caa"));
empList.add(new Employee(13, "ada"));
empList.add(new Employee(14, "eaa"));
System.out.println("Unsorted:" +empList);
Collections.sort(empList);
System.out.println("sorted:" +empList);
}
}
| Java |
package com.felight;
public class thread {
public static void main(String[] Felight){
C cThread1 = new C();
cThread1.setName("good");
C cThread2 = new C();
cThread2.setName("bad");
C cThread3 = new C();
cThread3.setName("ugly");
D dThread1 = new D();
Thread t1 = new Thread(dThread1);
t1.setName("tom");
D dThread2 = new D();
Thread t2 = new Thread(dThread2);
t1.setName("dick");
D dThread3 = new D();
Thread t3 = new Thread(dThread3);
t1.setName("harry");
cThread1.start();
cThread2.start();
cThread3.start();
t1.start();
t2.start();
t3.start();
}
} | Java |
package com.felight;
import java.util.ArrayList;
public class Collections {
public static void main(String[] Felight){
ArrayList<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(10,"Jack Sparrow"));
empList.add(new Employee(11,"Boramir"));
empList.add(new Employee(12,"Frodo Baggins"));
empList.add(new Employee(13,"Gandalf"));
empList.add(new Employee(16,"Legolas Greenleaf"));
System.out.println("unsorted: "+ empList);
Collections.sort(empList);
System.out.println("sortted:" + empList);
}
static void sort(ArrayList<Employee> empList) {
java.util.Collections.sort(empList);
}
public static void sort(ArrayList<Employee> empList, AddressSort addressSort) {
java.util.Collections.sort(empList);
}
}
| Java |
class employee{
int id;
String name;
String address;
double salary;
}
| Java |
package com.felight;
import java.util.ArrayList;
public class comparator {
public static void main(String[] Feliight){
ArrayList<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(10, "Jack Sparrow", "pirates of the caribbean"));
empList.add(new Employee(11, "Boramir", "LOTR"));
empList.add(new Employee(12, "Frodo Baggins", "LOTR"));
empList.add(new Employee(13, "Gandalf", "LOTR"));
empList.add(new Employee(16, "Legolas Greenleaf", "LOTR"));
System.out.println("unsorted: "+ empList);
Collections.sort(empList);
System.out.println("sortted:" + empList);
AddressSort addressSort = new AddressSort();
Collections.sort(empList,addressSort);
System.out.println("Sorted by address using Comparator:\n" + empList );
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.model;
import java.util.List;
public class TworzenieAnkietyModel {
private Integer idNauczyciela;
private Integer idZajec;
private String tytul;
private List<String> pytania;
private String grupaAnkietowanych;
public Integer getIdNauczyciela() {
return idNauczyciela;
}
public void setIdNauczyciela(Integer idNauczyciela) {
this.idNauczyciela = idNauczyciela;
}
public Integer getIdZajec() {
return idZajec;
}
public void setIdZajec(Integer idZajec) {
this.idZajec = idZajec;
}
public String getTytul() {
return tytul;
}
public void setTytul(String tytul) {
this.tytul = tytul;
}
public List<String> getPytania() {
return pytania;
}
public void setPytania(List<String> pytania) {
this.pytania = pytania;
}
public String getGrupaAnkietowanych() {
return grupaAnkietowanych;
}
public void setGrupaAnkietowanych(String grupaAnkietowanych) {
this.grupaAnkietowanych = grupaAnkietowanych;
}
public String toString() {
return idNauczyciela + " | " + tytul + " | " + idZajec + " | " + pytania.toString();
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.model;
import java.util.List;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
public class AnkietaModel {
private String tytul;
private List<Nauczyciel> nauczyciele;
private Nauczyciel nauczyciel;
private Zajecia zajecia;
private List<Zajecia> zajeciaDlaNauczyciela;
private List<Szablon> szablony;
private List<Pytanie> pytaniaDlaSzablonu;
private List<Pytanie> pytania;
private List<Ankietowany> ankietowani;
private List<Ankietowany> ankietowaniDlaZajec;
public Zajecia getZajecia() {
return zajecia;
}
public void setZajecia(Zajecia zajecia) {
this.zajecia = zajecia;
}
public Nauczyciel getNauczyciel() {
return this.nauczyciel;
}
public String getTytul() {
return tytul;
}
public void setTytul(String tytul) {
this.tytul = tytul;
}
public List<Nauczyciel> getNauczyciele() {
return nauczyciele;
}
public void setNauczyciele(List<Nauczyciel> nauczyciele) {
this.nauczyciele = nauczyciele;
}
public List<Zajecia> getZajeciaDlaNauczyciela() {
return zajeciaDlaNauczyciela;
}
public void setZajeciaDlaNauczyciela(List<Zajecia> zajeciaDlaNauczyciela) {
this.zajeciaDlaNauczyciela = zajeciaDlaNauczyciela;
}
public List<Szablon> getSzablony() {
return szablony;
}
public void setSzablony(List<Szablon> szablony) {
this.szablony = szablony;
}
public List<Pytanie> getPytaniaDlaSzablonu() {
return pytaniaDlaSzablonu;
}
public void setPytaniaDlaSzablonu(List<Pytanie> pytaniaDlaSzablonu) {
this.pytaniaDlaSzablonu = pytaniaDlaSzablonu;
}
public List<Pytanie> getPytania() {
return pytania;
}
public void setPytania(List<Pytanie> pytania) {
this.pytania = pytania;
}
public List<Ankietowany> getAnkietowani() {
return ankietowani;
}
public void setAnkietowani(List<Ankietowany> ankietowani) {
this.ankietowani = ankietowani;
}
public List<Ankietowany> getAnkietowaniDlaZajec() {
return ankietowaniDlaZajec;
}
public void setAnkietowaniDlaZajec(List<Ankietowany> ankietowaniDlaZajec) {
this.ankietowaniDlaZajec = ankietowaniDlaZajec;
}
public void setNauczyciel(Nauczyciel nauczyciel) {
this.nauczyciel = nauczyciel;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.model;
import java.util.ArrayList;
import java.util.List;
public class WypelnianieAnkietyModel {
private List<String> odpowiedzi;
private Integer ankietaId;
public WypelnianieAnkietyModel() {
odpowiedzi = new ArrayList<String>();
ankietaId = -1;
}
public List<String> getOdpowiedzi() {
return odpowiedzi;
}
public void setOdpowiedzi(List<String> odpowiedzi) {
this.odpowiedzi = odpowiedzi;
}
public String toString() {
return odpowiedzi.toString();
}
public Integer getAnkietaId() {
return ankietaId;
}
public void setAnkietaId(Integer ankietaId) {
this.ankietaId = ankietaId;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankieta;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
import pl.wroc.pwr.ankieta.ankietyzacja.model.TworzenieAnkietyModel;
import pl.wroc.pwr.ankieta.ankietyzacja.model.AnkietaModel;
import pl.wroc.pwr.ankieta.ankietyzacja.service.AnkietaService;
import pl.wroc.pwr.ankieta.ankietyzacja.service.AnkietowanyService;
import pl.wroc.pwr.ankieta.ankietyzacja.service.NauczycielService;
import pl.wroc.pwr.ankieta.ankietyzacja.service.PytanieService;
import pl.wroc.pwr.ankieta.ankietyzacja.service.SzablonService;
import pl.wroc.pwr.ankieta.ankietyzacja.service.ZajeciaService;
@Controller
@RequestMapping("/ankieta")
public class NowaAnkietaController {
@Autowired
NauczycielService nauczycielService;
@Autowired
ZajeciaService zajeciaService;
@Autowired
AnkietowanyService ankietowanyService;
@Autowired
SzablonService szablonService;
PytanieService pytanieSzablon;
@Autowired
AnkietaService ankietaService;
@ModelAttribute("model")
public TworzenieAnkietyModel construct() {
return new TworzenieAnkietyModel();
}
@RequestMapping("/nowaAnkieta")
public String nowaAnkieta(Model model) {
return "nowaAnkieta";
}
@RequestMapping(value="/krok1", method = RequestMethod.POST, produces = "text/html")
public String loadKrok1(Model model, AnkietaModel model1, Integer idNauczyciela) {
Nauczyciel nauczyciel = nauczycielService.findById(idNauczyciela);
model1.setNauczyciel(nauczyciel);
List<Nauczyciel> nauczyciele = nauczycielService.findAll();
model1.setNauczyciele(nauczyciele);
List<Zajecia> zajeciaDlaNauczyciela = null;
if (model1.getNauczyciel() == null) {
model1.setNauczyciel(nauczyciele.get(0));
zajeciaDlaNauczyciela = zajeciaService.findAllForNauczyciel(model1.getNauczyciel());
} else {
zajeciaDlaNauczyciela = zajeciaService.findAllForNauczyciel(model1.getNauczyciel());
}
model1.setZajeciaDlaNauczyciela(zajeciaDlaNauczyciela);
model.addAttribute("ankietaModel", model1);
return "krok1";
}
@RequestMapping(value="/krok2", method = RequestMethod.POST, produces = "text/html")
public String loadKrok2(Model model, AnkietaModel model2, Integer idZajec) {
Zajecia zajecia = zajeciaService.findById(idZajec);
model2.setZajecia(zajecia);
List<Ankietowany> ankietowaniZZajec = ankietowanyService.findAllForZajecia(model2.getZajecia());
model2.setAnkietowaniDlaZajec(ankietowaniZZajec);
model.addAttribute("ankietaModel", model2);
return "krok2";
}
@RequestMapping(value="/krok3", method = RequestMethod.POST, produces = "text/html")
public String loadKrok3(Model model, AnkietaModel model3) {
List<Szablon> szablony = szablonService.findAll();
model3.setSzablony(szablony);
model.addAttribute("ankietaModel", model3);
return "krok3";
}
public String applySzablon(AnkietaModel model) {
return "";
}
@RequestMapping(value="/zapisz", method = RequestMethod.POST)
public String createAnkieta(@ModelAttribute("model") TworzenieAnkietyModel model) {
model.getPytania().remove(model.getPytania().size() - 1);
Ankieta ankieta = ankietaService.createAnkieta(model);
ankietaService.save(ankieta);
return "dodanaAnkieta";
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login() {
return "login";
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankieta;
import pl.wroc.pwr.ankieta.ankietaService.entity.AnkietaAnkietowanego;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Audytor;
import pl.wroc.pwr.ankieta.ankietaService.entity.Otwarte;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
import pl.wroc.pwr.ankieta.ankietaService.entity.WariantOdpowiedzi;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zamkniete;
import pl.wroc.pwr.ankieta.ankietaService.repository.AnkietaRepository;
import pl.wroc.pwr.ankieta.ankietyzacja.model.TworzenieAnkietyModel;
import pl.wroc.pwr.ankieta.ankietyzacja.model.AnkietaModel;
@Service
public class AnkietaService {
@Autowired
private AnkietaRepository ankietaRepository;
@Autowired
private AudytorService audytorService;
@Autowired
private ZajeciaService zajeciaService;
@Autowired
private ZamknieteService zamknieteService;
@Autowired
private OtwarteService otwarteService;
@Autowired
private WariantOdpowiedziService wariantOdpowiedziService;
@Autowired
private AnkietowanyService ankietowanyService;
public Ankieta loadAnkieta(Integer idAnkiety) {
throw new UnsupportedOperationException();
}
public Ankieta createAnkieta(TworzenieAnkietyModel model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Audytor audytor = audytorService.findByEmail(authentication.getName());
model.getGrupaAnkietowanych();
Zajecia zajecia = zajeciaService.findById(model.getIdZajec());
Ankieta ankieta = new Ankieta();
save(ankieta);
ankieta.setTytul(model.getTytul());
ankieta.setTerminRozpoczecia(new Date());
ankieta.setTerminZakonczenia(getEndDateMock());
ankieta.setAudytor(audytor);
ankieta.setZajecia(zajecia);
ankieta.setGrupaAnkietowanych(readStudentsFromJSON(model.getGrupaAnkietowanych()));
List<Pytanie> pytania = new ArrayList<Pytanie>();
for (int i = 0; i < model.getPytania().size(); i++) {
Pytanie pytanie = readQuestionFromJSONAndSave(model.getPytania().get(i), ankieta);
pytania.add(pytanie);
}
ankieta.setPytania(pytania);
return ankieta;
}
private List<Ankietowany> readStudentsFromJSON(String json) {
List<Ankietowany> studentsGroup = new ArrayList<Ankietowany>();
JSONObject jsonObject = new JSONObject(json);
JSONArray group = jsonObject.getJSONArray("grupa");
for (int i = 0; i < group.length(); i++) {
Integer id = group.getJSONObject(i).getInt("id");
Ankietowany ankietowany = ankietowanyService.findOneById(id);
studentsGroup.add(ankietowany);
}
return studentsGroup;
}
private Pytanie readQuestionFromJSONAndSave(String json, Ankieta ankieta) {
JSONObject jsonObject = new JSONObject(json);
String content = jsonObject.getString("tresc");
Boolean isOpened = jsonObject.getBoolean("czyOtwarte");
Boolean isNumeric = jsonObject.getBoolean("czyLiczbowy");
JSONArray variants = jsonObject.getJSONArray("warianty");
if (isOpened) {
Otwarte question = new Otwarte();
question.setTresc(content);
question.setAnkieta(ankieta);
return otwarteService.save(question);
} else {
Zamkniete question = new Zamkniete();
question.setTresc(content);
question.setAnkieta(ankieta);
zamknieteService.save(question);
for (int i = 0; i < variants.length(); i++) {
String variantContent = variants.getJSONObject(i).getString("tresc");
WariantOdpowiedzi answerVariant = new WariantOdpowiedzi();
answerVariant.setCzyLiczbowy(isNumeric);
answerVariant.setTresc(variantContent);
answerVariant.setPytanieZamkniete(question);
wariantOdpowiedziService.save(answerVariant);
question.addWariantOdpowiedzi(answerVariant);
}
return zamknieteService.save(question);
}
}
private Date getEndDateMock() {
Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.DECEMBER, 31, 0, 0, 0);
return calendar.getTime();
}
public Ankieta save(Ankieta ankieta) {
return ankietaRepository.save(ankieta);
}
public Ankieta findAnkieta(Integer idAnkiety) {
return ankietaRepository.findOne(idAnkiety);
}
public List<Ankieta> findAll() {
return ankietaRepository.findAll();
}
public List<Ankieta> findAllAvailableForAnkietowany(Ankietowany ankietowany) {
List<Ankieta> result = new ArrayList<Ankieta>();
for(Ankieta ankieta : findAll()) {
if(isAnkietaAvailable(ankieta) && isAnkietowanyOfAnkieta(ankietowany, ankieta) && isAnkietaNotDoneYet(ankieta, ankietowany)) {
result.add(ankieta);
}
}
return result;
}
private boolean isAnkietaAvailable(Ankieta ankieta) {
Date now = new Date();
return ankieta.getTerminRozpoczecia().before(now) && ankieta.getTerminZakonczenia().after(now);
}
private boolean isAnkietowanyOfAnkieta(Ankietowany ankietowany, Ankieta ankieta) {
for(Ankieta a : ankietowany.getAnkiety()) {
if(ankieta.getId().equals(a.getId())) {
return true;
}
}
return false;
}
private boolean isAnkietaNotDoneYet(Ankieta ankieta, Ankietowany ankietowany) {
for(AnkietaAnkietowanego ankietaAnkietowanego : ankietowany.getAnkietaAnkietowanego()) {
if(ankietaAnkietowanego.getAnkieta().getId().equals(ankieta.getId()) && ankietaAnkietowanego.getCzyUkonczona()) {
return false;
}
}
return true;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zamkniete;
import pl.wroc.pwr.ankieta.ankietaService.repository.ZamknieteRepository;
@Service
public class ZamknieteService {
@Autowired
private ZamknieteRepository zamknieteRepository;
public Zamkniete save(Zamkniete zamkniete) {
return zamknieteRepository.save(zamkniete);
}
public List<Pytanie> findAllForSzablon(Szablon szablon) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
import pl.wroc.pwr.ankieta.ankietaService.repository.SzablonRepository;
@Service
public class SzablonService {
@Autowired
SzablonRepository szablonRepository;
public List<Szablon> findAll() {
return szablonRepository.findAll();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Audytor;
import pl.wroc.pwr.ankieta.ankietaService.repository.AudytorRepository;
@Service
public class AudytorService {
@Autowired
AudytorRepository audytorRepository;
public Audytor findByEmail(String email) {
return audytorRepository.findByEmail(email);
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
import pl.wroc.pwr.ankieta.ankietaService.repository.PytanieRepository;
@Service
public class PytanieService {
PytanieRepository repository;
public List<Pytanie> findAllForSzablon(Szablon szablon) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.WariantOdpowiedzi;
import pl.wroc.pwr.ankieta.ankietaService.repository.WariantOdpowiedziRepository;
@Service
public class WariantOdpowiedziService {
@Autowired
private WariantOdpowiedziRepository wariantOdpowiedziRepository;
public WariantOdpowiedzi save(WariantOdpowiedzi wariant) {
return wariantOdpowiedziRepository.save(wariant);
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankieta;
import pl.wroc.pwr.ankieta.ankietaService.entity.AnkietaAnkietowanego;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Odpowiedz;
import pl.wroc.pwr.ankieta.ankietaService.entity.OdpowiedzPytanieOtwarte;
import pl.wroc.pwr.ankieta.ankietaService.entity.Otwarte;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
import pl.wroc.pwr.ankieta.ankietaService.entity.WariantOdpowiedzi;
import pl.wroc.pwr.ankieta.ankietaService.entity.WybranaOdpowiedz;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zamkniete;
import pl.wroc.pwr.ankieta.ankietaService.repository.AnkietaAnkietowanegoRepository;
import pl.wroc.pwr.ankieta.ankietyzacja.model.WypelnianieAnkietyModel;
@Service
public class AnkietaAnkietowanegoService {
@Autowired
AnkietaAnkietowanegoRepository ankietaAnkietowanegoRepository;
public AnkietaAnkietowanego createAnkietaAnkietowanego(WypelnianieAnkietyModel model, Ankieta ankieta, Ankietowany ankietowany) {
AnkietaAnkietowanego ankietaAnkietowanego = new AnkietaAnkietowanego();
ankietaAnkietowanego.setAnkieta(ankieta);
ankietaAnkietowanego.setAnkietowany(ankietowany);
ankietaAnkietowanego.setOdpowiedzi(convertOdpowiedziFromViewToListOfOdpowiedz(model.getOdpowiedzi(), ankieta.getPytania()));
return ankietaAnkietowanego;
}
public AnkietaAnkietowanego save(AnkietaAnkietowanego ankietaAnkietowanego) {
ankietaAnkietowanego.setCzyUkonczona(true);
return ankietaAnkietowanegoRepository.save(ankietaAnkietowanego);
}
private List<Odpowiedz> convertOdpowiedziFromViewToListOfOdpowiedz(List<String> odpowiedzi, List<Pytanie> pytania) {
List<Odpowiedz> result = new ArrayList<Odpowiedz>();
for(int i = 0; i<pytania.size(); i++) {
Odpowiedz odpowiedz = null;
if(pytania.get(i) instanceof Otwarte) {
odpowiedz = new OdpowiedzPytanieOtwarte(odpowiedzi.get(i));
}
else {
Zamkniete zamkniete = (Zamkniete)pytania.get(i);
WariantOdpowiedzi wybranyWariant = getWariantWithTresc(zamkniete.getWariantyOdpowiedzi(), odpowiedzi.get(i));
odpowiedz = new WybranaOdpowiedz(wybranyWariant);
}
odpowiedz.setPytanie(pytania.get(i));
result.add(odpowiedz);
}
return result;
}
private WariantOdpowiedzi getWariantWithTresc(Collection<WariantOdpowiedzi> warianty, String tresc) {
Iterator<WariantOdpowiedzi> wariantyIterator = warianty.iterator();
while(wariantyIterator.hasNext()) {
WariantOdpowiedzi wariant = wariantyIterator.next();
if(wariant.getTresc().equals(tresc)) {
return wariant;
}
}
return null;
}
public AnkietaAnkietowanego findAnkietaAnkietowanego(int id) {
return ankietaAnkietowanegoRepository.findOne(id);
}
public List<AnkietaAnkietowanego> findAll() {
return ankietaAnkietowanegoRepository.findAll();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
import pl.wroc.pwr.ankieta.ankietaService.repository.AnkietowanyRepository;
@Service
public class AnkietowanyService {
@Autowired
AnkietowanyRepository ankietowanyRepository;
public Ankietowany findOneById(Integer id) {
return ankietowanyRepository.findOne(id);
}
public List<Ankietowany> findAllForZajecia(Zajecia zajecia) {
return ankietowanyRepository.findAllForZajecia(zajecia);
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Otwarte;
import pl.wroc.pwr.ankieta.ankietaService.repository.OtwarteRepository;
@Service
public class OtwarteService {
@Autowired
private OtwarteRepository otwarteRepository;
public Otwarte save(Otwarte otwarte) {
return otwarteRepository.save(otwarte);
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Uzytkownik;
import pl.wroc.pwr.ankieta.ankietaService.repository.UzytkownikRepository;
@Service
@Transactional
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public class UzytkownikService {
@Autowired
private UzytkownikRepository uzytkownikRepository;
private BCryptPasswordEncoder encoder;
public BCryptPasswordEncoder getEncoder() {
if (encoder == null) {
encoder = new BCryptPasswordEncoder();
}
return encoder;
}
public List<Uzytkownik> findAll() {
return uzytkownikRepository.findAll();
}
public Uzytkownik findOne(String email) {
return uzytkownikRepository.findByEmail(email);
}
public Uzytkownik getLoggedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return findOne(authentication.getName());
}
public Uzytkownik registerUser(Uzytkownik user) {
user.setHaslo(encryptPassword(user.getHaslo()));
return uzytkownikRepository.save(user);
}
public Uzytkownik updatePassword(String name, String password) {
Uzytkownik user = findOne(name);
user.setHaslo(encryptPassword(password));
return uzytkownikRepository.save(user);
}
public String encryptPassword(String plainPassword) {
return getEncoder().encode(plainPassword);
}
public Boolean isLoggedUserPasswordCorrect(String password) {
Uzytkownik loggedUser = getLoggedUser();
return getEncoder().matches(password, loggedUser.getHaslo());
}
public Boolean canChangePassword(String oldPassword, String newPassword, String confirmPassword) {
return isLoggedUserPasswordCorrect(oldPassword) && newPassword.equals(confirmPassword);
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.ankietaService.repository.NauczycielRepository;
@Service
public class NauczycielService {
@Autowired
NauczycielRepository nauczycielRepository;
public List<Nauczyciel> findAll() {
return nauczycielRepository.findAll();
}
public Nauczyciel findById(Integer id) {
return nauczycielRepository.findById(id);
}
} | Java |
package pl.wroc.pwr.ankieta.ankietyzacja.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
import pl.wroc.pwr.ankieta.ankietaService.repository.ZajeciaRepository;
@Service
public class ZajeciaService {
@Autowired
ZajeciaRepository zajeciaRepository;
public List<Zajecia> findAllForNauczyciel(Nauczyciel nauczyciel) {
return zajeciaRepository.findAllForNauczyciel(nauczyciel);
}
public Zajecia findById(Integer id) {
return zajeciaRepository.findById(id);
}
} | Java |
package pl.wroc.pwr.agile.analizaWynikow;
public abstract class AnalizatorWynikow {
public abstract void analizuj();
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { UniqueEmailValidator.class })
public @interface UniqueEmail {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import pl.wroc.pwr.ankieta.ankietaService.repository.UzytkownikRepository;
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String>{
@Autowired
private UzytkownikRepository userRepository;
public void initialize(UniqueEmail constraintAnnotation) {
}
public boolean isValid(String email, ConstraintValidatorContext context) {
if (userRepository == null) {
return true;
}
return userRepository.findByEmail(email) == null;
}
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.WariantOdpowiedzi;
@Repository
public interface WariantOdpowiedziRepository extends JpaRepository<WariantOdpowiedzi, Integer> {
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Audytor;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
@Repository
public interface AudytorRepository extends JpaRepository<Audytor, Integer> {
public Audytor findByEmail(String email);
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Kurs;
@Repository
public interface KursRepository extends JpaRepository<Kurs, Integer> {
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
public interface ZajeciaRepository extends JpaRepository<Zajecia, Integer> {
@Query("select z from Zajecia z join z.nauczyciele n where n = ?1")
public List<Zajecia> findAllForNauczyciel(Nauczyciel nauczyciel);
public Zajecia findById(Integer id);
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zamkniete;
@Repository
public interface ZamknieteRepository extends JpaRepository<Zamkniete, Integer> {
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Pytanie;
@Repository
public interface PytanieRepository extends JpaRepository<Pytanie, Integer> {
//TODO:public List<Pytanie> findAllForSzablon(Szablon szablon);
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankieta;
@Repository
public interface AnkietaRepository extends JpaRepository<Ankieta, Integer> {
//TODO:public Ankieta loadAnkieta(Integer idAnkiety);
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Uzytkownik;
@Repository
public interface UzytkownikRepository extends JpaRepository<Uzytkownik, Integer> {
Uzytkownik findByEmail(String email);
}
| Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Otwarte;
@Repository
public interface OtwarteRepository extends JpaRepository<Otwarte, Integer> {
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Szablon;
@Repository
public interface SzablonRepository extends JpaRepository<Szablon, Integer> {
public List<Szablon> findAll();
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.AnkietaAnkietowanego;
@Repository
public interface AnkietaAnkietowanegoRepository extends JpaRepository<AnkietaAnkietowanego, Integer> {
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Nauczyciel;
@Repository
public interface NauczycielRepository extends JpaRepository<Nauczyciel, Integer> {
public List<Nauczyciel> findAll();
public Nauczyciel findById(Integer id);
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import pl.wroc.pwr.ankieta.ankietaService.entity.Ankietowany;
import pl.wroc.pwr.ankieta.ankietaService.entity.Zajecia;
@Repository
public interface AnkietowanyRepository extends JpaRepository<Ankietowany, Integer> {
@Query("select a from Ankietowany a join a.zajecia z where z = ?1")
public List<Ankietowany> findAllForZajecia(Zajecia zajecia);
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
public class KierownikJednostki extends Uzytkownik {
Nauczyciel podwladny;
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Ankieta {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "audytor_id", nullable = true)
private Audytor audytor;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Pytanie> pytania;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "Ankieta_Ankietowany", joinColumns = {
@JoinColumn(name = "ankieta_id", nullable = true, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "ankietowany_id",
nullable = true, updatable = false) })
private Collection<Ankietowany> grupaAnkietowanych;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "zajecia_id", nullable = true)
private Zajecia zajecia;
@OneToMany
@JoinTable(name = "Ankieta_Zainteresowany", joinColumns = {
@JoinColumn(name = "ankieta_id", nullable = true, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "zainteresowany_id",
nullable = true, updatable = false) })
private Collection<Uzytkownik> zainteresowani;
@OneToMany(targetEntity=AnkietaAnkietowanego.class, mappedBy="ankieta", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Collection<AnkietaAnkietowanego> ankietyAnkietowanych;
@Id
@GeneratedValue
private Integer id;
private String tytul;
private Date terminRozpoczecia;
private Date terminZakonczenia;
private String komentarzDoWyniku;
public Audytor getAudytor() {
return audytor;
}
public void setAudytor(Audytor audytor) {
this.audytor = audytor;
}
public List<Pytanie> getPytania() {
return pytania;
}
public void setPytania(List<Pytanie> pytania) {
this.pytania = pytania;
}
public Collection<Ankietowany> getGrupaAnkietowanych() {
return grupaAnkietowanych;
}
public void setGrupaAnkietowanych(Collection<Ankietowany> grupaAnkietowanych) {
this.grupaAnkietowanych = grupaAnkietowanych;
}
public Zajecia getZajecia() {
return zajecia;
}
public void setZajecia(Zajecia zajecia) {
this.zajecia = zajecia;
}
public Collection<Uzytkownik> getZainteresowani() {
return zainteresowani;
}
public void setZainteresowani(Collection<Uzytkownik> zainteresowani) {
this.zainteresowani = zainteresowani;
}
public Integer getId() {
return id;
}
public String getTytul() {
return tytul;
}
public void setTytul(String tytul) {
this.tytul = tytul;
}
public Date getTerminRozpoczecia() {
return terminRozpoczecia;
}
public void setTerminRozpoczecia(Date terminRozpoczecia) {
this.terminRozpoczecia = terminRozpoczecia;
}
public Date getTerminZakonczenia() {
return terminZakonczenia;
}
public void setTerminZakonczenia(Date terminZakonczenia) {
this.terminZakonczenia = terminZakonczenia;
}
public String getKomentarzDoWyniku() {
return komentarzDoWyniku;
}
public void setKomentarzDoWyniku(String komentarzDoWyniku) {
this.komentarzDoWyniku = komentarzDoWyniku;
}
public Collection<AnkietaAnkietowanego> getAnkietyAnkietowanych() {
return ankietyAnkietowanych;
}
public void setAnkietyAnkietowanych(
Collection<AnkietaAnkietowanego> ankietyAnkietowanych) {
this.ankietyAnkietowanych = ankietyAnkietowanych;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
public enum DzienTygodnia {
Poniedzialek("pn"),
Wtorek("wt"),
Sroda("sr"),
Czwartek("cz"),
Piatek("pt"),
Sobota("sb"),
Niedziela("nd");
String skrot;
private DzienTygodnia(String skrot) {
this.skrot = skrot;
}
public String toString() {
return skrot;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Synonim {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "nadrzedny_id", nullable = false)
private Synonim synonimNadrzedny;
@OneToMany(mappedBy="synonimNadrzedny", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Collection<Synonim> synonimy;
@Id
@GeneratedValue
private Integer id;
private String slowo;
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.