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.data;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.EventListener;
import java.util.EventObject;
import java.util.List;
import java.util.Locale;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.Coefficients;
import org.concordiainternational.competition.utils.EventHelper;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.concordiainternational.competition.utils.Notifier;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.OptimisticLockType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.EventRouter;
import com.vaadin.event.MethodEventSource;
/**
* This class stores all the information related to a particular participant.
* <p>
* All persistent properties are managed by Java Persistance annotations.
* "Field" access mode is used, meaning that it is the values of the fields that
* are stored, and not the values returned by the getters. Note that it is often
* necessary to know when a value has been captured or not -- this is why values
* are stored as Integers or Doubles, so that we can use null to indicate that a
* value has not been captured.
* </p>
* <p>
* This allows us to use the getters to return the values as they will be
* displayed by the application
* </p>
* <p>
* Computed fields are defined as final transient properties and marked as
* @Transient; the only reason for this is so the JavaBeans introspection
* mechanisms find them.
* </p>
* <p>
* This class uses events to notify interested user interface
* components that fields or computed values have changed. In this
* way the user interface does not have to know that the category
* field on the screen is dependent on the bodyweight and the gender
* -- all the dependency logic is kept at the business object level.
* </p>
*
* @author jflamy
*
*/
@Entity
@org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.VERSION)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Lifter implements MethodEventSource, Notifier {
/**
* Lifter events all derive from this.
*/
public class UpdateEvent extends EventObject {
private static final long serialVersionUID = -126644150054472005L;
private List<String> propertyIds;
/**
* 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(Lifter source, String... propertyIds) {
super(source);
this.propertyIds = Arrays.asList(propertyIds);
}
public List<String> getPropertyIds() {
return propertyIds;
}
}
/**
* Listener interface for receiving <code>Lifter.UpdateEvent</code>s.
*/
public interface UpdateEventListener extends java.util.EventListener {
/**
* This method will be invoked when a Lifter.UpdateEvent is fired.
*
* @param updateEvent
* the event that has occured.
*/
public void updateEvent(Lifter.UpdateEvent updateEvent);
}
private static final long serialVersionUID = -7046330458901785754L;
private static final Logger logger = LoggerFactory.getLogger(Lifter.class);
static CategoryLookup categoryLookup = null;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long version;
Integer lotNumber = null;
Integer startNumber = null; // for masters.
String firstName = ""; //$NON-NLS-1$
String lastName = ""; //$NON-NLS-1$
String club = ""; //$NON-NLS-1$
String gender = ""; //$NON-NLS-1$
Integer ageGroup = 0;
Integer birthDate = 1900;
Double bodyWeight = null;
String membership = ""; //$NON-NLS-1$
@ManyToOne
CompetitionSession competitionSession;
// This is brute force, but having embedded classes does not bring much
// and we don't want joins or other such logic for the lifter card.
// Since the lifter card is 6 x 4 items, we take the simple route.
// Note: we use Strings because we need to distinguish actually entered
// values (such as 0)
// from empty cells. Using Integers or Doubles would work as well, but many
// people want to type
// "-" or other things in the cells, so Strings are actually easier.
@ManyToOne
Category registrationCategory = null;
String snatch1Declaration;
String snatch1Change1;
String snatch1Change2;
String snatch1ActualLift;
Date snatch1LiftTime;
String snatch2Declaration;
String snatch2Change1;
String snatch2Change2;
String snatch2ActualLift;
Date snatch2LiftTime;
String snatch3Declaration;
String snatch3Change1;
String snatch3Change2;
String snatch3ActualLift;
Date snatch3LiftTime;
String cleanJerk1Declaration;
String cleanJerk1Change1;
String cleanJerk1Change2;
String cleanJerk1ActualLift;
Date cleanJerk1LiftTime;
String cleanJerk2Declaration;
String cleanJerk2Change1;
String cleanJerk2Change2;
String cleanJerk2ActualLift;
Date cleanJerk2LiftTime;
String cleanJerk3Declaration;
String cleanJerk3Change1;
String cleanJerk3Change2;
String cleanJerk3ActualLift;
Date cleanJerk3LiftTime;
Integer snatchRank;
Integer cleanJerkRank;
Integer totalRank;
Integer sinclairRank;
Integer customRank;
Float snatchPoints;
Float cleanJerkPoints;
Float totalPoints; // points based on totalRank
Float sinclairPoints;
Float customPoints;
Integer teamSinclairRank;
Integer teamSnatchRank;
Integer teamCleanJerkRank;
Integer teamTotalRank;
Integer teamCombinedRank;
Boolean teamMember = true; // false if substitute; note that we consider null to be true.;
Integer qualifyingTotal = 0;
/*
* Computed properties. We create them here because we want the
* corresponding accessors to be discovered by introspection. Setters are
* not defined (the fields are final). Getters perform the required
* computation.
*
* BEWARE: the variables defined here must NOT be used -- you must be able
* to comment them out and get no compilation errors. All the code should
* use the getters only.
*/
@Transient
final transient String snatch1AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient String snatch2AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient String snatch3AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient String cleanJerk1AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient String cleanJerk2AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient String cleanJerk3AutomaticProgression = ""; //$NON-NLS-1$
@Transient
final transient Integer bestSnatch = 0;
@Transient
final transient Integer bestCleanJerk = 0;
@Transient
final transient Integer total = 0;
@Transient
final transient Integer attemptsDone = 0;
@Transient
final transient Integer snatchAttemptsDone = 0;
@Transient
final transient Integer cleanJerkAttemptsDone = 0;
@Transient
Date lastLiftTime = null;
@Transient
final transient Integer nextAttemptRequestedWeight = 0;
/*
* Non-persistent properties. These properties are used during computations,
* but need not be stored in the database
*/
@Transient
Integer liftOrderRank = 0;
@Transient
Integer resultOrderRank = 0;
@Transient
boolean currentLifter = false;
@Transient
boolean forcedAsCurrent = false;
/*
* Transient fields that have no relevance to the persistent state of a
* lifter All framework-related and pattern-related constructs go here.
*/
@Transient
private EventRouter eventRouter;
private Double customScore;
/**
* 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$;
@SuppressWarnings("unchecked")
static public List<Lifter> getAll() {
return CompetitionApplication.getCurrent().getHbnSession().createCriteria(Lifter.class).list();
}
public static boolean isEmpty(String value) {
return (value == null) || value.trim().isEmpty();
}
public static int zeroIfInvalid(String value) {
try {
return Integer.valueOf(value);
} catch (NumberFormatException nfe) {
return 0;
}
}
public Lifter() {
super();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#addListener(java.lang.Class,
* java.lang.Object, java.lang.reflect.Method)
*/
@Override
@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)
*/
@Override
@SuppressWarnings({ "rawtypes" })
public void addListener(Class eventType, Object object, String methodName) {
getEventRouter().addListener(eventType, object, methodName);
}
/**
* Register a new Lifter.Listener object with a Lifter in order to be
* informed of updates.
*
* @param listener
*/
@Override
public void addListener(EventListener listener) {
getEventRouter().addListener(UpdateEvent.class, listener, LIFTER_EVENT_METHOD);
}
public void failedLift() {
logger.debug("{}", this); //$NON-NLS-1$
final String weight = Integer.toString(-getNextAttemptRequestedWeight());
doLift(weight);
}
/**
* @return the ageGroup
*/
public Integer getAgeGroup() {
if (this.birthDate == null || this.gender == null || this.gender.trim().isEmpty()) {
return null;
}
int year1 = Calendar.getInstance().get(Calendar.YEAR);
final int age = year1 - this.birthDate;
if (age < 30) {
return null;
}
int ageGroup1 = (int) (Math.ceil(age / 5) * 5);
if (this.getGender().equals("F") && ageGroup1 >= 65) { //$NON-NLS-1$
return 65;
}
if (this.getGender().equals("M") && ageGroup1 >= 80) { //$NON-NLS-1$
return 80;
}
// normal case
return ageGroup1;
}
/**
* @return the ageGroup
*/
public String getMastersAgeGroupInterval() {
Integer ageGroup1 = getAgeGroup();
if (this.getGender().equals("F") && ageGroup1 >= 65) { //$NON-NLS-1$
return "65+";
}
if (this.getGender().equals("M") && ageGroup1 >= 80) { //$NON-NLS-1$
return "80+";
}
return ageGroup1 + "-" + (ageGroup1 + 4);
}
public String getMastersGenderAgeGroupInterval() {
Integer ageGroup1 = getAgeGroup();
if (this.getGender().equals("F") && ageGroup1 >= 65) { //$NON-NLS-1$
return "F65+";
}
if (this.getGender().equals("M") && ageGroup1 >= 80) { //$NON-NLS-1$
return "M80+";
}
return getGender().toUpperCase() + ageGroup1 + "-" + (ageGroup1 + 4);
}
/**
* @return the attemptsDone
*/
public Integer getAttemptsDone() {
return getSnatchAttemptsDone() + getCleanJerkAttemptsDone();
}
/**
* @return the bestCleanJerk
*/
public Integer getBestCleanJerk() {
final int cj1 = zeroIfInvalid(cleanJerk1ActualLift);
final int cj2 = zeroIfInvalid(cleanJerk2ActualLift);
final int cj3 = zeroIfInvalid(cleanJerk3ActualLift);
return max(0, cj1, cj2, cj3);
}
public int getBestCleanJerkAttemptNumber() {
int referenceValue = getBestCleanJerk();
if (referenceValue > 0) {
if (zeroIfInvalid(cleanJerk3ActualLift) == referenceValue) return 6;
if (zeroIfInvalid(cleanJerk2ActualLift) == referenceValue) return 5;
if (zeroIfInvalid(cleanJerk1ActualLift) == referenceValue) return 4;
}
return 0; // no match - bomb-out.
}
public int getBestResultAttemptNumber() {
int referenceValue = getBestCleanJerk();
if (referenceValue > 0) {
if (zeroIfInvalid(cleanJerk3ActualLift) == referenceValue) return 6;
if (zeroIfInvalid(cleanJerk2ActualLift) == referenceValue) return 5;
if (zeroIfInvalid(cleanJerk1ActualLift) == referenceValue) return 4;
} else {
if (referenceValue > 0) {
referenceValue = getBestSnatch();
if (zeroIfInvalid(snatch3ActualLift) == referenceValue) return 3;
if (zeroIfInvalid(snatch2ActualLift) == referenceValue) return 2;
if (zeroIfInvalid(snatch1ActualLift) == referenceValue) return 1;
}
}
return 0; // no match - bomb-out.
}
/**
* @return the bestSnatch
*/
public Integer getBestSnatch() {
final int sn1 = zeroIfInvalid(snatch1ActualLift);
final int sn2 = zeroIfInvalid(snatch2ActualLift);
final int sn3 = zeroIfInvalid(snatch3ActualLift);
return max(0, sn1, sn2, sn3);
}
public int getBestSnatchAttemptNumber() {
int referenceValue = getBestSnatch();
if (referenceValue > 0) {
if (zeroIfInvalid(snatch3ActualLift) == referenceValue) return 3;
if (zeroIfInvalid(snatch2ActualLift) == referenceValue) return 2;
if (zeroIfInvalid(snatch1ActualLift) == referenceValue) return 1;
}
return 0; // no match - bomb-out.
}
/* *****************************************************************************************
* Actual persisted properties.
*/
/**
* @return the birthDate
*/
public Integer getBirthDate() {
return birthDate;
};
/**
* @return the bodyWeight
*/
public Double getBodyWeight() {
return bodyWeight;
}
/**
* @return the category
*/
public Category getCategory() {
final CategoryLookup categoryLookup1 = CategoryLookup.getSharedInstance();
final Category lookup = categoryLookup1.lookup(this.gender, this.bodyWeight);
// System.err.println("getCategory: "+this.gender+","+this.bodyWeight+" = "+(lookup
// == null? null: lookup.getName()));
return lookup;
};
/**
* Compute the body weight at the maximum weight of the lifter's category.
* Note: for the purpose of this computation, only "official" categories are
* used as the purpose is to totalRank athletes according to their
* competition potential.
*
* @return
*/
public Double getCategorySinclair() {
Category category = getCategory();
if (category == null) return 0.0;
Double categoryWeight = category.getMaximumWeight();
final Integer total1 = getTotal();
if (total1 == null || total1 < 0.1) return 0.0;
if (getGender().equalsIgnoreCase("M")) { //$NON-NLS-1$
if (categoryWeight < 56.0) {
categoryWeight = 56.0;
} else if (categoryWeight > Coefficients.menMaxWeight()) {
categoryWeight = Coefficients.menMaxWeight();
}
} else {
if (categoryWeight < 48.0) {
categoryWeight = 48.0;
} else if (categoryWeight > Coefficients.menMaxWeight()) {
categoryWeight = Coefficients.womenMaxWeight();
}
}
return getSinclair(categoryWeight);
};
public String getCleanJerk1ActualLift() {
return emptyIfNull(cleanJerk1ActualLift);
};
public Integer getCleanJerk1AsInteger() {
return asInteger(cleanJerk1ActualLift);
}
/**
* @return
*/
protected Integer asInteger(String stringValue) {
if (stringValue == null) return null;
try {
return Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
return null;
}
};
public String getCleanJerk1AutomaticProgression() {
return "-"; // there is no such thing. //$NON-NLS-1$
};
public String getCleanJerk1Change1() {
return emptyIfNull(cleanJerk1Change1);
};
public String getCleanJerk1Change2() {
return emptyIfNull(cleanJerk1Change2);
};
public String getCleanJerk1Declaration() {
return emptyIfNull(cleanJerk1Declaration);
};
public Date getCleanJerk1LiftTime() {
return cleanJerk1LiftTime;
}
public String getCleanJerk2ActualLift() {
return emptyIfNull(cleanJerk2ActualLift);
}
public Integer getCleanJerk2AsInteger() {
return asInteger(cleanJerk2ActualLift);
}
public String getCleanJerk2AutomaticProgression() {
final int prevVal = zeroIfInvalid(cleanJerk1ActualLift);
return doAutomaticProgression(prevVal);
}
public String getCleanJerk2Change1() {
return emptyIfNull(cleanJerk2Change1);
}
public String getCleanJerk2Change2() {
return emptyIfNull(cleanJerk2Change2);
}
public String getCleanJerk2Declaration() {
return emptyIfNull(cleanJerk2Declaration);
}
public Date getCleanJerk2LiftTime() {
return cleanJerk2LiftTime;
}
public String getCleanJerk3ActualLift() {
return emptyIfNull(cleanJerk3ActualLift);
}
public Integer getCleanJerk3AsInteger() {
return asInteger(cleanJerk3ActualLift);
}
public String getCleanJerk3AutomaticProgression() {
final int prevVal = zeroIfInvalid(cleanJerk2ActualLift);
return doAutomaticProgression(prevVal);
}
public String getCleanJerk3Change1() {
return emptyIfNull(cleanJerk3Change1);
}
public String getCleanJerk3Change2() {
return emptyIfNull(cleanJerk3Change2);
}
public String getCleanJerk3Declaration() {
return emptyIfNull(cleanJerk3Declaration);
}
public Date getCleanJerk3LiftTime() {
return cleanJerk3LiftTime;
}
/**
* @return the cleanJerkAttemptsDone
*/
public Integer getCleanJerkAttemptsDone() {
// if lifter signals he wont take his remaining tries, a zero is entered
// further lifts are not counted.
int attempts = 0;
if (!isEmpty(cleanJerk1ActualLift)) {
attempts++;
} else {
return attempts;
}
if (!isEmpty(cleanJerk2ActualLift)) {
attempts++;
} else {
return attempts;
}
if (!isEmpty(cleanJerk3ActualLift)) {
attempts++;
} else {
return attempts;
}
return attempts;
}
public Float getCleanJerkPoints() {
if (cleanJerkPoints == null) return 0.0F;
return cleanJerkPoints;
}
public Integer getCleanJerkRank() {
return cleanJerkRank;
}
/**
* @return total for clean and jerk
*/
public int getCleanJerkTotal() {
final int cleanJerkTotal = max(0, zeroIfInvalid(cleanJerk1ActualLift), zeroIfInvalid(cleanJerk2ActualLift),
zeroIfInvalid(cleanJerk3ActualLift));
return cleanJerkTotal;
}
/**
* @return the club
*/
public String getClub() {
return club;
}
public Float getCombinedPoints() {
return getSnatchPoints() + getCleanJerkPoints() + getTotalPoints();
}
public boolean getCurrentLifter() {
return currentLifter;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
public boolean getForcedAsCurrent() {
return forcedAsCurrent;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @return the group
*/
public CompetitionSession getCompetitionSession() {
return competitionSession;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* Compute the time of last lift for lifter. Times are only compared within
* the same lift type (if a lifter is at the first attempt of clean and
* jerk, then the last lift occurred forever ago.)
*
* @param lifter1
* @return null if lifter has not lifted
*/
public Date getLastLiftTime() {
Date max = null; // long ago
if (getAttemptsDone() <= 3) {
final Date sn1 = snatch1LiftTime;
if (sn1 != null) {
max = sn1;
} else {
return max;
}
final Date sn2 = snatch2LiftTime;
if (sn2 != null) {
max = (max.after(sn2) ? max : sn2);
} else {
return max;
}
final Date sn3 = snatch3LiftTime;
if (sn3 != null) {
max = (max.after(sn3) ? max : sn3);
} else {
return max;
}
} else {
final Date cj1 = cleanJerk1LiftTime;
if (cj1 != null) {
max = cj1;
} else {
return max;
}
final Date cj2 = cleanJerk2LiftTime;
if (cj2 != null) {
max = (max.after(cj2) ? max : cj2);
} else {
return max;
}
final Date cj3 = cleanJerk3LiftTime;
if (cj3 != null) {
max = (max.after(cj3) ? max : cj3);
} else {
return max;
}
}
return max;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
public Date getLastSuccessfulLiftTime() {
if (zeroIfInvalid(cleanJerk3ActualLift) > 0) return getCleanJerk3LiftTime();
if (zeroIfInvalid(cleanJerk2ActualLift) > 0) return getCleanJerk2LiftTime();
if (zeroIfInvalid(cleanJerk1ActualLift) > 0) return getCleanJerk1LiftTime();
if (zeroIfInvalid(snatch3ActualLift) > 0) return getCleanJerk3LiftTime();
if (zeroIfInvalid(snatch2ActualLift) > 0) return getCleanJerk2LiftTime();
if (zeroIfInvalid(snatch1ActualLift) > 0) return getCleanJerk1LiftTime();
return new Date(0L); // long ago
}
public Integer getLiftOrderRank() {
return liftOrderRank;
}
/**
* @return the lotNumber
*/
public Integer getLotNumber() {
return (lotNumber == null ? 0 : lotNumber);
}
public String getMembership() {
return membership;
}
/**
* @return the nextAttemptRequestedWeight
*/
public Integer getNextAttemptRequestedWeight() {
int attempt = getAttemptsDone() + 1;
switch (attempt) {
case 1:
return (Integer) last(zeroIfInvalid(getSnatch1AutomaticProgression()), zeroIfInvalid(snatch1Declaration),
zeroIfInvalid(snatch1Change1), zeroIfInvalid(snatch1Change2));
case 2:
return (Integer) last(zeroIfInvalid(getSnatch2AutomaticProgression()), zeroIfInvalid(snatch2Declaration),
zeroIfInvalid(snatch2Change1), zeroIfInvalid(snatch2Change2));
case 3:
return (Integer) last(zeroIfInvalid(getSnatch3AutomaticProgression()), zeroIfInvalid(snatch3Declaration),
zeroIfInvalid(snatch3Change1), zeroIfInvalid(snatch3Change2));
case 4:
return (Integer) last(zeroIfInvalid(getCleanJerk1AutomaticProgression()),
zeroIfInvalid(cleanJerk1Declaration), zeroIfInvalid(cleanJerk1Change1),
zeroIfInvalid(cleanJerk1Change2));
case 5:
return (Integer) last(zeroIfInvalid(getCleanJerk2AutomaticProgression()),
zeroIfInvalid(cleanJerk2Declaration), zeroIfInvalid(cleanJerk2Change1),
zeroIfInvalid(cleanJerk2Change2));
case 6:
return (Integer) last(zeroIfInvalid(getCleanJerk3AutomaticProgression()),
zeroIfInvalid(cleanJerk3Declaration), zeroIfInvalid(cleanJerk3Change1),
zeroIfInvalid(cleanJerk3Change2));
}
return 0;
}
public Integer getQualifyingTotal() {
if (qualifyingTotal == null) return 0;
return qualifyingTotal;
}
public Integer getRank() {
return totalRank;
}
public Category getRegistrationCategory() {
return registrationCategory;
}
public Integer getResultOrderRank() {
return resultOrderRank;
}
/**
* Compute the Sinclair total for the lifter, that is, the total multiplied
* by a value that depends on the lifter's body weight. This value
* extrapolates what the lifter would have lifted if he/she had the bodymass
* of a maximum-weight lifter.
*
* @return the sinclair-adjusted value for the lifter
*/
public Double getSinclair() {
final Double bodyWeight1 = getBodyWeight();
if (bodyWeight1 == null) return 0.0;
return getSinclair(bodyWeight1);
}
public Double getSinclair(Double bodyWeight1) {
Integer total1 = getTotal();
if (total1 == null || total1 < 0.1) return 0.0;
if (gender == null) return 0.0;
if (gender.equalsIgnoreCase("M")) { //$NON-NLS-1$
return total1 * sinclairFactor(bodyWeight1, Coefficients.menCoefficient(), Coefficients.menMaxWeight());
} else {
return total1 * sinclairFactor(bodyWeight1, Coefficients.womenCoefficient(), Coefficients.womenMaxWeight());
}
}
public Integer getSinclairRank() {
return sinclairRank;
}
static int year = Calendar.getInstance().get(Calendar.YEAR);
public Double getSMM() {
try {
final Integer birthDate1 = getBirthDate();
if (birthDate1 == null) return 0.0;
return getSinclair() * Coefficients.getSMMCoefficient(year - birthDate1);
} catch (IOException e) {
LoggerUtils.logException(logger, e);
return getSinclair();
}
}
public String getSnatch1ActualLift() {
return emptyIfNull(snatch1ActualLift);
}
public Integer getSnatch1AsInteger() {
return asInteger(snatch1ActualLift);
}
public String getSnatch1AutomaticProgression() {
return "-"; //no such thing. //$NON-NLS-1$
}
public String getSnatch1Change1() {
return emptyIfNull(snatch1Change1);
}
public String getSnatch1Change2() {
return emptyIfNull(snatch1Change2);
}
public String getSnatch1Declaration() {
return emptyIfNull(snatch1Declaration);
}
public Date getSnatch1LiftTime() {
return snatch1LiftTime;
}
public String getSnatch2ActualLift() {
return emptyIfNull(snatch2ActualLift);
}
public Integer getSnatch2AsInteger() {
return asInteger(snatch2ActualLift);
}
public String getSnatch2AutomaticProgression() {
final int prevVal = zeroIfInvalid(snatch1ActualLift);
return doAutomaticProgression(prevVal);
}
public String getSnatch2Change1() {
return emptyIfNull(snatch2Change1);
}
public String getSnatch2Change2() {
return emptyIfNull(snatch2Change2);
}
public String getSnatch2Declaration() {
return emptyIfNull(snatch2Declaration);
}
public Date getSnatch2LiftTime() {
return snatch2LiftTime;
}
public String getSnatch3ActualLift() {
return emptyIfNull(snatch3ActualLift);
}
public Integer getSnatch3AsInteger() {
return asInteger(snatch3ActualLift);
}
public String getSnatch3AutomaticProgression() {
final int prevVal = zeroIfInvalid(snatch2ActualLift);
return doAutomaticProgression(prevVal);
}
public String getSnatch3Change1() {
return emptyIfNull(snatch3Change1);
}
public String getSnatch3Change2() {
return emptyIfNull(snatch3Change2);
}
public String getSnatch3Declaration() {
return emptyIfNull(snatch3Declaration);
}
public Date getSnatch3LiftTime() {
return snatch3LiftTime;
}
/**
* @return how many snatch attempts have been performed
*/
public Integer getSnatchAttemptsDone() {
// lifter signals he wont take his remaining tries, a zero is entered
// further lifts are not counted.
int attempts = 0;
if (!isEmpty(snatch1ActualLift)) {
attempts++;
} else {
return attempts;
}
if (!isEmpty(snatch2ActualLift)) {
attempts++;
} else {
return attempts;
}
if (!isEmpty(snatch3ActualLift)) {
attempts++;
} else {
return attempts;
}
return attempts;
}
public Float getSnatchPoints() {
if (snatchPoints == null) return 0.0F;
return snatchPoints;
}
public Integer getSnatchRank() {
return snatchRank;
}
/**
* @return total for snatch.
*/
public int getSnatchTotal() {
final int snatchTotal = max(0, zeroIfInvalid(snatch1ActualLift), zeroIfInvalid(snatch2ActualLift),
zeroIfInvalid(snatch3ActualLift));
return snatchTotal;
}
public Integer getTeamCleanJerkRank() {
return teamCleanJerkRank;
}
public Boolean getTeamMember() {
if (teamMember == null) return true;
return teamMember;
}
public Integer getTeamSnatchRank() {
return teamSnatchRank;
}
public Integer getTeamTotalRank() {
return teamTotalRank;
}
/**
* Total is zero if all three snatches or all three clean&jerks are failed.
* Failed lifts are indicated as negative amounts. Total is the sum of all
* good lifts otherwise. Null entries indicate that no data has been
* captured, and are counted as zero.
*
* @return the total
*/
public Integer getTotal() {
final int snatchTotal = getSnatchTotal();
if (snatchTotal == 0) return 0;
final int cleanJerkTotal = getCleanJerkTotal();
if (cleanJerkTotal == 0) return 0;
return snatchTotal + cleanJerkTotal;
}
public Float getTotalPoints() {
if (totalPoints == null) return 0.0F;
return totalPoints;
}
public Integer getTotalRank() {
return totalRank;
}
public boolean isCurrentLifter() {
return currentLifter;
}
public boolean isForcedAsCurrent() {
return forcedAsCurrent;
}
public boolean isInvited() {
final Locale locale = CompetitionApplication.getCurrentLocale();
int threshold = Competition.invitedIfBornBefore();
return (getBirthDate() < threshold)
|| membership.equalsIgnoreCase(Messages.getString("Lifter.InvitedAbbreviated", locale)) //$NON-NLS-1$
// || !getTeamMember()
;
}
public void removeAllListeners() {
if (eventRouter != null) {
eventRouter.removeAllListeners();
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.event.MethodEventSource#removeListener(java.lang.Class,
* java.lang.Object)
*/
@Override
@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)
*/
@Override
@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)
*/
@Override
@SuppressWarnings({ "rawtypes" })
public void removeListener(Class eventType, Object target, String methodName) {
if (eventRouter != null) {
eventRouter.removeListener(eventType, target, methodName);
}
}
/**
* Remove a specific Lifter.Listener object
*
* @param listener
*/
@Override
public void removeListener(EventListener listener) {
if (eventRouter != null) {
eventRouter.removeListener(UpdateEvent.class, listener, LIFTER_EVENT_METHOD);
}
}
public void resetForcedAsCurrent() {
this.forcedAsCurrent = false;
}
public void setAgeGroup(Integer ageGroup) {
this.ageGroup = ageGroup;
}
public void setAsCurrentLifter(Boolean currentLifter) {
// if (currentLifter)
// System.err.println("Lifter.setAsCurrentLifter(): current lifter is now "+getLastName()+" "+getFirstName());
this.currentLifter = currentLifter;
if (currentLifter) {
logger.info("{} is current lifter", this);
}
}
public void setAttemptsDone(Integer i) {
}
public void setBestCleanJerk(Integer i) {
}
public void setBestSnatch(Integer i) {
}
/**
* @param birthDate
* the birthDate to set
*/
public void setBirthDate(Integer birthDate) {
this.birthDate = birthDate;
}
/**
* @param bodyWeight
* the bodyWeight to set
*/
public void setBodyWeight(Double bodyWeight) {
this.bodyWeight = bodyWeight;
fireEvent(new UpdateEvent(this, "category", "bodyWeight")); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @param category
* the category to set
*/
// public void setCategory(Category category) {
// this.category = category;
// }
public void setCleanJerk1ActualLift(String cleanJerk1ActualLift) {
validateActualLift(1, getCleanJerk1AutomaticProgression(), cleanJerk1Declaration, cleanJerk1Change1,
cleanJerk1Change2, cleanJerk1ActualLift);
this.cleanJerk1ActualLift = cleanJerk1ActualLift;
if (zeroIfInvalid(cleanJerk1ActualLift) == 0) this.cleanJerk1LiftTime = (null);
else this.cleanJerk1LiftTime = (Calendar.getInstance().getTime());
logger.info("{} cleanJerk1ActualLift={}", this, cleanJerk1ActualLift);
fireEvent(new UpdateEvent(this, "cleanJerk1ActualLift", "cleanJerk1LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setCleanJerk1AutomaticProgression(String s) {
}
public void setCleanJerk1Change1(String cleanJerk1Change1) {
if ("0".equals(cleanJerk1Change1)) {
this.cleanJerk1Change1 = cleanJerk1Change1;
logger.info("{} cleanJerk1Change1={}", this, cleanJerk1Change1);
setCleanJerk1ActualLift("0");
return;
}
validateChange1(1, getCleanJerk1AutomaticProgression(), cleanJerk1Declaration, cleanJerk1Change1,
cleanJerk1Change2, cleanJerk1ActualLift);
this.cleanJerk1Change1 = cleanJerk1Change1;
logger.info("{} cleanJerk1Change1={}", this, cleanJerk1Change1);
fireEvent(new UpdateEvent(this, "cleanJerk1Change1")); //$NON-NLS-1$
}
public void setCleanJerk1Change2(String cleanJerk1Change2) {
if ("0".equals(cleanJerk1Change2)) {
this.cleanJerk1Change2 = cleanJerk1Change2;
logger.info("{} cleanJerk1Change2={}", this, cleanJerk1Change2);
setCleanJerk1ActualLift("0");
return;
}
validateChange2(1, getCleanJerk1AutomaticProgression(), cleanJerk1Declaration, cleanJerk1Change1,
cleanJerk1Change2, cleanJerk1ActualLift);
this.cleanJerk1Change2 = cleanJerk1Change2;
logger.info("{} cleanJerk1Change2={}", this, cleanJerk1Change2);
fireEvent(new UpdateEvent(this, "cleanJerk1Change2")); //$NON-NLS-1$
}
public void setCleanJerk1Declaration(String cleanJerk1Declaration) {
if ("0".equals(cleanJerk1Declaration)) {
this.cleanJerk1Declaration = cleanJerk1Declaration;
logger.info("{} cleanJerk1Declaration={}", this, cleanJerk1Declaration);
setCleanJerk1ActualLift("0");
return;
}
validateDeclaration(1, getCleanJerk1AutomaticProgression(), cleanJerk1Declaration, cleanJerk1Change1,
cleanJerk1Change2, cleanJerk1ActualLift);
this.cleanJerk1Declaration = cleanJerk1Declaration;
logger.info("{} cleanJerk1Declaration={}", this, cleanJerk1Declaration);
fireEvent(new UpdateEvent(this, "cleanJerk1Declaration")); //$NON-NLS-1$
}
public void setCleanJerk1LiftTime(java.util.Date date) {
}
public void setCleanJerk2ActualLift(String cleanJerk2ActualLift) {
validateActualLift(2, getCleanJerk2AutomaticProgression(), cleanJerk2Declaration, cleanJerk2Change1,
cleanJerk2Change2, cleanJerk2ActualLift);
this.cleanJerk2ActualLift = cleanJerk2ActualLift;
if (zeroIfInvalid(cleanJerk2ActualLift) == 0) this.cleanJerk2LiftTime = (null);
else this.cleanJerk2LiftTime = (Calendar.getInstance().getTime());
logger.info("{} cleanJerk2ActualLift={}", this, cleanJerk2ActualLift);
fireEvent(new UpdateEvent(this, "cleanJerk2ActualLift", "cleanJerk2LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setCleanJerk2AutomaticProgression(String s) {
}
public void setCleanJerk2Change1(String cleanJerk2Change1) throws RuleViolationException {
if ("0".equals(cleanJerk2Change1)) {
this.cleanJerk2Change1 = cleanJerk2Change1;
logger.info("{} cleanJerk2Change1={}", this, cleanJerk2Change1);
setCleanJerk2ActualLift("0");
return;
}
validateChange1(2, getCleanJerk2AutomaticProgression(), cleanJerk2Declaration, cleanJerk2Change1,
cleanJerk2Change2, cleanJerk2ActualLift);
this.cleanJerk2Change1 = cleanJerk2Change1;
logger.info("{} cleanJerk2Change1={}", this, cleanJerk2Change1);
fireEvent(new UpdateEvent(this, "cleanJerk2Change1")); //$NON-NLS-1$
}
public void setCleanJerk2Change2(String cleanJerk2Change2) {
if ("0".equals(cleanJerk2Change2)) {
this.cleanJerk2Change2 = cleanJerk2Change2;
logger.info("{} cleanJerk2Change2={}", this, cleanJerk2Change2);
setCleanJerk2ActualLift("0");
return;
}
validateChange2(2, getCleanJerk2AutomaticProgression(), cleanJerk2Declaration, cleanJerk2Change1,
cleanJerk2Change2, cleanJerk2ActualLift);
this.cleanJerk2Change2 = cleanJerk2Change2;
logger.info("{} cleanJerk2Change2={}", this, cleanJerk2Change2);
fireEvent(new UpdateEvent(this, "cleanJerk2Change2")); //$NON-NLS-1$
}
public void setCleanJerk2Declaration(String cleanJerk2Declaration) {
if ("0".equals(cleanJerk2Declaration)) {
this.cleanJerk2Declaration = cleanJerk2Declaration;
logger.info("{} cleanJerk2Declaration={}", this, cleanJerk2Declaration);
setCleanJerk2ActualLift("0");
return;
}
validateDeclaration(2, getCleanJerk2AutomaticProgression(), cleanJerk2Declaration, cleanJerk2Change1,
cleanJerk2Change2, cleanJerk2ActualLift);
this.cleanJerk2Declaration = cleanJerk2Declaration;
logger.info("{} cleanJerk2Declaration={}", this, cleanJerk2Declaration);
fireEvent(new UpdateEvent(this, "cleanJerk2Declaration")); //$NON-NLS-1$
}
public void setCleanJerk2LiftTime(Date cleanJerk2LiftTime) {
}
public void setCleanJerk3ActualLift(String cleanJerk3ActualLift) {
validateActualLift(3, getCleanJerk3AutomaticProgression(), cleanJerk3Declaration, cleanJerk3Change1,
cleanJerk3Change2, cleanJerk3ActualLift);
this.cleanJerk3ActualLift = cleanJerk3ActualLift;
if (zeroIfInvalid(cleanJerk3ActualLift) == 0) this.cleanJerk3LiftTime = (null);
else this.cleanJerk3LiftTime = (Calendar.getInstance().getTime());
logger.info("{} cleanJerk3ActualLift={}", this, cleanJerk3ActualLift);
fireEvent(new UpdateEvent(this, "cleanJerk3ActualLift", "cleanJerk3LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setCleanJerk3AutomaticProgression(String s) {
}
public void setCleanJerk3Change1(String cleanJerk3Change1) throws RuleViolationException {
if ("0".equals(cleanJerk3Change1)) {
this.cleanJerk3Change1 = cleanJerk3Change1;
logger.info("{} cleanJerk3Change1={}", this, cleanJerk3Change1);
setCleanJerk3ActualLift("0");
return;
}
validateChange1(3, getCleanJerk3AutomaticProgression(), cleanJerk3Declaration, cleanJerk3Change1,
cleanJerk3Change2, cleanJerk3ActualLift);
this.cleanJerk3Change1 = cleanJerk3Change1;
logger.info("{} cleanJerk3Change1={}", this, cleanJerk3Change1);
fireEvent(new UpdateEvent(this, "cleanJerk3Change1")); //$NON-NLS-1$
}
public void setCleanJerk3Change2(String cleanJerk3Change2) {
if ("0".equals(cleanJerk3Change2)) {
this.cleanJerk3Change2 = cleanJerk3Change2;
logger.info("{} cleanJerk3Change2={}", this, cleanJerk3Change2);
setCleanJerk3ActualLift("0");
return;
}
validateChange2(3, getCleanJerk3AutomaticProgression(), cleanJerk3Declaration, cleanJerk3Change1,
cleanJerk3Change2, cleanJerk3ActualLift);
this.cleanJerk3Change2 = cleanJerk3Change2;
logger.info("{} cleanJerk3Change2={}", this, cleanJerk3Change2);
fireEvent(new UpdateEvent(this, "cleanJerk3Change2")); //$NON-NLS-1$
}
public void setCleanJerk3Declaration(String cleanJerk3Declaration) {
if ("0".equals(cleanJerk3Declaration)) {
this.cleanJerk3Declaration = cleanJerk3Declaration;
logger.info("{} cleanJerk3Declaration={}", this, cleanJerk3Declaration);
setCleanJerk3ActualLift("0");
return;
}
validateDeclaration(3, getCleanJerk3AutomaticProgression(), cleanJerk3Declaration, cleanJerk3Change1,
cleanJerk3Change2, cleanJerk3ActualLift);
this.cleanJerk3Declaration = cleanJerk3Declaration;
logger.info("{} cleanJerk3Declaration={}", this, cleanJerk3Declaration);
fireEvent(new UpdateEvent(this, "cleanJerk3Declaration")); //$NON-NLS-1$
}
public void setCleanJerk3LiftTime(Date cleanJerk3LiftTime) {
}
public void setCleanJerkAttemptsDone(Integer i) {
}
public void setCleanJerkPoints(Float cleanJerkPoints) {
this.cleanJerkPoints = cleanJerkPoints;
}
public void setCleanJerkRank(Integer cleanJerkRank) {
this.cleanJerkRank = cleanJerkRank;
}
/**
* @param club
* the club to set
*/
public void setClub(String club) {
this.club = club;
}
public void setCurrentLifter(boolean currentLifter) {
this.currentLifter = currentLifter;
}
/**
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @param forcedAsCurrent
*/
public void setForcedAsCurrent(boolean forcedAsCurrent) {
logger.debug("setForcedAsCurrent({})", forcedAsCurrent); //$NON-NLS-1$
this.forcedAsCurrent = forcedAsCurrent;
fireEvent(new UpdateEvent(this, "_forceAsCurrent")); // no visible property update //$NON-NLS-1$
}
/**
* @param string
* the gender to set
*/
public void setGender(String string) {
if (string != null) {
this.gender = string.toUpperCase();
} else {
this.gender = string;
}
fireEvent(new UpdateEvent(this, "category", "gender")); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @param competitionSession
* the group to set
*/
public void setCompetitionSession(CompetitionSession competitionSession) {
this.competitionSession = competitionSession;
}
public void setLastLiftTime(Date d) {
}
/**
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setLiftOrderRank(Integer liftOrder) {
this.liftOrderRank = liftOrder;
}
/**
* @param lotNumber
* the lotNumber to set
*/
public void setLotNumber(Integer lotNumber) {
this.lotNumber = lotNumber;
}
public void setMembership(String membership) {
this.membership = membership;
}
public void setNextAttemptRequestedWeight(Integer i) {
}
public void setQualifyingTotal(Integer qualifyingTotal) {
this.qualifyingTotal = qualifyingTotal;
}
public void setRank(Integer i) {
this.totalRank = i;
}
public void setRegistrationCategory(Category registrationCategory) {
this.registrationCategory = registrationCategory;
// category may need to be flagged as different from registration if
// this
// value is changed.
fireEvent(new UpdateEvent(this, "registrationCategory", "category")); //$NON-NLS-1$//$NON-NLS-2$
}
public void setResultOrderRank(Integer resultOrderRank, Ranking rankingType) {
this.resultOrderRank = resultOrderRank;
}
public void setSinclairRank(Integer sinclairRank) {
this.sinclairRank = sinclairRank;
}
public void setSnatch1ActualLift(String snatch1ActualLift) {
validateActualLift(1, getSnatch1AutomaticProgression(), snatch1Declaration, snatch1Change1, snatch1Change2,
snatch1ActualLift);
this.snatch1ActualLift = snatch1ActualLift;
if (zeroIfInvalid(snatch1ActualLift) == 0) this.snatch1LiftTime = null;
else this.snatch1LiftTime = (Calendar.getInstance().getTime());
logger.info("{} snatch1ActualLift={}", this, snatch1ActualLift);
fireEvent(new UpdateEvent(this, "snatch1ActualLift", "snatch1LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setSnatch1AutomaticProgression(String s) {
}
public void setSnatch1Change1(String snatch1Change1) throws RuleViolationException {
if ("0".equals(snatch1Change1)) {
this.snatch1Change1 = snatch1Change1;
logger.info("{} snatch1Change1={}", this, snatch1Change1);
setSnatch1ActualLift("0");
return;
}
validateChange1(1, getSnatch1AutomaticProgression(), snatch1Declaration, snatch1Change1, snatch1Change2,
snatch1ActualLift);
this.snatch1Change1 = snatch1Change1;
logger.info("{} snatch1Change1={}", this, snatch1Change1);
fireEvent(new UpdateEvent(this, "snatch1Change1")); //$NON-NLS-1$
}
public void setSnatch1Change2(String snatch1Change2) {
if ("0".equals(snatch1Change2)) {
this.snatch1Change2 = snatch1Change2;
logger.info("{} snatch1Change2={}", this, snatch1Change2);
setSnatch1ActualLift("0");
return;
}
validateChange2(1, getSnatch1AutomaticProgression(), snatch1Declaration, snatch1Change1, snatch1Change2,
snatch1ActualLift);
this.snatch1Change2 = snatch1Change2;
logger.info("{} snatch1Change2={}", this, snatch1Change2);
fireEvent(new UpdateEvent(this, "snatch1Change2")); //$NON-NLS-1$
}
public void setSnatch1Declaration(String snatch1Declaration) {
if ("0".equals(snatch1Declaration)) {
this.snatch1Declaration = snatch1Declaration;
logger.info("{} snatch1Declaration={}", this, snatch1Declaration);
setSnatch1ActualLift("0");
return;
}
validateDeclaration(1, getSnatch1AutomaticProgression(), snatch1Declaration, snatch1Change1, snatch1Change2,
snatch1ActualLift);
this.snatch1Declaration = snatch1Declaration;
logger.info("{} snatch1Declaration={}", this, snatch1Declaration);
fireEvent(new UpdateEvent(this, "snatch1Declaration")); //$NON-NLS-1$
}
public void setSnatch1LiftTime(Date snatch1LiftTime) {
}
public void setSnatch2ActualLift(String snatch2ActualLift) {
validateActualLift(2, getSnatch2AutomaticProgression(), snatch2Declaration, snatch2Change1, snatch2Change2,
snatch2ActualLift);
this.snatch2ActualLift = snatch2ActualLift;
if (zeroIfInvalid(snatch2ActualLift) == 0) this.snatch2LiftTime = (null);
else this.snatch2LiftTime = (Calendar.getInstance().getTime());
logger.info("{} snatch2ActualLift={}", this, snatch2ActualLift);
fireEvent(new UpdateEvent(this, "snatch2ActualLift", "snatch2LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setSnatch2AutomaticProgression(String s) {
}
public void setSnatch2Change1(String snatch2Change1) throws RuleViolationException {
if ("0".equals(snatch2Change1)) {
this.snatch2Change1 = snatch2Change1;
logger.info("{} snatch2Change1={}", this, snatch2Change1);
setSnatch2ActualLift("0");
return;
}
validateChange1(2, getSnatch2AutomaticProgression(), snatch2Declaration, snatch2Change1, snatch2Change2,
snatch2ActualLift);
this.snatch2Change1 = snatch2Change1;
logger.info("{} snatch2Change1={}", this, snatch2Change1);
fireEvent(new UpdateEvent(this, "snatch2Change1")); //$NON-NLS-1$
}
/* *********************************************************************************
* UpdateEvent framework.
*/
public void setSnatch2Change2(String snatch2Change2) {
if ("0".equals(snatch2Change2)) {
this.snatch2Change2 = snatch2Change2;
logger.info("{} snatch2Change2={}", this, snatch2Change2);
setSnatch2ActualLift("0");
return;
}
validateChange2(2, getSnatch2AutomaticProgression(), snatch2Declaration, snatch2Change1, snatch2Change2,
snatch2ActualLift);
this.snatch2Change2 = snatch2Change2;
logger.info("{} snatch2Change2={}", this, snatch2Change2);
fireEvent(new UpdateEvent(this, "snatch2Change2")); //$NON-NLS-1$
}
public void setSnatch2Declaration(String snatch2Declaration) {
if ("0".equals(snatch2Declaration)) {
this.snatch2Declaration = snatch2Declaration;
logger.info("{} snatch2Declaration={}", this, snatch2Declaration);
setSnatch2ActualLift("0");
return;
}
validateDeclaration(2, getSnatch2AutomaticProgression(), snatch2Declaration, snatch2Change1, snatch2Change2,
snatch2ActualLift);
this.snatch2Declaration = snatch2Declaration;
logger.info("{} snatch2Declaration={}", this, snatch2Declaration);
fireEvent(new UpdateEvent(this, "snatch2Declaration")); //$NON-NLS-1$
}
public void setSnatch2LiftTime(Date snatch2LiftTime) {
}
public void setSnatch3ActualLift(String snatch3ActualLift) {
validateActualLift(3, getSnatch3AutomaticProgression(), snatch3Declaration, snatch3Change1, snatch3Change2,
snatch3ActualLift);
this.snatch3ActualLift = snatch3ActualLift;
if (zeroIfInvalid(snatch3ActualLift) == 0) this.snatch3LiftTime = (null);
else this.snatch3LiftTime = (Calendar.getInstance().getTime());
logger.info("{} snatch3ActualLift={}", this, snatch3ActualLift);
fireEvent(new UpdateEvent(this, "snatch2ActualLift", "snatch2LiftTime", "total")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void setSnatch3AutomaticProgression(String s) {
}
public void setSnatch3Change1(String snatch3Change1) throws RuleViolationException {
if ("0".equals(snatch3Change1)) {
this.snatch3Change1 = snatch3Change1;
logger.info("{} snatch3Change1={}", this, snatch3Change1);
setSnatch3ActualLift("0");
return;
}
validateChange1(3, getSnatch3AutomaticProgression(), snatch3Declaration, snatch3Change1, snatch3Change2,
snatch3ActualLift);
this.snatch3Change1 = snatch3Change1;
logger.info("{} snatch3Change1={}", this, snatch3Change1);
fireEvent(new UpdateEvent(this, "snatch3Change1")); //$NON-NLS-1$
}
/*
* 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 that an event has occurred, and
* how the listener can register/unregister itself.
*/
public void setSnatch3Change2(String snatch3Change2) {
if ("0".equals(snatch3Change2)) {
this.snatch3Change2 = snatch3Change2;
logger.info("{} snatch3Change2={}", this, snatch3Change2);
setSnatch3ActualLift("0");
return;
}
validateChange2(3, getSnatch3AutomaticProgression(), snatch3Declaration, snatch3Change1, snatch3Change2,
snatch3ActualLift);
this.snatch3Change2 = snatch3Change2;
logger.info("{} snatch3Change2={}", this, snatch3Change2);
fireEvent(new UpdateEvent(this, "snatch3Change2")); //$NON-NLS-1$
}
public void setSnatch3Declaration(String snatch3Declaration) {
if ("0".equals(snatch3Declaration)) {
this.snatch3Declaration = snatch3Declaration;
logger.info("{} snatch3Declaration={}", this, snatch3Declaration);
setSnatch3ActualLift("0");
return;
}
validateDeclaration(3, getSnatch3AutomaticProgression(), snatch3Declaration, snatch3Change1, snatch3Change2,
snatch3ActualLift);
this.snatch3Declaration = snatch3Declaration;
logger.info("{} snatch3Declaration={}", this, snatch3Declaration);
fireEvent(new UpdateEvent(this, "snatch3Declaration")); //$NON-NLS-1$
}
public void setSnatch3LiftTime(Date snatch3LiftTime) {
}
public void setSnatchAttemptsDone(Integer i) {
}
public void setSnatchPoints(float snatchPoints) {
this.snatchPoints = snatchPoints;
}
public void setSnatchRank(Integer snatchRank) {
this.snatchRank = snatchRank;
}
public void setTeamCleanJerkRank(Integer teamCJRank) {
this.teamCleanJerkRank = teamCJRank;
}
public void setTeamCombinedRank(Integer teamCombinedRank) {
this.teamCombinedRank = teamCombinedRank;
}
public void setTeamMember(Boolean teamMember) {
this.teamMember = teamMember;
}
public void setTeamSnatchRank(Integer teamSnatchRank) {
this.teamSnatchRank = teamSnatchRank;
}
public void setTeamTotalRank(Integer teamTotalRank) {
this.teamTotalRank = teamTotalRank;
}
public void setTeamSinclairRank(Integer teamSinclairRank) {
this.teamSinclairRank = teamSinclairRank;
}
public void setTotal(Integer i) {
}
public void setTotalPoints(float totalPoints) {
this.totalPoints = totalPoints;
}
public void setTotalRank(Integer totalRank) {
this.totalRank = totalRank;
}
public Double getCustomScore() {
if (customScore == null || customScore < 0.01) return new Double(getTotal());
return customScore;
}
public void setCustomScore(Double customScore) {
this.customScore = customScore;
}
public void setCustomRank(Integer customRank) {
this.customRank = customRank;
}
public Integer getCustomRank() {
return this.customRank;
}
public void setCustomPoints(float customPoints) {
this.customPoints = customPoints;
}
public void successfulLift() {
logger.debug("good lift for {}, listeners={}", this); //, getEventRouter().dumpListeners(this)); //$NON-NLS-1$
final String weight = Integer.toString(getNextAttemptRequestedWeight());
doLift(weight);
}
@Override
public String toString() {
return getLastName() + "_" + getFirstName() + "_" + System.identityHashCode(this); //$NON-NLS-1$ //$NON-NLS-2$
}
public void withdraw() {
if (snatch1ActualLift != null && snatch1ActualLift.trim().isEmpty()) {
setSnatch1ActualLift("0");
}
if (snatch2ActualLift != null && snatch2ActualLift.trim().isEmpty()) {
setSnatch2ActualLift("0");
}
if (snatch3ActualLift != null && snatch3ActualLift.trim().isEmpty()) {
setSnatch3ActualLift("0");
}
if (cleanJerk1ActualLift != null && cleanJerk1ActualLift.trim().isEmpty()) {
setCleanJerk1ActualLift("0");
}
if (cleanJerk2ActualLift != null && cleanJerk2ActualLift.trim().isEmpty()) {
setCleanJerk2ActualLift("0");
}
if (cleanJerk3ActualLift != null && cleanJerk3ActualLift.trim().isEmpty()) {
setCleanJerk3ActualLift("0");
}
}
/**
* @param prevVal
* @return
*/
private String doAutomaticProgression(final int prevVal) {
if (prevVal > 0) {
return Integer.toString(prevVal + 1);
} else {
return Integer.toString(Math.abs(prevVal));
}
}
/**
* @param lifter
* @param lifters
* @param weight
*/
private void doLift(final String weight) {
switch (this.getAttemptsDone() + 1) {
case 1:
this.setSnatch1ActualLift(weight);
break;
case 2:
this.setSnatch2ActualLift(weight);
break;
case 3:
this.setSnatch3ActualLift(weight);
break;
case 4:
this.setCleanJerk1ActualLift(weight);
break;
case 5:
this.setCleanJerk2ActualLift(weight);
break;
case 6:
this.setCleanJerk3ActualLift(weight);
break;
}
}
private String emptyIfNull(String value) {
return (value == null ? "" : value); //$NON-NLS-1$
}
/**
* @return the object's event router.
*/
private EventRouter getEventRouter() {
if (eventRouter == null) {
// eventRouter = new EventRouter(this);
eventRouter = new EventRouter();
logger.trace("new event router for lifter {}", this); //$NON-NLS-1$
}
return eventRouter;
}
private Integer last(Integer... items) {
int lastIndex = items.length - 1;
while (lastIndex >= 0) {
if (items[lastIndex] > 0) {
return items[lastIndex];
}
lastIndex--;
}
return 0;
}
private Integer max(Integer... items) {
List<Integer> itemList = Arrays.asList(items);
final Integer max = Collections.max(itemList);
return max;
}
@SuppressWarnings("unused")
private Integer max(String... items) {
List<String> itemList = Arrays.asList(items);
List<Integer> intItemList = new ArrayList<Integer>(itemList.size());
for (String curString : itemList) {
intItemList.add(zeroIfInvalid(curString));
}
final Integer max = Collections.max(intItemList);
return max;
}
/**
* Compute the sinclair formula given its parameters.
*
* @param coefficient
* @param maxWeight
*/
// ($R7*
// SI($E7="m",
// SI($G7<173.961,
// 10^(0.784780654*((LOG10($G7/173.961))^2)),
// 1),
// SI($G7<125.441,
// 10^(1.056683941*((LOG10($G7/125.441))^2)),1)
// )
// )
private Double sinclairFactor(Double bodyWeight1, Double coefficient, Double maxWeight) {
if (bodyWeight1 == null) return 0.0;
if (bodyWeight1 >= maxWeight) {
return 1.0;
} else {
return Math.pow(10.0, coefficient * (Math.pow(Math.log10(bodyWeight1 / maxWeight), 2)));
}
}
/**
* @param curLift
* @param actualLift
*/
private void validateActualLift(int curLift, String automaticProgression, String declaration, String change1,
String change2, String actualLift) {
if (actualLift == null || actualLift.trim().length() == 0) return; // allow
// reset
// of
// field.
final int declaredChanges = last(zeroIfInvalid(declaration), zeroIfInvalid(change1), zeroIfInvalid(change2));
final int iAutomaticProgression = zeroIfInvalid(automaticProgression);
final int liftedWeight = zeroIfInvalid(actualLift);
logger.debug("declaredChanges={} automaticProgression={} liftedWeight={}", //$NON-NLS-1$
new Object[] { declaredChanges, automaticProgression, liftedWeight });
if (liftedWeight == 0) {
// lifter is not taking try; always ok no matter what was declared.
return;
}
if (declaredChanges == 0 && iAutomaticProgression > 0) {
// assume data entry is being done without reference to
// declarations, check if > progression
if (Math.abs(liftedWeight) >= iAutomaticProgression) {
return;
} else {
throw RuleViolation.liftValueBelowProgression(curLift, actualLift, iAutomaticProgression);
}
} else {
// declarations are being captured, lift must match declared
// changes.
final boolean declaredChangesOk = declaredChanges >= iAutomaticProgression;
final boolean liftedWeightOk = Math.abs(liftedWeight) == declaredChanges;
if (liftedWeightOk && declaredChangesOk) {
return;
} else {
if (declaredChanges == 0)
return;
if (!declaredChangesOk)
throw RuleViolation.declaredChangesNotOk(curLift, declaredChanges, iAutomaticProgression,
iAutomaticProgression + 1);
if (!liftedWeightOk)
throw RuleViolation
.liftValueNotWhatWasRequested(curLift, actualLift, declaredChanges, liftedWeight);
}
}
}
/**
* @param curLift
* @param actualLift
*/
private void validateChange1(int curLift, String automaticProgression, String declaration, String change1,
String change2, String actualLift) {
if (change1 == null || change1.trim().length() == 0) return; // allow
// reset of
// field.
int newVal = zeroIfInvalid(change1);
int prevVal = zeroIfInvalid(automaticProgression);
if (newVal < prevVal) throw RuleViolation.declaredChangesNotOk(curLift, newVal, prevVal);
}
/**
* @param curLift
* @param actualLift
*/
private void validateChange2(int curLift, String automaticProgression, String declaration, String change1,
String change2, String actualLift) {
if (change2 == null || change2.trim().length() == 0) return; // allow
// reset of
// field.
int newVal = zeroIfInvalid(change2);
int prevVal = zeroIfInvalid(automaticProgression);
if (newVal < prevVal) throw RuleViolation.declaredChangesNotOk(curLift, newVal, prevVal);
}
/**
* @param curLift
* @param actualLift
*/
private void validateDeclaration(int curLift, String automaticProgression, String declaration, String change1,
String change2, String actualLift) {
if (declaration == null || declaration.trim().length() == 0) return; // allow
// reset
// of
// field.
int newVal = zeroIfInvalid(declaration);
int iAutomaticProgression = zeroIfInvalid(automaticProgression);
// allow null declaration for reloading old results.
if (iAutomaticProgression > 0 && newVal < iAutomaticProgression) throw RuleViolation.declarationValueTooSmall(curLift, newVal, iAutomaticProgression);
}
/**
* Broadcast a Lifter.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
.debug("Lifter: firing event from " + System.identityHashCode(this) + " " + lastName + " " + firstName + " " + updateEvent.getPropertyIds()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if (eventRouter != null) {
eventRouter.fireEvent(updateEvent);
}
}
/**
* @return
*/
public String getMastersLongCategory() {
String catString;
String gender1 = getGender().toUpperCase();
final String mastersAgeCategory = getMastersAgeGroup(gender1);
final String shortCategory = getShortCategory(gender1);
catString = mastersAgeCategory + " " + shortCategory;
return catString;
}
/**
* @param gender
* @return
*/
public String getMastersAgeGroup() {
String gender1 = getGender().toUpperCase();
return getMastersAgeGroup(gender1);
}
/**
* @param gender1
* @return
*/
private String getMastersAgeGroup(String gender1) {
Integer ageGroup1;
ageGroup1 = getAgeGroup();
final String agePlus = (("M".equals(gender1) && ageGroup1 == 80) || ("F".equals(gender1) && ageGroup1 == 65) ? "+"
: "");
final String mastersAgeCategory = gender1 + ageGroup1 + agePlus;
return mastersAgeCategory;
}
/**
* @param gender
* @return
*/
public String getShortCategory() {
String gender1 = getGender();
return getShortCategory(gender1);
}
/**
* @param gender1
* @return
*/
public String getShortCategory(String gender1) {
// final Double catMin = getCategory().getMinimumWeight();
// Double catMax = getCategory().getMaximumWeight();
// final String weightPlus = (("M".equals(gender1) && catMin > 104.999) || ("F".equals(gender1) && catMin > 74.999) ? ">"
// : "");
// if (catMax > 125) {
// catMax = catMin;
// }
// final String shortCategory = weightPlus + catMax.intValue();
// return shortCategory;
final Category category = getCategory();
if (category == null) return "";
String shortCategory = category.getName();
int gtPos = shortCategory.indexOf(">");
if (gtPos > 0) {
return shortCategory.substring(gtPos);
} else {
return shortCategory.substring(1);
}
}
/**
* @return
*/
public String getDisplayCategory() {
final Category category = getCategory();
if (category != null && Competition.isMasters()) {
return getShortCategory();
} else {
return category != null ? category.getName() : "";
}
}
/**
* @return
*/
public String getLongCategory() {
final Category category = getCategory();
if (category != null && Competition.isMasters()) {
return getMastersLongCategory();
} else {
return getDisplayCategory();
}
}
@Version
public Long getVersion() {
return version;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((club == null) ? 0 : club.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Lifter other = (Lifter) obj;
if (club == null) {
if (other.club != null)
return false;
} else if (!club.equals(other.club))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
}
| 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.data;
import java.io.Serializable;
@SuppressWarnings("serial")
public class SearchFilter implements Serializable {
private final String term;
private final Object propertyId;
private String searchName;
public SearchFilter(Object propertyId, String searchTerm, String name) {
this.propertyId = propertyId;
this.term = searchTerm;
this.searchName = name;
}
/**
* @return the term
*/
public String getTerm() {
return term;
}
/**
* @return the propertyId
*/
public Object getPropertyId() {
return propertyId;
}
/**
* @return the name of the search
*/
public String getSearchName() {
return searchName;
}
@Override
public String toString() {
return getSearchName();
}
}
| 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.data;
public class RuleViolation {
// public static RuleViolationException change1ValueTooSmall(Object... objs)
// {
// return new RuleViolationException(("RuleViolation.change1ValueTooSmall"), objs); //$NON-NLS-1$
// }
//
// public static RuleViolationException change2ValueTooSmall(Object... objs)
// {
// return new RuleViolationException(("RuleViolation.change2ValueTooSmall"), objs); //$NON-NLS-1$
// }
//
public static RuleViolationException declarationValueTooSmall(Object... objs) {
return new RuleViolationException(("RuleViolation.declarationValueTooSmall"), objs); //$NON-NLS-1$
}
//
// public static RuleViolationException liftValueTooSmall(Object... objs) {
// return new RuleViolationException(("RuleViolation.liftValueTooSmall"), objs); //$NON-NLS-1$
// }
public static RuleViolationException liftValueNotWhatWasRequested(Object... objs) {
return new RuleViolationException(("RuleViolation.liftValueNotWhatWasRequested"), objs); //$NON-NLS-1$
}
public static RuleViolationException declaredChangesNotOk(Object... objs) {
return new RuleViolationException(("RuleViolation.declaredChangesNotOk"), objs); //$NON-NLS-1$
}
public static RuleViolationException liftValueBelowProgression(int curLift, String actualLift,
int automaticProgression) {
return new RuleViolationException(
("RuleViolation.liftValueBelowProgression"), curLift, actualLift, automaticProgression); //$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.data;
/**
* @author jflamy
*
*/
public class Team {
}
| 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.data;
import java.text.MessageFormat;
import java.util.Locale;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.Localized;
import com.vaadin.data.Validator.InvalidValueException;
public class RuleViolationException extends InvalidValueException implements Localized {
private static final long serialVersionUID = 8965943679108964933L;
private String messageKey;
private Object[] messageFormatData;
private Locale locale;
public RuleViolationException(String s, Object... objs) {
super(s);
this.messageKey = s;
this.messageFormatData = objs;
}
public RuleViolationException(Locale l, String s, Object... objs) {
super(s);
this.setLocale(l);
this.messageKey = s;
this.messageFormatData = objs;
}
@Override
public String getMessage() {
return getLocalizedMessage();
}
@Override
public void setLocale(Locale locale) {
this.locale = locale;
}
@Override
public String getLocalizedMessage() {
final Locale locale1 = (this.locale == null ? CompetitionApplication.getDefaultLocale() : this.locale);
final String messageTemplate = Messages.getString(this.messageKey, locale1);
return MessageFormat.format(messageTemplate, messageFormatData);
}
public String getLocalizedMessage(Locale locale1) {
final String messageTemplate = Messages.getString(this.messageKey, locale1);
return MessageFormat.format(messageTemplate, messageFormatData);
}
@Override
public Locale getLocale() {
return this.locale;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
/**
* This comparator is used for the standard display board. It returns the same
* order throughout the competition.
*
* @author jflamy
*
*/
public class DisplayOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (Competition.isMasters()) {
compare = compareAgeGroup(lifter1, lifter2);
if (compare != 0) return -compare;
}
if (WinningOrderComparator.useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (compare != 0) return compare;
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLastName(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareFirstName(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This comparator sorts lifters within their team
*
* @author jflamy
*
*/
public class TeamRankingComparator extends AbstractLifterComparator implements Comparator<Lifter> {
final private static Logger logger = LoggerFactory.getLogger(TeamRankingComparator.class);
private Ranking rankingType;
TeamRankingComparator(Ranking rankingType) {
this.rankingType = rankingType;
}
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareClub(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareGender(lifter1, lifter2);
if (compare != 0) return compare;
compare = comparePointsOrder(lifter1, lifter2);
if (compare != 0) return -compare;
return compare;
}
/**
* @param lifter1
* @param lifter2
* @return
*/
private int comparePointsOrder(Lifter lifter1, Lifter lifter2) {
switch (rankingType) {
case SNATCH:
return lifter1.getSnatchPoints().compareTo(lifter2.getSnatchPoints());
case CLEANJERK:
return lifter1.getCleanJerkPoints().compareTo(lifter2.getCleanJerkPoints());
case TOTAL:
final Float totalPoints1 = lifter1.getTotalPoints();
final Float totalPoints2 = lifter2.getTotalPoints();
final int compareTo = totalPoints1.compareTo(totalPoints2);
logger.trace(lifter1 + " " + totalPoints1 + " [" + compareTo + "]" + lifter2 + " " + totalPoints2);
return compareTo;
case COMBINED:
final Float combinedPoints1 = lifter1.getCombinedPoints();
final Float combinedPoints2 = lifter2.getCombinedPoints();
final int compareCombined = combinedPoints1.compareTo(combinedPoints2);
logger.trace(lifter1 + " " + combinedPoints1 + " [" + compareCombined + "]" + lifter2 + " " + combinedPoints2);
return compareCombined;
}
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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
/**
* This comparator is used for the technical meeting sheet. It is based on the
* registration category
*
* @author jflamy
*
*/
public class WeighInOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareGroupWeighInTime(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLastName(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareFirstName(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
public class LiftOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare;
// a lifter that has the boolean flag "forceAsFirst" collates smallest
// by definition
compare = compareForcedAsFirst(lifter1, lifter2);
if (compare != 0) return compare;
// lifters who are done lifting are shown at bottom, in reverse total
// number
compare = compareFinalResults(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLiftType(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareRequestedWeight(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareAttemptsDone(lifter1, lifter2);
if (compare != 0) return compare;
compare = comparePreviousLiftOrderExceptAtEnd(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Medal ordering.
*
* @author jflamy
*
*/
public class WinningOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
final static Logger logger = LoggerFactory.getLogger(WinningOrderComparator.class);
/**
* Normally we use the computed category; but for special tournaments we
* want to override this. For example, a tournament may feature "beginners"
* category with special judging rules. It is then possible to assign
* different registration categories to these persons without messing up the
* regular competition.
*/
public static boolean useRegistrationCategory = false;
public static boolean useCategorySinclair = true;
private Ranking rankingType;
public WinningOrderComparator(Ranking rankingType) {
this.rankingType = rankingType;
}
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
switch (rankingType) {
case SNATCH:
return compareSnatchResultOrder(lifter1, lifter2);
case CLEANJERK:
return compareCleanJerkResultOrder(lifter1, lifter2);
case TOTAL:
return compareTotalResultOrder(lifter1, lifter2);
case CUSTOM:
return compareCustomResultOrder(lifter1, lifter2);
case SINCLAIR:
if (Competition.isMasters()) {
return compareSMMResultOrder(lifter1, lifter2);
} else {
if (useCategorySinclair) {
return compareCategorySinclairResultOrder(lifter1, lifter2);
} else {
return compareSinclairResultOrder(lifter1, lifter2);
}
}
}
return compare;
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareTotalResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (Competition.isMasters()) {
compare = compareGender(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareAgeGroup(lifter1, lifter2);
if (compare != 0) return -compare;
}
if (useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (compare != 0) return compare;
compare = compareTotal(lifter1, lifter2);
if (compare != 0) return -compare; // we want reverse order - smaller
// comes after
return sharedCoefficientComparison(lifter1, lifter2);
}
public int compareSnatchResultOrder(Lifter lifter1, Lifter lifter2) {
boolean trace =
// (
// (lifter1.getFirstName().equals("Yvon") &&
// lifter2.getFirstName().equals("Anthony"))
// ||
// (lifter2.getFirstName().equals("Yvon") &&
// lifter1.getFirstName().equals("Anthony"))
// );
false;
int compare = 0;
if (trace) logger.trace("lifter1 {}; lifter2 {}", lifter1.getFirstName(), lifter2.getFirstName());
if (useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (trace) logger.trace("compareCategory {}", compare);
if (compare != 0) return compare;
compare = compareBestSnatch(lifter1, lifter2);
if (trace) logger.trace("compareBestSnatch {}", compare);
if (compare != 0) return -compare; // smaller snatch is less good
compare = compareBodyWeight(lifter1, lifter2);
if (trace) logger.trace("compareBodyWeight {}", compare);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestSnatchAttemptNumber(lifter1, lifter2);
if (trace) logger.trace("compareBestSnatchAttemptNumber {}", compare);
if (compare != 0) return compare; // earlier best attempt wins
compare = comparePreviousAttempts(lifter1.getBestSnatchAttemptNumber(), false, lifter1, lifter2);
if (trace) logger.trace("comparePreviousAttempts {}", compare);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The referee examination example shows a case where the lifter in the
// earlier group is not
// given the ranking.
// compare = compareGroup(lifter1, lifter2);
// if (trace) logger.trace("compareGroup {}",compare);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (trace) logger.trace("compareLotNumber {}", compare);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
public int compareCleanJerkResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (compare != 0) return compare;
compare = compareBestCleanJerk(lifter1, lifter2);
if (compare != 0) return -compare; // smaller is less good
compare = compareBodyWeight(lifter1, lifter2);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestCleanJerkAttemptNumber(lifter1, lifter2);
if (compare != 0) return compare; // earlier best attempt wins
compare = comparePreviousAttempts(lifter1.getBestCleanJerkAttemptNumber(), true, lifter1, lifter2);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The referee examination example shows a case where the lifter in the
// earlier group is not
// given the ranking.
// compare = compareGroup(lifter1, lifter2);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareSinclairResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareSinclair(lifter1, lifter2);
if (compare != 0) return compare;
return sharedCoefficientComparison(lifter1, lifter2);
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareCategorySinclairResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareCategorySinclair(lifter1, lifter2);
if (compare != 0) return compare;
return sharedCoefficientComparison(lifter1, lifter2);
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareSMMResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareSMM(lifter1, lifter2);
if (compare != 0) return compare;
return sharedCoefficientComparison(lifter1, lifter2);
}
/**
* Processing shared between all coefficient-based rankings
*
* @param lifter1
* @param lifter2
* @return
*/
private int sharedCoefficientComparison(Lifter lifter1, Lifter lifter2) {
int compare;
compare = compareBodyWeight(lifter1, lifter2);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestCleanJerk(lifter1, lifter2);
if (compare != 0) return compare; // smallest clean and jerk wins (i.e.
// best snatch wins !)
compare = compareBestCleanJerkAttemptNumber(lifter1, lifter2);
if (compare != 0) return compare; // earlier best attempt wins
// note that when comparing total, we do NOT consider snatch. At this
// stage, both lifters have
// done the same weight at the same attempt. We are trying to determine
// who did the attempt first.
// So if the best attempt was the first one, we must NOT consider snatch
// results when doing this determination
compare = comparePreviousAttempts(lifter1.getBestResultAttemptNumber(), true, lifter1, lifter2);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The IWF referee examination example shows a case where the lifter in
// the earlier group is not
// given the ranking; according to the answers, lot number alone is
// used.
// compare = compareGroup(lifter1, lifter2);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* This variant allows judges to award a score based on a formula, with bonuses
* or penalties, manually. Used for the under-12 championship in Quebec.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareCustomResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (Competition.isMasters()) {
compare = compareGender(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareAgeGroup(lifter1, lifter2);
if (compare != 0) return -compare;
}
compare = compareRegistrationCategory(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareCustomScore(lifter1, lifter2);
if (compare != 0) return -compare; // we want reverse order - smaller comes after
compare = compareTotal(lifter1, lifter2);
if (compare != 0) return -compare; // we want reverse order - smaller comes after
return sharedCoefficientComparison(lifter1, lifter2);
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
/**
* This comparator is used to highlight the lifters that have lifted recently,
* and are likely to request changes to the automatic progression. It simply
* sorts according to time stamp, if available. Else lot number is used.
*
* @author jflamy
*
*/
public class LiftTimeStampComparator extends AbstractLifterComparator implements Comparator<Lifter> {
public LiftTimeStampComparator() {
}
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = comparePreviousLiftOrder(lifter1, lifter2);
if (compare != 0) return -compare;
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
/**
* This comparator sorts lifters within their team
*
* @author jflamy
*
*/
public class TeamPointsOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
private Ranking rankingType;
TeamPointsOrderComparator(Ranking rankingType) {
this.rankingType = rankingType;
}
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareClub(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareGender(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareRanking(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
/**
* @param lifter1
* @param lifter2
* @return
*/
private int compareRanking(Lifter lifter1, Lifter lifter2) {
switch (rankingType) {
case SNATCH:
return lifter1.getSnatchRank().compareTo(lifter2.getSnatchRank());
case CLEANJERK:
return lifter1.getCleanJerkRank().compareTo(lifter2.getCleanJerkRank());
case TOTAL:
return lifter1.getRank().compareTo(lifter2.getRank());
}
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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Medal ordering.
*
* @author jflamy
*
*/
public class CombinedPointsOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
final static Logger logger = LoggerFactory.getLogger(CombinedPointsOrderComparator.class);
private Ranking rankingType;
public CombinedPointsOrderComparator(Ranking rankingType) {
this.rankingType = rankingType;
}
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
switch (rankingType) {
case SNATCH:
return compareSnatchResultOrder(lifter1, lifter2);
case CLEANJERK:
return compareCleanJerkResultOrder(lifter1, lifter2);
case TOTAL:
return compareTotalResultOrder(lifter1, lifter2);
case SINCLAIR:
return compareSinclairResultOrder(lifter1, lifter2);
}
return compare;
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareTotalResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (WinningOrderComparator.useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (compare != 0) return compare;
compare = compareTotal(lifter1, lifter2);
if (compare != 0) return -compare; // we want reverse order - smaller
// comes after
compare = compareBodyWeight(lifter1, lifter2);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestCleanJerk(lifter1, lifter2);
if (compare != 0) return compare; // smallest clean and jerk wins (i.e.
// best snatch wins !)
compare = compareBestCleanJerkAttemptNumber(lifter1, lifter2);
if (compare != 0) return compare; // earlier best attempt wins
// note that when comparing total, we do NOT consider snatch. At this
// stage, both lifters have
// done the same weight at the same attempt. We are trying to determine
// who did the attempt first.
// So if the best attempt was the first one, we must NOT consider snatch
// results when doing this determination
compare = comparePreviousAttempts(lifter1.getBestResultAttemptNumber(), true, lifter1, lifter2);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The IWF referee examination example shows a case where the lifter in
// the earlier group is not
// given the ranking; according to the answers, lot number alone is
// used.
// compare = compareGroup(lifter1, lifter2);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
public int compareSnatchResultOrder(Lifter lifter1, Lifter lifter2) {
boolean trace =
// (
// (lifter1.getFirstName().equals("Yvon") &&
// lifter2.getFirstName().equals("Anthony"))
// ||
// (lifter2.getFirstName().equals("Yvon") &&
// lifter1.getFirstName().equals("Anthony"))
// );
false;
int compare = 0;
if (trace) logger.trace("lifter1 {}; lifter2 {}", lifter1.getFirstName(), lifter2.getFirstName());
if (WinningOrderComparator.useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (trace) logger.trace("compareCategory {}", compare);
if (compare != 0) return compare;
compare = compareBestSnatch(lifter1, lifter2);
if (trace) logger.trace("compareBestSnatch {}", compare);
if (compare != 0) return -compare; // smaller snatch is less good
compare = compareBodyWeight(lifter1, lifter2);
if (trace) logger.trace("compareBodyWeight {}", compare);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestSnatchAttemptNumber(lifter1, lifter2);
if (trace) logger.trace("compareBestSnatchAttemptNumber {}", compare);
if (compare != 0) return compare; // earlier best attempt wins
compare = comparePreviousAttempts(lifter1.getBestSnatchAttemptNumber(), false, lifter1, lifter2);
if (trace) logger.trace("comparePreviousAttempts {}", compare);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The referee examination example shows a case where the lifter in the
// earlier group is not
// given the ranking.
// compare = compareGroup(lifter1, lifter2);
// if (trace) logger.trace("compareGroup {}",compare);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (trace) logger.trace("compareLotNumber {}", compare);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
public int compareCleanJerkResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
if (WinningOrderComparator.useRegistrationCategory) {
compare = compareRegistrationCategory(lifter1, lifter2);
} else {
compare = compareCategory(lifter1, lifter2);
}
if (compare != 0) return compare;
compare = compareBestCleanJerk(lifter1, lifter2);
if (compare != 0) return -compare; // smaller is less good
compare = compareBodyWeight(lifter1, lifter2);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestCleanJerkAttemptNumber(lifter1, lifter2);
if (compare != 0) return compare; // earlier best attempt wins
compare = comparePreviousAttempts(lifter1.getBestCleanJerkAttemptNumber(), true, lifter1, lifter2);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The referee examination example shows a case where the lifter in the
// earlier group is not
// given the ranking.
// compare = compareGroup(lifter1, lifter2);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
/**
* Determine who ranks first. If the body weights are the same, the lifter
* who reached total first is ranked first.
*
* @param lifter1
* @param lifter2
* @return
*/
public int compareSinclairResultOrder(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareSinclair(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareBodyWeight(lifter1, lifter2);
if (compare != 0) return compare; // smaller lifter wins
compare = compareBestCleanJerk(lifter1, lifter2);
if (compare != 0) return compare; // smallest clean and jerk wins (i.e.
// best snatch wins !)
compare = compareBestCleanJerkAttemptNumber(lifter1, lifter2);
if (compare != 0) return compare; // earlier best attempt wins
// note that when comparing total, we do NOT consider snatch. At this
// stage, both lifters have
// done the same weight at the same attempt. We are trying to determine
// who did the attempt first.
// So if the best attempt was the first one, we must NOT consider snatch
// results when doing this determination
compare = comparePreviousAttempts(lifter1.getBestResultAttemptNumber(), true, lifter1, lifter2);
if (compare != 0) return compare; // compare attempted weights (prior to
// best attempt), smaller first
// The IWF referee examination example shows a case where the lifter in
// the earlier group is not
// given the ranking; according to the answers, lot number alone is
// used.
// compare = compareGroup(lifter1, lifter2);
// if (compare != 0) return compare; // if split groups, smallest group
// wins -- lifted earlier
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare; // if equality within a group,
// smallest lot number wins
return compare;
}
}
| 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.data.lifterSort;
import java.util.Comparator;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
/**
* This comparator is used for the technical meeting sheet. It is based on the
* registration category
*
* @author jflamy
*
*/
public class RegistrationOrderComparator extends AbstractLifterComparator implements Comparator<Lifter> {
@Override
public int compare(Lifter lifter1, Lifter lifter2) {
int compare = 0;
compare = compareGroupWeighInTime(lifter1, lifter2);
if (compare != 0) return compare;
if (Competition.isMasters()) {
compare = compareAgeGroup(lifter1, lifter2);
if (compare != 0) return -compare;
}
compare = compareRegistrationCategory(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLotNumber(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareLastName(lifter1, lifter2);
if (compare != 0) return compare;
compare = compareFirstName(lifter1, lifter2);
if (compare != 0) return compare;
return compare;
}
}
| 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.data.lifterSort;
import java.util.Date;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AbstractLifterComparator {
final private static Logger logger = LoggerFactory.getLogger(AbstractLifterComparator.class);
int compareCategory(Lifter lifter1, Lifter lifter2) {
Category lifter1Value = lifter1.getCategory();
Category lifter2Value = lifter2.getCategory();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
int compare = compareGender(lifter1,lifter2);
if (compare != 0) return compare;
Double value1 = lifter1.getCategory().getMaximumWeight();
Double value2 = lifter2.getCategory().getMaximumWeight();
return value1.compareTo(value2);
}
int compareRegistrationCategory(Lifter lifter1, Lifter lifter2) {
Category lifter1Category = lifter1.getRegistrationCategory();
Category lifter2Category = lifter2.getRegistrationCategory();
if (lifter1Category == null && lifter2Category == null) return 0;
if (lifter1Category == null) return -1;
if (lifter2Category == null) return 1;
int compare = compareGender(lifter1,lifter2);
if (compare != 0) return compare;
Double value1 = lifter1Category.getMaximumWeight();
Double value2 = lifter2Category.getMaximumWeight();
return value1.compareTo(value2);
}
int compareFirstName(Lifter lifter1, Lifter lifter2) {
String lifter1Value = lifter1.getFirstName();
String lifter2Value = lifter2.getFirstName();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
return lifter1Value.compareTo(lifter2Value);
}
int compareLastName(Lifter lifter1, Lifter lifter2) {
String lifter1Value = lifter1.getLastName();
String lifter2Value = lifter2.getLastName();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
return lifter1Value.compareTo(lifter2Value);
}
int compareLotNumber(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getLotNumber();
Integer lifter2Value = lifter2.getLotNumber();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
return lifter1Value.compareTo(lifter2Value);
}
int compareAgeGroup(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getAgeGroup();
Integer lifter2Value = lifter2.getAgeGroup();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
return lifter1Value.compareTo(lifter2Value);
}
int compareGroup(Lifter lifter1, Lifter lifter2) {
CompetitionSession lifter1Group = lifter1.getCompetitionSession();
CompetitionSession lifter2Group = lifter2.getCompetitionSession();
if (lifter1Group == null && lifter2Group == null) return 0;
if (lifter1Group == null) return -1;
if (lifter2Group == null) return 1;
String lifter1Value = lifter1Group.getName();
String lifter2Value = lifter2Group.getName();
if (lifter1Value == null && lifter2Value == null) return 0;
if (lifter1Value == null) return -1;
if (lifter2Value == null) return 1;
return lifter1Value.compareTo(lifter2Value);
}
int compareGroupWeighInTime(Lifter lifter1, Lifter lifter2) {
CompetitionSession lifter1Group = lifter1.getCompetitionSession();
CompetitionSession lifter2Group = lifter2.getCompetitionSession();
if (lifter1Group == null && lifter2Group == null) return 0;
if (lifter1Group == null) return -1;
if (lifter2Group == null) return 1;
Date lifter1Date = lifter1Group.getWeighInTime();
Date lifter2Date = lifter2Group.getWeighInTime();
if (lifter1Date == null && lifter2Date == null) return 0;
if (lifter1Date == null) return -1;
if (lifter2Date == null) return 1;
int compare = lifter1Date.compareTo(lifter2Date);
if (compare != 0) return compare;
String lifter1String = lifter1Group.getName();
String lifter2String = lifter2Group.getName();
if (lifter1String == null && lifter2String == null) return 0;
if (lifter1String == null) return -1;
if (lifter2String == null) return 1;
return lifter1String.compareTo(lifter2String);
}
/**
* Comparer les totaux des leveurs, si ils ont termin� tous leurs essais. Le
* leveur ayant terminé va après, de manière à ce le premier à lever soit
* toujours toujours le premier dans la liste.
*
* @param lifter1
* @param lifter2
* @return -1,0,1 selon comparaison
*/
int compareFinalResults(Lifter lifter1, Lifter lifter2) {
Integer lifter1Done = (lifter1.getAttemptsDone() >= 6 ? 1 : 0);
Integer lifter2Done = (lifter2.getAttemptsDone() >= 6 ? 1 : 0);
int compare = lifter1Done.compareTo(lifter2Done);
if (compare != 0) return compare;
// at this point both lifters are done, or both are not done.
if (lifter1Done == 0) {
// both are not done
return 0;
} else {
// both are done, use descending order on total
return -compareTotal(lifter1, lifter2);
}
}
int compareLiftType(Lifter lifter1, Lifter lifter2) {
// snatch comes before clean and jerk
Integer lifter1Value = lifter1.getAttemptsDone();
Integer lifter2Value = lifter2.getAttemptsDone();
if (lifter1Value < 3) {
lifter1Value = 0;
} else {
lifter1Value = 1;
}
if (lifter2Value < 3) {
lifter2Value = 0;
} else {
lifter2Value = 1;
}
return lifter1Value.compareTo(lifter2Value);
}
int compareRequestedWeight(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getNextAttemptRequestedWeight();
Integer lifter2Value = lifter2.getNextAttemptRequestedWeight();
if (lifter1Value == null || lifter1Value == 0) lifter1Value = 999; // place people with no
// declared weight at the end
if (lifter2Value == null || lifter2Value == 0) lifter2Value = 999; // place people with no
// declared weight at the end
return lifter1Value.compareTo(lifter2Value);
}
int compareAttemptsDone(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getAttemptsDone();
Integer lifter2Value = lifter2.getAttemptsDone();
return lifter1Value.compareTo(lifter2Value);
}
/**
* Return who lifted last, for real.
*
* @param lifter1
* @param lifter2
* @return
*/
int comparePreviousLiftOrder(Lifter lifter1, Lifter lifter2) {
Date lifter1Value = lifter1.getLastLiftTime();
Date lifter2Value = lifter2.getLastLiftTime();
final Date longAgo = new Date(0L);
if (lifter1Value == null) lifter1Value = longAgo;
if (lifter2Value == null) lifter2Value = longAgo;
return lifter1Value.compareTo(lifter2Value);
}
/**
* Return who lifted last, ignoring lifters who are done lifting for this
* part of the meet.
*
* @param lifter1
* @param lifter2
* @return
*/
int comparePreviousLiftOrderExceptAtEnd(Lifter lifter1, Lifter lifter2) {
Date lifter1Value = lifter1.getLastLiftTime();
Date lifter2Value = lifter2.getLastLiftTime();
final Date longAgo = new Date(0L);
if (lifter1Value == null) lifter1Value = longAgo;
if (lifter2Value == null) lifter2Value = longAgo;
// at start of snatch and start of clean and jerk, previous lift is
// irrelevant.
if (lifter1.getAttemptsDone() == 3) lifter1Value = longAgo;
if (lifter2.getAttemptsDone() == 3) lifter2Value = longAgo;
return lifter1Value.compareTo(lifter2Value);
}
int compareTotal(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getTotal();
Integer lifter2Value = lifter2.getTotal();
return lifter1Value.compareTo(lifter2Value);
}
int compareCustomScore(Lifter lifter1, Lifter lifter2) {
Double lifter1Value = lifter1.getCustomScore();
Double lifter2Value = lifter2.getCustomScore();
final Double notScored = 0D;
if (lifter1Value == null) lifter1Value = notScored;
if (lifter2Value == null) lifter2Value = notScored;
return lifter1Value.compareTo(lifter2Value);
}
int compareBodyWeight(Lifter lifter1, Lifter lifter2) {
Double lifter1Value = lifter1.getBodyWeight();
Double lifter2Value = lifter2.getBodyWeight();
final Double notWeighed = 0D;
if (lifter1Value == null) lifter1Value = notWeighed;
if (lifter2Value == null) lifter2Value = notWeighed;
return lifter1Value.compareTo(lifter2Value);
}
int compareSinclair(Lifter lifter1, Lifter lifter2) {
String gender = lifter1.getGender();
if (gender == null) return -1;
int compare = gender.compareTo(lifter2.getGender());
if (compare != 0) return compare;
Double lifter1Value = lifter1.getSinclair();
Double lifter2Value = lifter2.getSinclair();
final Double notWeighed = 0D;
if (lifter1Value == null) lifter1Value = notWeighed;
if (lifter2Value == null) lifter2Value = notWeighed;
// bigger sinclair comes first
return -lifter1Value.compareTo(lifter2Value);
}
int compareCategorySinclair(Lifter lifter1, Lifter lifter2) {
String gender = lifter1.getGender();
if (gender == null) return -1;
int compare = gender.compareTo(lifter2.getGender());
if (compare != 0) return compare;
Double lifter1Value = lifter1.getCategorySinclair();
Double lifter2Value = lifter2.getCategorySinclair();
final Double notWeighed = 0D;
if (lifter1Value == null) lifter1Value = notWeighed;
if (lifter2Value == null) lifter2Value = notWeighed;
// bigger sinclair comes first
return -lifter1Value.compareTo(lifter2Value);
}
int compareSMM(Lifter lifter1, Lifter lifter2) {
String gender = lifter1.getGender();
if (gender == null) return -1;
int compare = gender.compareTo(lifter2.getGender());
if (compare != 0) return compare;
Double lifter1Value = lifter1.getSMM();
Double lifter2Value = lifter2.getSMM();
final Double notWeighed = 0D;
if (lifter1Value == null) lifter1Value = notWeighed;
if (lifter2Value == null) lifter2Value = notWeighed;
// bigger sinclair comes first
return -lifter1Value.compareTo(lifter2Value);
}
int compareLastSuccessfulLiftTime(Lifter lifter1, Lifter lifter2) {
Date lifter1Value = lifter1.getLastSuccessfulLiftTime();
Date lifter2Value = lifter2.getLastSuccessfulLiftTime();
// safe to compare, no nulls.
return lifter1Value.compareTo(lifter2Value);
}
int compareForcedAsFirst(Lifter lifter1, Lifter lifter2) {
// can't be nulls, method returns primitive boolean
Boolean lifter1Value = lifter1.getForcedAsCurrent();
Boolean lifter2Value = lifter2.getForcedAsCurrent();
// true.compareTo(false) returns positive (i.e. greater). We want the
// opposite.
final int compare = -lifter1Value.compareTo(lifter2Value);
return compare;
}
int compareBestCleanJerk(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getBestCleanJerk();
Integer lifter2Value = lifter2.getBestCleanJerk();
return lifter1Value.compareTo(lifter2Value);
}
int compareBestSnatch(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getBestSnatch();
Integer lifter2Value = lifter2.getBestSnatch();
return lifter1Value.compareTo(lifter2Value);
}
int compareBestLiftAttemptNumber(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getBestResultAttemptNumber();
Integer lifter2Value = lifter2.getBestResultAttemptNumber();
return lifter1Value.compareTo(lifter2Value);
}
int compareBestSnatchAttemptNumber(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getBestSnatchAttemptNumber();
Integer lifter2Value = lifter2.getBestSnatchAttemptNumber();
return lifter1Value.compareTo(lifter2Value);
}
int compareBestCleanJerkAttemptNumber(Lifter lifter1, Lifter lifter2) {
Integer lifter1Value = lifter1.getBestCleanJerkAttemptNumber();
Integer lifter2Value = lifter2.getBestCleanJerkAttemptNumber();
return lifter1Value.compareTo(lifter2Value);
}
/**
* Compare absolute value of attempts prior to attempt "startingFrom" Start
* comparing attempted weights at "startingFrom". If attempted weight
* differ, smallest attempted weight comes first. If attempted weights are
* same, go back one attempt and keep comparing.
*
* startingFrom is exclusive endingWith is inclusive, and is used to the
* previous attempts.
*
* @param startingFrom
* @param excludeSnatch
* to consider only cleanAndJerk
* @param lifter1
* @param lifter2
* @return
*/
int comparePreviousAttempts(int startingFrom, boolean excludeSnatch, Lifter lifter1, Lifter lifter2) {
int compare = 0;
boolean trace = false;
if (trace)
logger.trace("starting from {}, lifter1 {}, lifter2 {}", new Object[] { startingFrom, lifter1, lifter2 });
if (startingFrom >= 6) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getCleanJerk3ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getCleanJerk3ActualLift())));
if (trace) logger.trace("essai 6: {}", compare);
if (compare != 0) return compare;
}
if (startingFrom >= 5) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getCleanJerk2ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getCleanJerk2ActualLift())));
if (trace) logger.trace("essai 5: {}", compare);
if (compare != 0) return compare;
}
if (startingFrom >= 4) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getCleanJerk1ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getCleanJerk1ActualLift())));
if (trace) logger.trace("essai 4: {}", compare);
if (compare != 0) return compare;
}
if (excludeSnatch) {
return 0;
}
if (startingFrom >= 3) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getSnatch3ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getSnatch3ActualLift())));
if (trace) logger.trace("essai 3: {}", compare);
if (compare != 0) return compare;
}
if (startingFrom >= 2) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getSnatch2ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getSnatch2ActualLift())));
if (trace) logger.trace("essai 2: {}", compare);
if (compare != 0) return compare;
}
if (startingFrom >= 1) {
compare = ((Integer) Math.abs(Lifter.zeroIfInvalid(lifter1.getSnatch1ActualLift()))).compareTo(Math
.abs(Lifter.zeroIfInvalid(lifter2.getSnatch1ActualLift())));
if (trace) logger.trace("essai 1: {}", compare);
if (compare != 0) return compare;
}
return 0;
}
/**
* @param lifter1
* @param lifter2
* @return
*/
protected int compareGender(Lifter lifter1, Lifter lifter2) {
String gender1 = lifter1.getGender();
String gender2 = lifter2.getGender();
if (gender1 == null && gender2 == null) return 0;
if (gender1 == null) return -1;
if (gender2 == null) return 1;
// "F" is smaller than "M"
return gender1.compareTo(gender2);
}
/**
* @param lifter1
* @param lifter2
* @return
*/
protected int compareClub(Lifter lifter1, Lifter lifter2) {
String club1 = lifter1.getClub();
String club2 = lifter2.getClub();
if (club1 == null && club2 == null) return 0;
if (club1 == null) return -1;
if (club2 == null) return 1;
return lifter1.getClub().compareTo(lifter2.getClub());
}
}
| 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.data.lifterSort;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.persistence.Entity;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @since
* @author jflamy
*/
@Entity
public class LifterSorter implements Serializable {
private static final long serialVersionUID = -3507146241019771820L;
private static final Logger logger = LoggerFactory.getLogger(LifterSorter.class);
public enum Ranking {
SNATCH, CLEANJERK, TOTAL, COMBINED, SINCLAIR, CUSTOM
}
/**
* Sort lifters according to official rules, creating a new list.
*
* @see #liftingOrder(List)
* @return lifters, ordered according to their lifting order
*/
static public List<Lifter> liftingOrderCopy(List<Lifter> toBeSorted) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
liftingOrder(sorted);
return sorted;
}
/**
* Sort lifters according to official rules.
* <p>
* <li>Lowest weight goes first</li>
* <li>At same weight, lower attempt goes first</li>
* <li>At same weight and same attempt, whoever lifted first goes first</li>
* <li>At first attempt of each lift, lowest lot number goes first if same
* weight is requested</li>
* </p>
*/
static public void liftingOrder(List<Lifter> toBeSorted) {
Collections.sort(toBeSorted, new LiftOrderComparator());
int liftOrder = 1;
for (Lifter curLifter : toBeSorted) {
curLifter.setLiftOrderRank(liftOrder++);
}
}
/**
* Sort lifters according to official rules (in place) <tableToolbar> <li>by
* category</li> <li>by lot number</li> </tableToolbar>
*/
static public void displayOrder(List<Lifter> toBeSorted) {
Collections.sort(toBeSorted, new DisplayOrderComparator());
}
/**
* Sort lifters according to official rules, creating a new list.
*
* @see #liftingOrder(List)
* @return lifters, ordered according to their standard order
*/
static public List<Lifter> displayOrderCopy(List<Lifter> toBeSorted) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
displayOrder(sorted);
return sorted;
}
/**
* Sort lifters according to official rules (in place) for the technical
* meeting <tableToolbar> <li>by registration category</li> <li>by lot
* number</li> </tableToolbar>
*/
static public void registrationOrder(List<Lifter> toBeSorted) {
Collections.sort(toBeSorted, new RegistrationOrderComparator());
}
/**
* Sort lifters according to official rules, creating a new list.
*
* @see #liftingOrder(List)
* @return lifters, ordered according to their standard order for the
* technical meeting
*/
static public List<Lifter> registrationOrderCopy(List<Lifter> toBeSorted) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
registrationOrder(sorted);
return sorted;
}
/**
* Sort lifters according to official rules (in place) for the technical
* meeting <tableToolbar> <li>by registration category</li> <li>by lot
* number</li> </tableToolbar>
*/
static public void weighInOrder(List<Lifter> toBeSorted) {
Collections.sort(toBeSorted, new WeighInOrderComparator());
}
/**
* Sort lifters according to official rules, creating a new list.
*
* @see #liftingOrder(List)
* @return lifters, ordered according to their standard order for the
* technical meeting
*/
static public List<Lifter> weighInOrderCopy(List<Lifter> toBeSorted) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
weighInOrder(sorted);
return sorted;
}
/**
* Sort lifters according to winning order, creating a new list.
*
* @see #liftingOrder(List)
* @return lifters, ordered according to their category and totalRank order
*/
static public List<Lifter> resultsOrderCopy(List<Lifter> toBeSorted, Ranking rankingType) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
resultsOrder(sorted, rankingType);
return sorted;
}
/**
* Sort lifters according to winning order.
*/
static public void resultsOrder(List<Lifter> toBeSorted, Ranking rankingType) {
Collections.sort(toBeSorted, new WinningOrderComparator(rankingType));
int liftOrder = 1;
for (Lifter curLifter : toBeSorted) {
curLifter.setResultOrderRank(liftOrder++, rankingType);
}
}
/**
* @param lifters
* @param sinclair
*/
@SuppressWarnings("unused")
private void teamPointsOrder(List<Lifter> toBeSorted, Ranking rankingType) {
Collections.sort(toBeSorted, new TeamPointsOrderComparator(rankingType));
}
/**
* @param lifters
* @param combined
*/
@SuppressWarnings("unused")
private void combinedPointsOrder(List<Lifter> toBeSorted, Ranking rankingType) {
Collections.sort(toBeSorted, new CombinedPointsOrderComparator(rankingType));
}
/**
* Assign lot numbers at random.
*
* @param toBeSorted
*/
static public List<Lifter> drawLots(List<Lifter> toBeShuffled) {
List<Lifter> shuffled = new ArrayList<Lifter>(toBeShuffled);
Collections.shuffle(shuffled, new Random());
assignLotNumbers(shuffled);
return shuffled;
}
/**
* Assign lot numbers, sequentially. Normally called by
* {@link #drawLots(List)}.
*
* @param shuffledList
*/
static public void assignLotNumbers(List<Lifter> shuffledList) {
int lotNumber = 1;
for (Lifter curLifter : shuffledList) {
curLifter.setLotNumber(lotNumber++);
}
}
/**
* Sets the current lifter as such (setCurrentLifter(true)), the others to
* false
*
* @param lifters
* Assumed to be already sorted in lifting order.
*/
static public Lifter markCurrentLifter(List<Lifter> lifters) {
if (!lifters.isEmpty()) {
final Lifter firstLifter = lifters.get(0);
firstLifter.setAsCurrentLifter(firstLifter.getAttemptsDone() < 6);
for (Lifter lifter : lifters) {
if (lifter != firstLifter) {
lifter.setAsCurrentLifter(false);
}
lifter.resetForcedAsCurrent();
}
return firstLifter;
} else {
return null;
}
}
/**
* Compute the number of lifts already done. During snatch, exclude
*
* @param lifters
* Assumed to be already sorted in lifting order.
*/
static public int countLiftsDone(List<Lifter> lifters) {
if (!lifters.isEmpty()) {
int totalSnatch = 0;
int totalCJ = 0;
boolean cJHasStarted = false;
for (Lifter lifter : lifters) {
totalSnatch += lifter.getSnatchAttemptsDone();
totalCJ += lifter.getCleanJerkAttemptsDone();
if (lifter.getCleanJerkTotal() > 0) {
cJHasStarted = true;
}
}
if (cJHasStarted || totalSnatch >= lifters.size() * 3) {
return totalCJ;
} else {
return totalSnatch;
}
} else {
return 0;
}
}
/**
* Sort lifters according to who lifted last, creating a new list.
*
* @see #liftTimeOrder(List)
* @return lifters, ordered according to their lifting order
* @param toBeSorted
*/
static public List<Lifter> LiftTimeOrderCopy(List<Lifter> toBeSorted) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
liftTimeOrder(sorted);
return sorted;
}
/**
* Sort lifters according to who lifted last.
*/
static public void liftTimeOrder(List<Lifter> toBeSorted) {
Collections.sort(toBeSorted, new LiftTimeStampComparator());
}
/**
* Sort lifters by team, gender and totalRank so team totals can be computed
*
* @param lifters
* @param rankingType
* what type of lift or total is being ranked
* @return
*/
public static List<Lifter> teamRankingOrderCopy(List<Lifter> toBeSorted, Ranking rankingType) {
List<Lifter> sorted = new ArrayList<Lifter>(toBeSorted);
teamRankingOrder(sorted, rankingType);
return sorted;
}
/**
*
* Sort lifters by team, gender and totalRank so team totals can be assigned
*
* @param lifters
* @return
*/
static public void teamRankingOrder(List<Lifter> toBeSorted, Ranking rankingType) {
Collections.sort(toBeSorted, new TeamRankingComparator(rankingType));
}
/**
* Check that lifter is one of the howMany previous lifters. The list of
* lifters is assumed to have been sorted with {@link #liftTimeOrderCopy}
*
* @see #liftingOrder(List)
* @return true if lifter is found and meets criterion.
* @param toBeSorted
*/
static public boolean isRecentLifter(Lifter lifter, List<Lifter> sortedLifters, int howMany) {
int rank = sortedLifters.indexOf(lifter);
if (rank >= 0 && rank <= howMany - 1) return true;
return false;
}
/**
* Assign medals, sequentially.
*
* @param sortedList
*/
static public void assignMedals(List<Lifter> sortedList) {
Category prevCategory = null;
Integer prevAgeGroup = null;
Integer curAgeGroup = null;
int rank = 1;
for (Lifter curLifter : sortedList) {
Category curCategory = null;
if (WinningOrderComparator.useRegistrationCategory) {
curCategory = curLifter.getRegistrationCategory();
} else {
curCategory = curLifter.getCategory();
}
if (Competition.isMasters()) {
curAgeGroup = curLifter.getAgeGroup();
}
if (!equals(curCategory, prevCategory) || !equals(curAgeGroup, prevAgeGroup)) {
// category boundary has been crossed
rank = 1;
}
if (curLifter.isInvited()) {
logger.trace("lifter {} totalRank={} total={}",
new Object[] { curLifter, -1, curLifter.getTotal() }); //$NON-NLS-1$
curLifter.setRank(-1);
} else if (rank <= 3 && curLifter.getTotal() > 0) {
logger.trace("lifter {} totalRank={} total={}",
new Object[] { curLifter, rank, curLifter.getTotal() }); //$NON-NLS-1$
curLifter.setRank(rank);
rank++;
} else {
logger.trace("lifter {} totalRank={} total={}",
new Object[] { curLifter, 0, curLifter.getTotal() }); //$NON-NLS-1$
curLifter.setRank(0);
rank++;
}
prevCategory = curCategory;
prevAgeGroup = curAgeGroup;
}
}
/**
* Assign ranks, sequentially.
*
* @param sortedList
*/
public void assignCategoryRanks(List<Lifter> sortedList, Ranking rankingType) {
Category prevCategory = null;
Integer prevAgeGroup = null;
Integer curAgeGroup = null;
int rank = 1;
for (Lifter curLifter : sortedList) {
Category curCategory = null;
if (WinningOrderComparator.useRegistrationCategory || rankingType == Ranking.CUSTOM) {
curCategory = curLifter.getRegistrationCategory();
} else {
curCategory = curLifter.getCategory();
}
if (Competition.isMasters()) {
curAgeGroup = curLifter.getAgeGroup();
}
if (!equals(curCategory, prevCategory) || !equals(curAgeGroup, prevAgeGroup)) {
// category boundary has been crossed
rank = 1;
}
if (curLifter.isInvited() || !curLifter.getTeamMember()) {
logger.trace("not counted {} {}Rank={} total={} {}",
new Object[] { curLifter, rankingType, -1, curLifter.getTotal(), curLifter.isInvited() }); //$NON-NLS-1$
setRank(curLifter, -1, rankingType);
setPoints(curLifter, 0, rankingType);
} else {
// if (curLifter.getTeamMember()) {
// setTeamRank(curLifter, 0, rankingType);
// }
final double rankingTotal = getRankingTotal(curLifter, rankingType);
if (rankingTotal > 0) {
setRank(curLifter, rank, rankingType);
logger.trace("lifter {} {}rank={} total={}",
new Object[] { curLifter, rankingType, getRank(curLifter, rankingType), rankingTotal }); //$NON-NLS-1$
rank++;
} else {
logger.trace("lifter {} {}rank={} total={}",
new Object[] { curLifter, rankingType, 0, rankingTotal }); //$NON-NLS-1$
setRank(curLifter, 0, rankingType);
rank++;
}
final float points = computePoints(curLifter,rankingType);
setPoints(curLifter,points,rankingType);
}
prevCategory = curCategory;
prevAgeGroup = curAgeGroup;
}
}
/**
* Assign ranks, sequentially.
*
* @param sortedList
*/
public void assignSinclairRanksAndPoints(List<Lifter> sortedList, Ranking rankingType) {
String prevGender = null;
// String prevAgeGroup = null;
int rank = 1;
for (Lifter curLifter : sortedList) {
final String curGender = curLifter.getGender();
// final Integer curAgeGroup = curLifter.getAgeGroup();
if (!equals(curGender, prevGender)
// || !equals(curAgeGroup,prevAgeGroup)
) {
// category boundary has been crossed
rank = 1;
}
if (curLifter.isInvited() || !curLifter.getTeamMember()) {
logger.trace("invited {} {}rank={} total={} {}",
new Object[] { curLifter, rankingType, -1, curLifter.getTotal(), curLifter.isInvited() }); //$NON-NLS-1$
setRank(curLifter, -1, rankingType);
setPoints(curLifter, 0, rankingType);
} else {
setTeamRank(curLifter, 0, rankingType);
final double rankingTotal = getRankingTotal(curLifter, rankingType);
if (rankingTotal > 0) {
setRank(curLifter, rank, rankingType);
logger.trace("lifter {} {}rank={} {}={} total={}",
new Object[] { curLifter, rankingType, rank, rankingTotal }); //$NON-NLS-1$
rank++;
} else {
logger.trace("lifter {} {}rank={} total={}",
new Object[] { curLifter, rankingType, 0, rankingTotal }); //$NON-NLS-1$
setRank(curLifter, 0, rankingType);
rank++;
}
final float points = computePoints(curLifter, rankingType);
setPoints(curLifter, points, rankingType);
}
prevGender = curGender;
}
}
/**
* @param curLifter
* @param i
* @param rankingType
*/
public void setRank(Lifter curLifter, int i, Ranking rankingType) {
switch (rankingType) {
case SNATCH:
curLifter.setSnatchRank(i);
break;
case CLEANJERK:
curLifter.setCleanJerkRank(i);
break;
case TOTAL:
curLifter.setTotalRank(i);
break;
case SINCLAIR:
curLifter.setSinclairRank(i);
break;
case CUSTOM:
curLifter.setCustomRank(i);
break;
}
}
/**
* Assign ranks, sequentially.
*
* @param sortedList
*/
public void assignRanksWithinTeam(List<Lifter> sortedList, Ranking rankingType) {
String prevTeam = null;
// String prevAgeGroup = null;
int rank = 1;
for (Lifter curLifter : sortedList) {
final String curTeam = curLifter.getClub() + "_" + curLifter.getGender();
// final Integer curAgeGroup = curLifter.getAgeGroup();
if (!equals(curTeam, prevTeam)
// || !equals(curAgeGroup,prevAgeGroup)
) {
// category boundary has been crossed
rank = 1;
}
if (curLifter.isInvited() || !curLifter.getTeamMember()) {
setTeamRank(curLifter, -1, rankingType);
} else {
if (getRankingTotal(curLifter, rankingType) > 0) {
setTeamRank(curLifter, rank, rankingType);
rank++;
} else {
setTeamRank(curLifter, 0, rankingType);
rank++;
}
}
prevTeam = curTeam;
}
}
/**
* @param curLifter
* @param points
* @param rankingType
*/
private void setPoints(Lifter curLifter, float points, Ranking rankingType) {
logger.trace(curLifter + " " + rankingType + " points=" + points);
switch (rankingType) {
case SNATCH:
curLifter.setSnatchPoints(points);
break;
case CLEANJERK:
curLifter.setCleanJerkPoints(points);
break;
case TOTAL:
curLifter.setTotalPoints(points);
break;
case CUSTOM:
curLifter.setCustomPoints(points);
break;
case COMBINED:
return; // computed
}
}
/**
* @param curLifter
* @param rankingType
* @return
*/
private float computePoints(Lifter curLifter, Ranking rankingType) {
switch (rankingType) {
case SNATCH:
return pointsFormula(curLifter.getSnatchRank(), curLifter);
case CLEANJERK:
return pointsFormula(curLifter.getCleanJerkRank(), curLifter);
case TOTAL:
return pointsFormula(curLifter.getTotalRank(), curLifter);
case CUSTOM:
return pointsFormula(curLifter.getCustomRank(), curLifter);
case COMBINED:
return pointsFormula(curLifter.getSnatchRank(), curLifter)
+ pointsFormula(curLifter.getCleanJerkRank(), curLifter)
+ pointsFormula(curLifter.getTotalRank(), curLifter);
}
return 0;
}
/**
* @param rank
* @param curLifter
* @return
*/
private float pointsFormula(Integer rank, Lifter curLifter) {
if (rank == null || rank <= 0) return 0;
if (rank == 1) return 28;
if (rank == 2) return 25;
return 26 - rank;
}
/**
* @param curLifter
* @param i
* @param rankingType
*/
public static void setTeamRank(Lifter curLifter, int i, Ranking rankingType) {
switch (rankingType) {
case SNATCH:
curLifter.setTeamSnatchRank(i);
break;
case CLEANJERK:
curLifter.setTeamCleanJerkRank(i);
break;
case TOTAL:
curLifter.setTeamTotalRank(i);
break;
case SINCLAIR:
curLifter.setTeamSinclairRank(i);
break;
case COMBINED:
return; // there is no combined rank
}
}
/**
* @param curLifter
* @param rankingType
* @return
*/
public Integer getRank(Lifter curLifter, Ranking rankingType) {
switch (rankingType) {
case SNATCH:
return curLifter.getSnatchRank();
case CLEANJERK:
return curLifter.getCleanJerkRank();
case SINCLAIR:
return curLifter.getSinclairRank();
case TOTAL:
return curLifter.getRank();
case CUSTOM:
return curLifter.getCustomRank();
}
return 0;
}
/**
* @param curLifter
* @param rankingType
* @return
*/
private static double getRankingTotal(Lifter curLifter, Ranking rankingType) {
switch (rankingType) {
case SNATCH:
return curLifter.getBestSnatch();
case CLEANJERK:
return curLifter.getBestCleanJerk();
case TOTAL:
return curLifter.getTotal();
case SINCLAIR:
return curLifter.getSinclair();
case CUSTOM:
return curLifter.getCustomScore();
case COMBINED:
return 0D; // no such thing
}
return 0D;
}
static private boolean equals(Object o1, Object o2) {
if (o1 == null && o2 == null) return true;
if (o1 != null) return o1.equals(o2);
return false; // o1 is null but not o2
}
// public Collection<Team> fullResults(List<Lifter> lifters) {
// resultsOrder(lifters, Ranking.SNATCH);
// assignCategoryRanksAndPoints(lifters, Ranking.SNATCH);
// teamPointsOrder(lifters, Ranking.SNATCH);
// assignRanksWithinTeam(lifters, Ranking.SNATCH);
//
// resultsOrder(lifters, Ranking.CLEANJERK);
// assignCategoryRanksAndPoints(lifters, Ranking.CLEANJERK);
// teamPointsOrder(lifters, Ranking.CLEANJERK);
// assignRanksWithinTeam(lifters, Ranking.CLEANJERK);
//
// resultsOrder(lifters, Ranking.TOTAL);
// assignCategoryRanksAndPoints(lifters, Ranking.TOTAL);
// teamPointsOrder(lifters, Ranking.TOTAL);
// assignRanksWithinTeam(lifters, Ranking.TOTAL);
//
// combinedPointsOrder(lifters, Ranking.COMBINED);
// assignCategoryRanksAndPoints(lifters, Ranking.COMBINED);
// teamPointsOrder(lifters, Ranking.COMBINED);
// assignRanksWithinTeam(lifters, Ranking.COMBINED);
//
// resultsOrder(lifters, Ranking.SINCLAIR);
// assignCategoryRanksAndPoints(lifters, Ranking.SINCLAIR);
// teamPointsOrder(lifters, Ranking.SINCLAIR);
// assignRanksWithinTeam(lifters, Ranking.SINCLAIR);
//
// HashSet<Team> teams = new HashSet<Team>();
// return new TreeSet<Team>(teams);
// }
}
| 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.data;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.sound.sampled.Mixer;
import org.concordiainternational.competition.decision.Speakers;
import org.concordiainternational.competition.nec.NECDisplay;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.LiftList;
import org.concordiainternational.competition.webapp.WebApplicationConfiguration;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Data on a lifting site.
* <p>
* Groups are associated with a lifting platformName.
* </p>
* <p>
* Projectors and officials are associated with a lifting platformName so there
* is no need to refresh their setup during a competition. The name of the
* platformName is used as a key in the ServletContext so other sessions and
* other kinds of pages (such as JSP) can locate the information about that
* platformName. See in particular the {@link LiftList#updateTable()} method
* </p>
*
* @author jflamy
*
*/
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Platform implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(Platform.class);
private static final long serialVersionUID = -6871042180395572184L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
/**
* true if the NEC LED display is attached to the platform.
*/
Boolean hasDisplay = false;
/**
* true if the referee use this application to give decisions, and
* decision lights need to be shown on the attempt and result boards.
*/
Boolean showDecisionLights = false;
// collar
Integer nbC_2_5 = 0;
// small plates
Integer nbS_0_5 = 0;
Integer nbS_1 = 0;
Integer nbS_1_5 = 0;
Integer nbS_2 = 0;
Integer nbS_2_5 = 0;
Integer nbS_5 = 0;
// large plates
Integer nbL_2_5 = 0;
Integer nbL_5 = 0;
Integer nbL_10 = 0;
Integer nbL_15 = 0;
Integer nbL_20 = 0;
Integer nbL_25 = 0;
// bar
Integer officialBar = 0;
Integer lightBar = 0;
String mixerName = "";
transient private Mixer mixer;
public Platform() {
}
public Platform(String name) {
this.setName(name);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
@SuppressWarnings("unchecked")
static public List<Platform> getAll() {
final List<Platform> list = CompetitionApplication.getCurrent().getHbnSession().createCriteria(Platform.class).addOrder(
Order.asc("name")) //$NON-NLS-1$
.list();
return list;
}
@SuppressWarnings("unchecked")
static public Platform getByName(String name) {
final List<Platform> list = CompetitionApplication.getCurrent().getHbnSession().createCriteria(Platform.class).add(
Restrictions.eq("name", name)) //$NON-NLS-1$
.list();
if (list.size() == 1) {
final Platform platform = (Platform) list.get(0);
platform.setMixerName(platform.mixerName);
platform.setHasDisplay(platform.hasDisplay);
return platform;
} else {
return null;
}
}
public Boolean getHasDisplay() {
return isHasDisplay();
}
public Boolean isHasDisplay() {
if (hasDisplay == null) return false;
return hasDisplay;
}
public void setHasDisplay(Boolean hasDisplay) {
this.hasDisplay = hasDisplay;
if (hasDisplay) {
NECDisplay display = WebApplicationConfiguration.necDisplay;
if (display != null) {
// ensure that last platform with checkbox has display.
display.setPlatform(this);
}
}
}
public static int getSize() {
return getAll().size();
}
@Override
public String toString() {
return name + "_" + System.identityHashCode(this); //$NON-NLS-1$
}
public Integer getNbC_2_5() {
if (nbC_2_5 == null) return 0;
return nbC_2_5;
}
public void setNbC_2_5(Integer nbC_2_5) {
this.nbC_2_5 = nbC_2_5;
}
public Integer getNbS_0_5() {
if (nbS_0_5 == null) return 0;
return nbS_0_5;
}
public void setNbS_0_5(Integer nbS_0_5) {
this.nbS_0_5 = nbS_0_5;
}
public Integer getNbS_1() {
if (nbS_1 == null) return 0;
return nbS_1;
}
public void setNbS_1(Integer nbS_1) {
this.nbS_1 = nbS_1;
}
public Integer getNbS_1_5() {
if (nbS_1_5 == null) return 0;
return nbS_1_5;
}
public void setNbS_1_5(Integer nbS_1_5) {
this.nbS_1_5 = nbS_1_5;
}
public Integer getNbS_2() {
if (nbS_2 == null) return 0;
return nbS_2;
}
public void setNbS_2(Integer nbS_2) {
this.nbS_2 = nbS_2;
}
public Integer getNbS_2_5() {
if (nbS_2_5 == null) return 0;
return nbS_2_5;
}
public void setNbS_2_5(Integer nbS_2_5) {
this.nbS_2_5 = nbS_2_5;
}
public Integer getNbS_5() {
if (nbS_5 == null) return 0;
return nbS_5;
}
public void setNbS_5(Integer nbS_5) {
this.nbS_5 = nbS_5;
}
public Integer getNbL_2_5() {
if (nbL_2_5 == null) return 0;
return nbL_2_5;
}
public void setNbL_2_5(Integer nbL_2_5) {
this.nbL_2_5 = nbL_2_5;
}
public Integer getNbL_5() {
if (nbL_5 == null) return 0;
return nbL_5;
}
public void setNbL_5(Integer nbL_5) {
this.nbL_5 = nbL_5;
}
public Integer getNbL_10() {
if (nbL_10 == null) return 0;
return nbL_10;
}
public void setNbL_10(Integer nbL_10) {
this.nbL_10 = nbL_10;
}
public Integer getNbL_15() {
if (nbL_15 == null) return 0;
return nbL_15;
}
public void setNbL_15(Integer nbL_15) {
this.nbL_15 = nbL_15;
}
public Integer getNbL_20() {
if (nbL_20 == null) return 0;
return nbL_20;
}
public void setNbL_20(Integer nbL_20) {
this.nbL_20 = nbL_20;
}
public Integer getNbL_25() {
if (nbL_25 == null) return 0;
return nbL_25;
}
public void setNbL_25(Integer nbL_25) {
this.nbL_25 = nbL_25;
}
public Integer getOfficialBar() {
if (lightBar == null) return 0;
return officialBar;
}
public void setOfficialBar(Integer officialBar) {
this.officialBar = officialBar;
}
public Integer getLightBar() {
if (lightBar == null) return 0;
return lightBar;
}
public void setLightBar(Integer lightBar) {
this.lightBar = lightBar;
}
public Boolean getShowDecisionLights() {
return showDecisionLights == null ? false : showDecisionLights;
}
public void setShowDecisionLights(Boolean showDecisionLights) {
this.showDecisionLights = showDecisionLights;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Platform other = (Platform) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Mixer getMixer() {
return mixer;
}
public void setMixer(Mixer mixer) {
this.mixer = mixer;
}
/**
* @return the mixerName
*/
public String getMixerName() {
return mixerName;
}
/**
* @param mixerName the mixerName to set
*/
public void setMixerName(String mixerName) {
this.mixerName = mixerName;
setMixer(null);
List<Mixer> mixers = Speakers.getOutputs();
for (Mixer curMixer: mixers) {
if (curMixer.getMixerInfo().getName().equals(mixerName)) {
setMixer(curMixer);
logger.debug("Platform: {}: changing mixer to {}",this.name,mixerName);
break;
}
}
}
public NECDisplay getNECDisplay() {
if (hasDisplay) {
NECDisplay necDisplay = WebApplicationConfiguration.necDisplay;
return necDisplay;
} else {
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.data;
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Entity
public class Competition implements Serializable {
private static final long serialVersionUID = -2817516132425565754L;
@SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(Competition.class);
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String competitionName;
String competitionSite;
Date competitionDate;
String competitionCity;
String competitionOrganizer;
String resultTemplateFileName;
Integer invitedIfBornBefore;
Boolean masters;
String federation;
String federationAddress;
String federationWebSite;
String federationEMail;
public String getCompetitionName() {
return competitionName;
}
public void setCompetitionName(String competitionName) {
this.competitionName = competitionName;
}
public String getCompetitionSite() {
return competitionSite;
}
public void setCompetitionSite(String competitionSite) {
this.competitionSite = competitionSite;
}
public Date getCompetitionDate() {
return competitionDate;
}
public void setCompetitionDate(Date competitionDate) {
this.competitionDate = competitionDate;
}
public String getCompetitionCity() {
return competitionCity;
}
public void setCompetitionCity(String competitionCity) {
this.competitionCity = competitionCity;
}
public Boolean getMasters() {
return masters;
}
public void setMasters(Boolean masters) {
this.masters = masters;
}
public String getFederation() {
return federation;
}
public void setFederation(String federation) {
this.federation = federation;
}
public String getFederationAddress() {
return federationAddress;
}
public void setFederationAddress(String federationAddress) {
this.federationAddress = federationAddress;
}
public String getFederationWebSite() {
return federationWebSite;
}
public void setFederationWebSite(String federationWebSite) {
this.federationWebSite = federationWebSite;
}
public String getFederationEMail() {
return federationEMail;
}
public void setFederationEMail(String federationEMail) {
this.federationEMail = federationEMail;
}
public Long getId() {
return id;
}
public Integer getInvitedIfBornBefore() {
if (invitedIfBornBefore == null) return 0;
return invitedIfBornBefore;
}
public void setInvitedIfBornBefore(Integer invitedIfBornBefore) {
this.invitedIfBornBefore = invitedIfBornBefore;
}
public String getCompetitionOrganizer() {
return competitionOrganizer;
}
public void setCompetitionOrganizer(String competitionOrganizer) {
this.competitionOrganizer = competitionOrganizer;
}
public String getResultTemplateFileName() {
//logger.debug("getResultTemplateFileName {}",resultTemplateFileName);
if (resultTemplateFileName != null && new File(resultTemplateFileName).exists()) {
return resultTemplateFileName;
} else {
return CompetitionApplication.getCurrent().getContext().getBaseDirectory()
+ "/WEB-INF/classes/templates/competitionBook/CompetitionBook_Total_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
//+ "/WEB-INF/classes/templates/team/TeamResultSheetTemplate.xls";
}
}
public void setResultTemplateFileName(String resultTemplateFileName) {
this.resultTemplateFileName = resultTemplateFileName;
}
static Integer invitedThreshold = null;
@SuppressWarnings("unchecked")
public static int invitedIfBornBefore() {
if (invitedThreshold != null) return invitedThreshold;
final CompetitionApplication currentApp = CompetitionApplication.getCurrent();
final Session hbnSession = currentApp.getHbnSession();
List<Competition> competitions = hbnSession.createCriteria(Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
invitedThreshold = competition.getInvitedIfBornBefore();
}
if (invitedThreshold == null) return 0;
return invitedThreshold;
}
@SuppressWarnings("unchecked")
static public List<Competition> getAll() {
final List<Competition> list = CompetitionApplication.getCurrent().getHbnSession().createCriteria(Competition.class).list();
return list;
}
static Boolean isMasters = null;
@SuppressWarnings("unchecked")
public static boolean isMasters() {
if (isMasters != null) return isMasters;
final CompetitionApplication currentApp = CompetitionApplication.getCurrent();
final Session hbnSession = currentApp.getHbnSession();
List<Competition> competitions = hbnSession.createCriteria(Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
isMasters = competition.getMasters();
}
if (isMasters == null) return false; // junit database does not have
// this attribute set.
return isMasters;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((competitionName == null) ? 0 : competitionName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Competition other = (Competition) obj;
if (competitionName == null) {
if (other.competitionName != null)
return false;
} else if (!competitionName.equals(other.competitionName))
return false;
return true;
}
}
| 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.timer;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
public interface CountdownTimerListener {
void finalWarning(int timeRemaining);
void initialWarning(int timeRemaining);
void noTimeLeft(int timeRemaining);
void normalTick(int timeRemaining);
/**
* timer has been stopped, lifter is still associated with timer.
*
* @param timeRemaining
* @param reason
* @param competitionApplication
*/
void pause(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason);
void start(int timeRemaining);
/**
* timer has been stopped and associated lifter has been cleared.
*
* @param timeRemaining
*/
void stop(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason);
/**
* someone is forcing the amount of time.
*
* @param startTime
*/
void forceTimeRemaining(int startTime, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason);
}
| 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.timer;
import java.io.Serializable;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runnable task for counting down. run() is invoked every "decrement"
* milliseconds. For convenience we count down in milliseconds.
*
*/
class CountdownTask extends TimerTask implements Serializable {
private static final long serialVersionUID = -2967275874759395049L;
final private static Logger logger = LoggerFactory.getLogger(CountdownTask.class);
private final CountdownTimer countdownTimer;
int ticks;
long startMillis = System.currentTimeMillis();
private int startTime;
private int decrement; // milliseconds
private boolean firstWarningSignaled = false;
private boolean finalWarningSignaled = false;
private boolean noTimeLeftSignaled = false;
private int finalWarningTick;
private int firstWarningTick;
private int noTimeLeftTicks;
final static int firstWarning = 90; // seconds
final static int lastWarning = 30; // seconds
CountdownTask(CountdownTimer countdownTimer, int countdownFrom, int decrement) {
this.countdownTimer = countdownTimer;
this.startTime = countdownFrom;
// round up to decrement interval (100ms)
this.ticks = roundUpCountdown(countdownFrom, decrement);
this.decrement = decrement;
this.firstWarningTick = firstWarning * 1000;
this.finalWarningTick = lastWarning * 1000;
this.noTimeLeftTicks = 0;
int adjustedCountdown = countdownFrom;
if (adjustedCountdown < firstWarningTick) {
logger.debug("already beyond first: {} <= {}", adjustedCountdown, firstWarningTick);
setFirstWarningSignaled(true);
}
if (adjustedCountdown < finalWarningTick) {
logger.debug("already beyond last: {} <= {}", adjustedCountdown, finalWarningTick);
setFinalWarningSignaled(true);
}
if (adjustedCountdown < noTimeLeftTicks) {
logger.debug("already signaled no time left: {} <= {}", adjustedCountdown, noTimeLeftTicks);
setNoTimeLeftSignaled(true);
}
}
/**
* Round up to decrement interval (100ms)
* @param countdownFrom
* @param decrement1
* @return
*/
private int roundUpCountdown(int countdownFrom, int decrement1) {
if (countdownFrom <= 0) {
return 0;
} else if (countdownFrom % decrement1 == 0) {
return countdownFrom;
} else {
return ((countdownFrom / decrement1) * decrement1) + decrement1;
}
}
/**
* @return best available estimation of the time elapsed.
*/
long getBestTimeRemaining() {
return startTime - (System.currentTimeMillis() - startMillis);
}
/**
* @return time elapsed, empirically less than 15ms late
*/
public int getTimeRemaining() {
return ticks;
}
@Override
public void run() {
if (ticks <= firstWarningTick && !getFirstWarningSignaled()) {
initialWarning();
setFirstWarningSignaled(true);
} else if (ticks <= finalWarningTick && !getFinalWarningSignaled()) {
finalWarning();
setFinalWarningSignaled(true);
} else if (ticks <= noTimeLeftTicks && !getNoTimeLeftSignaled()) {
noTimeLeft();
setNoTimeLeftSignaled(true); // buzzer has already sounded.
} else if (ticks >= 0) {
normalTick();
}
// leave the timer running for one second extra
// Under linux, cancelling the timer also cancel the sounds
if (ticks <= -1000) {
logger.info("end: " + ticks / 1000 + " " + (System.currentTimeMillis() - startMillis)); //$NON-NLS-1$ //$NON-NLS-2$
this.countdownTimer.cancel();
} else {
ticks = ticks - decrement;
}
}
private void normalTick() {
logger.trace("normalTick: " + ticks / 1000 + " " + (System.currentTimeMillis() - startMillis)); //$NON-NLS-1$ //$NON-NLS-2$
final CountdownTimerListener countdownDisplay = countdownTimer.getCountdownDisplay();
final CountdownTimerListener masterBuzzer = countdownTimer.getMasterBuzzer();
if (countdownDisplay != null) {
countdownDisplay.normalTick((int) getBestTimeRemaining());
}
if (masterBuzzer != null) {
masterBuzzer.normalTick((int) getBestTimeRemaining());
}
for (CountdownTimerListener curListener : countdownTimer.getListeners()) {
curListener.normalTick((int) getBestTimeRemaining());
}
}
private void initialWarning() {
logger.info("initial warning: " + ticks / 1000 + " " + (System.currentTimeMillis() - startMillis)); //$NON-NLS-1$ //$NON-NLS-2$
final CountdownTimerListener countdownDisplay = countdownTimer.getCountdownDisplay();
final CountdownTimerListener masterBuzzer = countdownTimer.getMasterBuzzer();
if (countdownDisplay != null) {
countdownDisplay.initialWarning((int) getBestTimeRemaining());
}
if (masterBuzzer != null) {
masterBuzzer.initialWarning((int) getBestTimeRemaining());
}
for (CountdownTimerListener curListener : countdownTimer.getListeners()) {
curListener.initialWarning((int) getBestTimeRemaining());
}
}
private void finalWarning() {
logger.info("final warning: " + ticks / 1000 + " " + (System.currentTimeMillis() - startMillis)); //$NON-NLS-1$ //$NON-NLS-2$
final CountdownTimerListener countdownDisplay = countdownTimer.getCountdownDisplay();
final CountdownTimerListener masterBuzzer = countdownTimer.getMasterBuzzer();
if (countdownDisplay != null) {
countdownDisplay.finalWarning((int) getBestTimeRemaining());
}
if (masterBuzzer != null) {
masterBuzzer.finalWarning((int) getBestTimeRemaining());
}
for (CountdownTimerListener curListener : countdownTimer.getListeners()) {
curListener.finalWarning((int) getBestTimeRemaining());
}
}
private void noTimeLeft() {
logger.info("time over: " + ticks / 1000 + " " + (System.currentTimeMillis() - startMillis)); //$NON-NLS-1$ //$NON-NLS-2$
final CountdownTimerListener countdownDisplay = countdownTimer.getCountdownDisplay();
final CountdownTimerListener masterBuzzer = countdownTimer.getMasterBuzzer();
if (countdownDisplay != null) {
countdownDisplay.noTimeLeft((int) getBestTimeRemaining());
}
if (masterBuzzer != null) {
masterBuzzer.noTimeLeft((int) getBestTimeRemaining());
}
for (CountdownTimerListener curListener : countdownTimer.getListeners()) {
curListener.noTimeLeft((int) getBestTimeRemaining());
}
}
/**
* @param firstWarningSignaled
* the firstWarningSignaled to set
*/
private void setFirstWarningSignaled(boolean firstWarningSignaled) {
this.firstWarningSignaled = firstWarningSignaled;
}
/**
* @return the firstWarningSignaled
*/
private boolean getFirstWarningSignaled() {
return firstWarningSignaled;
}
/**
* @param finalWarningSignaled
* the finalWarningSignaled to set
*/
private void setFinalWarningSignaled(boolean finalWarningSignaled) {
// logger.debug("setting finalWarningSignaled={}",finalWarningSignaled);
// LoggerUtils.logException(logger,new Exception("wtf"));
this.finalWarningSignaled = finalWarningSignaled;
}
/**
* @return the finalWarningSignaled
*/
private boolean getFinalWarningSignaled() {
return finalWarningSignaled;
}
/**
* @param noTimeLeftSignaled
* the noTimeLeftSignaled to set
*/
private void setNoTimeLeftSignaled(boolean noTimeLeftSignaled) {
this.noTimeLeftSignaled = noTimeLeftSignaled;
}
/**
* @return the noTimeLeftSignaled
*/
private boolean getNoTimeLeftSignaled() {
return noTimeLeftSignaled;
}
}
| 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.timer;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.LifterInfo;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.Application;
import com.vaadin.ui.AbstractComponent;
/**
* Master stopwatch for a competition session.
*
* @author jflamy
*
*/
public class CountdownTimer implements Serializable {
private static final long serialVersionUID = 8921641103581546472L;
final static Logger logger = LoggerFactory.getLogger(CountdownTimer.class);
private boolean platformFree;
private Lifter owner = null;
final private static int DECREMENT = 100; // milliseconds
private int timeRemaining;
private Timer timer = null;
private CountdownTask countdownTask;
/*
* listeners : the display for the lifter and the buzzer controller are
* treated specially as they require immediate attention.
* then all other listeners are treated in whatever order.
*/
private Set<CountdownTimerListener> listeners = new HashSet<CountdownTimerListener>();
private CountdownTimerListener countdownDisplay = null;
/**
* Buzzer is controlled by LifterInfo on announcer console
* (legacy design -- buzzer used to be on client side)
*/
private LifterInfo masterBuzzer = null;
public CountdownTimer() {
logger.debug("new {}",this); //$NON-NLS-1$
}
/**
* Start the timer.
*/
public void start() {
logger.debug("enter start {} {}", this, getTimeRemaining()); //$NON-NLS-1$
if (timer != null) {
timer.cancel();
}
if (countdownTask != null) {
countdownTask.cancel();
}
if (owner == null) return;
if (timeRemaining <= 0) {
setTimeRemaining(0);
return;
}
timer = new Timer();
countdownTask = new CountdownTask(this, timeRemaining, DECREMENT);
timer.scheduleAtFixedRate(countdownTask,
0, // start right away
DECREMENT); // 100ms precision is good enough
final Set<CountdownTimerListener> listeners2 = getListeners();
logger.trace("start: {} - {} listeners", timeRemaining, listeners2.size()); //$NON-NLS-1$
if (countdownDisplay != null) {
countdownDisplay.start(timeRemaining);
}
if (masterBuzzer != null) {
masterBuzzer.start(timeRemaining);
}
for (CountdownTimerListener curListener : listeners2) {
// avoid duplicate notifications
if (curListener != masterBuzzer && curListener != countdownDisplay) {
curListener.start(timeRemaining);
}
}
}
/**
* Start the timer.
*/
public void restart() {
logger.debug("enter restart {} {}", getTimeRemaining()); //$NON-NLS-1$
start();
}
/**
* Stop the timer, without clearing the associated lifter.
*/
public void pause() {
pause(TimeStoppedNotificationReason.UNKNOWN);
}
@SuppressWarnings("unchecked")
public void pause(TimeStoppedNotificationReason reason) {
logger.debug("enter pause {} {}", getTimeRemaining()); //$NON-NLS-1$
if (countdownTask != null) {
setTimeRemaining((int) countdownTask.getBestTimeRemaining());
}
if (timer != null) {
timer.cancel();
}
timer = null;
if (countdownTask != null) {
countdownTask.cancel();
countdownTask = null;
}
logger.info("pause: {}", timeRemaining); //$NON-NLS-1$
if (countdownDisplay != null) {
countdownDisplay.pause(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
if (masterBuzzer != null) {
masterBuzzer.pause(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
final HashSet<CountdownTimerListener> listenerSet = (HashSet<CountdownTimerListener>) getListeners();
for (CountdownTimerListener curListener : (HashSet<CountdownTimerListener>)listenerSet.clone()) {
// avoid duplicate notifications
if (curListener != masterBuzzer && curListener != countdownDisplay) {
// avoid notifying orphaned listeners
if (curListener instanceof AbstractComponent) {
AbstractComponent curComponent = (AbstractComponent)curListener;
Application curApp = curComponent.getApplication();
if (curApp == null) {
// application is null, the listener is an orphan
listenerSet.remove(curListener);
} else {
curListener.pause(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
} else {
curListener.pause(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
}
}
}
/**
* Stop the timer, clear the associated lifter.
*/
public void stop() {
stop(TimeStoppedNotificationReason.UNKNOWN);
}
public void stop(TimeStoppedNotificationReason reason) {
logger.debug("enter stop {} {}", getTimeRemaining()); //$NON-NLS-1$
if (timer != null) timer.cancel();
timer = null;
if (countdownTask != null) {
countdownTask.cancel();
setTimeRemaining((int) countdownTask.getBestTimeRemaining());
}
setOwner(null);
logger.info("stop: {}", timeRemaining); //$NON-NLS-1$
if (countdownDisplay != null) {
countdownDisplay.stop(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
if (masterBuzzer != null) {
masterBuzzer.stop(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
for (CountdownTimerListener curListener : getListeners()) {
// avoid duplicate notifications
if (curListener != masterBuzzer && curListener != countdownDisplay) {
if (curListener instanceof AbstractComponent) {
final Application application = ((AbstractComponent) curListener).getApplication();
if (application != null) {
curListener.stop(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
} else {
curListener.stop(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
}
}
}
/**
* Set the remaining time explicitly. Meant to be called only by SessionData()
* so that the time is reset correctly.
*/
public void forceTimeRemaining(int remainingTime) {
forceTimeRemaining(remainingTime, TimeStoppedNotificationReason.UNKNOWN);
}
public void forceTimeRemaining(int remainingTime,TimeStoppedNotificationReason reason) {
if (timer != null) timer.cancel();
timer = null;
if (countdownTask != null) {
countdownTask.cancel();
countdownTask = null;
}
setTimeRemaining(remainingTime);
logger.info("forceTimeRemaining: {}", getTimeRemaining()); //$NON-NLS-1$
if (countdownDisplay != null) {
countdownDisplay.forceTimeRemaining(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
if (masterBuzzer != null) {
masterBuzzer.forceTimeRemaining(timeRemaining, CompetitionApplication.getCurrent(), reason);
}
for (CountdownTimerListener curListener : getListeners()) {
// avoid duplicate notifications
if (curListener != masterBuzzer && curListener != countdownDisplay) {
if (curListener instanceof AbstractComponent) {
final Application application = ((AbstractComponent) curListener).getApplication();
if (application != null) {
curListener.forceTimeRemaining(getTimeRemaining(), CompetitionApplication.getCurrent(), reason);
}
} else {
curListener.forceTimeRemaining(getTimeRemaining(), CompetitionApplication.getCurrent(), reason);
}
}
}
}
/**
* @return true if the timer is actually counting down.
*/
public boolean isRunning() {
return timer != null;
}
/**
* Set the time remaining for the next start.
*
* @param i
*/
public void setTimeRemaining(int i) {
logger.debug("setTimeRemaining {}" + i);
this.timeRemaining = i;
}
// private void logException(Logger logger2, Exception exception) {
// StringWriter sw = new StringWriter();
// exception.printStackTrace(new PrintWriter(sw));
// logger.info(sw.toString());
// }
public int getTimeRemaining() {
return timeRemaining;
}
/**
* Associate the timer with a lifter Set to null to indicate that the time
* on the timer belongs to no-one in particular.
*
* @param lifter
*/
public void setOwner(Lifter lifter) {
// logger.debug("setLifterAnnounced(): {}",lifter);
// logException(logger,new Exception());
this.owner = lifter;
}
public Lifter getOwner() {
return owner;
}
public void setPlatformFree(boolean platformFree) {
this.platformFree = platformFree;
}
public boolean isPlatformFree() {
return platformFree;
}
public void addListener(CountdownTimerListener timerListener) {
logger.debug("{} listened by {}", this, timerListener); //$NON-NLS-1$
listeners.add(timerListener);
}
public void removeAllListeners() {
listeners.clear();
}
public void removeListener(CountdownTimerListener timerListener) {
listeners.remove(timerListener);
}
public Set<CountdownTimerListener> getListeners() {
return listeners;
}
/**
* @param countdownDisplay
* the countdownDisplay to set
*/
public void setCountdownDisplay(CountdownTimerListener countdownDisplay) {
logger.info("countdownDisplay={}", countdownDisplay);
this.countdownDisplay = countdownDisplay;
}
/**
* @return the countdownDisplay
*/
public CountdownTimerListener getCountdownDisplay() {
return countdownDisplay;
}
/**
* @param lifterInfo
*/
public void setMasterBuzzer(LifterInfo lifterInfo) {
this.masterBuzzer = lifterInfo;
}
/**
* @return the masterBuzzer
*/
public LifterInfo getMasterBuzzer() {
return masterBuzzer;
}
@Test
public void doCountdownTest() {
try {
setTimeRemaining(4000);
final Lifter testLifter = new Lifter();
setOwner(testLifter);
start();
long now = System.currentTimeMillis();
System.out
.println("after scheduling: " + countdownTask.getTimeRemaining() + " " + (System.currentTimeMillis() - now)); //$NON-NLS-1$ //$NON-NLS-2$
Thread.sleep(1000);
pause();
System.out
.println("pause after 1000: " + countdownTask.getTimeRemaining() + " " + (System.currentTimeMillis() - now)); //$NON-NLS-1$ //$NON-NLS-2$
Thread.sleep(1000);
System.out
.println("restart after 2000: " + countdownTask.getTimeRemaining() + " " + (System.currentTimeMillis() - now)); //$NON-NLS-1$ //$NON-NLS-2$
setOwner(testLifter);
restart();
Thread.sleep(3000);
} catch (InterruptedException t) {
logger.error(t.getMessage());
}
}
public void cancel() {
logger.debug("cancelling timer");
this.timer.cancel();
}
}
| 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.decision;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.mobile.IRefereeConsole;
import org.concordiainternational.competition.timer.CountdownTimerListener;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
import org.concordiainternational.competition.utils.EventHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.EventRouter;
/**
* Registers decisions from referees and notifies interested UI Components
*
* @author jflamy
*/
public class JuryDecisionController implements IDecisionController, CountdownTimerListener {
private static final int RESET_DELAY = 5000;
/**
* 3 seconds to change decision (after all refs have selected)
*/
private static final int DECISION_REVERSAL_DELAY = 4000;
/**
* Time before displaying decision once all referees have pressed.
*/
//private static final int DECISION_DISPLAY_DELAY = 1000;
Logger logger = LoggerFactory.getLogger(JuryDecisionController.class);
Decision[] juryDecisions = new Decision[3];
DecisionEventListener[] listeners = new DecisionEventListener[3];
public JuryDecisionController(SessionData groupData) {
for (int i = 0; i < juryDecisions.length; i++) {
juryDecisions[i] = new Decision();
}
}
long allDecisionsMadeTime = 0L; // all 3 referees have pressed
int decisionsMade = 0;
private EventRouter eventRouter;
@SuppressWarnings("unused")
private boolean blocked = true;
/**
* Enable jury devices.
*/
@Override
public void reset() {
for (int i = 0; i < juryDecisions.length; i++) {
juryDecisions[i].accepted = null;
juryDecisions[i].time = 0L;
}
allDecisionsMadeTime = 0L; // all 3 referees have pressed
decisionsMade = 0;
fireEvent(new DecisionEvent(this, DecisionEvent.Type.RESET, System.currentTimeMillis(), juryDecisions));
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#decisionMade(int, boolean)
*/
@Override
public synchronized void decisionMade(int refereeNo, boolean accepted) {
if (isBlocked()) return;
final long currentTimeMillis = System.currentTimeMillis();
long deltaTime = currentTimeMillis - allDecisionsMadeTime;
if (decisionsMade == 3 && deltaTime > DECISION_REVERSAL_DELAY) {
// too late to reverse decision
logger.info("decision ignored from jury {}: {} (too late by {} ms)", new Object[] { refereeNo + 1,
(accepted ? "lift" : "no lift"), deltaTime - DECISION_REVERSAL_DELAY });
return;
}
juryDecisions[refereeNo].accepted = accepted;
juryDecisions[refereeNo].time = currentTimeMillis;
logger.info("decision by jury {}: {}", refereeNo + 1, (accepted ? "lift" : "no lift"));
decisionsMade = 0;
for (int i = 0; i < juryDecisions.length; i++) {
final Boolean accepted2 = juryDecisions[i].accepted;
if (accepted2 != null) {
decisionsMade++;
}
}
if (decisionsMade == 2) {
fireEvent(new DecisionEvent(this, DecisionEvent.Type.WAITING, currentTimeMillis, juryDecisions));
} else if (decisionsMade == 3) {
// broadcast the decision
if (allDecisionsMadeTime == 0L) {
// all 3 referees have just made a choice; schedule the display
// in 3 seconds
allDecisionsMadeTime = System.currentTimeMillis();
scheduleDisplay(currentTimeMillis);
scheduleBlock();
scheduleReset();
}
// referees have changed their mind
fireEvent(new DecisionEvent(this, DecisionEvent.Type.UPDATE, currentTimeMillis, juryDecisions));
}
}
/**
* @param currentTimeMillis
* @param goodLift
*/
private void scheduleDisplay(final long currentTimeMillis) {
// display right away
fireEvent(new DecisionEvent(JuryDecisionController.this, DecisionEvent.Type.SHOW, currentTimeMillis,
juryDecisions));
// Timer timer = new Timer();
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// fireEvent(new DecisionEvent(JuryDecisionController.this, DecisionEvent.Type.SHOW, currentTimeMillis,
// juryDecisions));
// }
// }, DECISION_DISPLAY_DELAY);
}
/**
*
*/
private void scheduleBlock() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fireEvent(new DecisionEvent(JuryDecisionController.this, DecisionEvent.Type.BLOCK, System.currentTimeMillis(), juryDecisions));
setBlocked(true);
}
}, DECISION_REVERSAL_DELAY);
}
/**
*
*/
private void scheduleReset() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
reset();
}
}, DECISION_REVERSAL_DELAY + RESET_DELAY);
}
/**
* 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 DECISION_EVENT_METHOD = EventHelper.findMethod(DecisionEvent.class,
// when receiving this type of event
DecisionEventListener.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(DecisionEvent 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
*/
@Override
public void addListener(DecisionEventListener listener) {
logger.debug("add listener {}", listener); //$NON-NLS-1$
getEventRouter().addListener(DecisionEvent.class, listener, DECISION_EVENT_METHOD);
}
/**
* Remove a specific SessionData.Listener object
*
* @param listener
*/
@Override
public void removeListener(DecisionEventListener listener) {
if (eventRouter != null) {
logger.debug("hide listener {}", listener); //$NON-NLS-1$
eventRouter.removeListener(DecisionEvent.class, listener, DECISION_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.
*/
/**
* @return the object's event router.
*/
private EventRouter getEventRouter() {
if (eventRouter == null) {
eventRouter = new EventRouter();
logger.trace("new event router for JuryDecisionController " + System.identityHashCode(this) + " = " + System.identityHashCode(eventRouter)); //$NON-NLS-1$ //$NON-NLS-2$
}
return eventRouter;
}
// timer events
@Override
public void finalWarning(int timeRemaining) {
}
@Override
public void forceTimeRemaining(int startTime, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
@Override
public void initialWarning(int timeRemaining) {
}
@Override
public void noTimeLeft(int timeRemaining) {
}
@Override
public void normalTick(int timeRemaining) {
}
@Override
public void pause(int timeRemaining, CompetitionApplication app, TimeStoppedNotificationReason reason) {
}
@Override
public void start(int timeRemaining) {
}
@Override
public void stop(int timeRemaining, CompetitionApplication app, TimeStoppedNotificationReason reason) {
}
@Override
public void addListener(IRefereeConsole refereeConsole, int refereeIndex) {
if (listeners[refereeIndex] != null) {
logger.trace("removing previous JuryConsole listener {}",listeners[refereeIndex]);
removeListener(listeners[refereeIndex]);
}
addListener(refereeConsole);
listeners[refereeIndex] = refereeConsole;
logger.trace("adding new JuryConsole listener {}",listeners[refereeIndex]);
}
@Override
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
@Override
public boolean isBlocked() {
//return blocked && (groupData.getCurrentSession() != null);
return false; // does not matter for jury
}
@Override
public Lifter getLifter() {
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.decision;
import org.concordiainternational.competition.ui.SessionData;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RefereeDecisionTester implements DecisionEventListener {
private Logger logger = LoggerFactory.getLogger(RefereeDecisionTester.class);
@Override
public void updateEvent(DecisionEvent updateEvent) {
logger.info(updateEvent.toString());
}
@Test
public void runTest() {
IDecisionController decisionController = new RefereeDecisionController(new SessionData(null));
decisionController.addListener(this);
decisionController.reset();
try {
decisionController.decisionMade(0, true);
decisionController.decisionMade(1, true);
decisionController.decisionMade(2, true);
Thread.sleep(1001);
decisionController.decisionMade(2, false);
Thread.sleep(2100);
decisionController.decisionMade(1, false);
} catch (InterruptedException e) {
}
}
}
| 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.decision;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.mobile.IRefereeConsole;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
public interface IDecisionController {
/**
* Need to block decisions if a session is underway, unblocking when lifter is announced
* or time has started.
*/
public abstract boolean isBlocked();
public void setBlocked(boolean blocked);
public abstract void reset();
/**
* Record a decision made by the officials, broacasting to the listeners.
* @param refereeNo
* @param accepted
*/
public abstract void decisionMade(int refereeNo, boolean accepted);
/**
* Register a new SessionData.Listener object with a SessionData in order to be
* informed of updates.
*
* @param listener
*/
public abstract void addListener(DecisionEventListener listener);
/**
* Remove a specific SessionData.Listener object
*
* @param listener
*/
public abstract void removeListener(DecisionEventListener listener);
// timer events
public abstract void finalWarning(int timeRemaining);
public abstract void forceTimeRemaining(int startTime,
CompetitionApplication originatingApp,
TimeStoppedNotificationReason reason);
public abstract void initialWarning(int timeRemaining);
public abstract void noTimeLeft(int timeRemaining);
public abstract void normalTick(int timeRemaining);
public abstract void pause(int timeRemaining, CompetitionApplication app,
TimeStoppedNotificationReason reason);
public abstract void start(int timeRemaining);
public abstract void stop(int timeRemaining, CompetitionApplication app,
TimeStoppedNotificationReason reason);
public abstract void addListener(IRefereeConsole refereeConsole,
int refereeIndex);
public abstract Lifter getLifter();
}
| 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.decision;
import java.util.EventObject;
import org.concordiainternational.competition.data.Lifter;
public class DecisionEvent extends EventObject {
private static final long serialVersionUID = 2789988074894824591L;
public enum Type {
DOWN, // two refs have given the same decision, lifter can put weight
// down
WAITING, // two refs have given different decisions, waiting for third
UPDATE, // any change during 3 second period where refs can change their decision
SHOW, // all referees have given decisions, public sees decision
BLOCK, // cannot change decision after 3 seconds
RESET, // after 5 seconds, or if announced
}
private Type type;
private long when;
private Decision[] decisions;
private Lifter lifter;
private Integer attempt;
private Boolean accepted;
public DecisionEvent(IDecisionController source, Type down, long currentTimeMillis, Decision[] refereeDecisions) {
super(source);
this.type = down;
this.when = currentTimeMillis;
this.decisions = refereeDecisions;
this.lifter = source.getLifter();
if (lifter != null) {
this.setAttempt(lifter.getAttemptsDone());
}
this.setAccepted(computeAccepted());
}
@Override
public String toString() {
switch (this.type) {
case DOWN:
return type + " " + when;
case RESET:
return "reset";
default:
return type + " " + decisions[0].accepted + " " + decisions[1].accepted + " " + decisions[2].accepted;
}
}
public Type getType() {
return type;
}
public Decision[] getDecisions() {
return decisions;
}
public boolean isDisplayable() {
int count = 0;
for (Decision decision : decisions){
if (decision.accepted != null) count++;
}
return count == 3;
}
/**
* Return true for a good lift, false for a rejected lift, null if decisions are pending.
* @return null if no decision yet, true if 3 decisions and at least 2 good, false otherwise
*/
public Boolean computeAccepted() {
int count = 0;
int countAccepted = 0;
for (Decision decision : decisions){
final Boolean accepted1 = decision.accepted;
if (accepted1 != null) {
count++;
if (accepted1) countAccepted++;
}
}
if (count < 3) {
return null;
} else {
return countAccepted >= 2;
}
}
public Lifter getLifter() {
return lifter;
}
public void setAttempt(Integer attempt) {
this.attempt = attempt;
}
public Integer getAttempt() {
return attempt;
}
public void setAccepted(Boolean accepted) {
this.accepted = accepted;
}
public Boolean isAccepted() {
return accepted;
}
}
| 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.decision;
public class Decision {
public Boolean accepted = null;
Long time;
}
| 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.decision;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
public class Tone {
private byte[] buf;
private AudioFormat af;
private SourceDataLine sdl;
Tone(Mixer mixer, int hz, int msecs, double vol) throws IllegalArgumentException {
if (mixer == null) return;
init(hz, msecs, vol, mixer);
}
/**
* @param hz
* @param msecs
* @param vol
* @param mixer
*/
protected void init(int hz, int msecs, double vol, Mixer mixer) {
if (vol > 1.0 || vol < 0.0)
throw new IllegalArgumentException("Volume out of range 0.0 - 1.0");
buf = new byte[msecs * 8];
for (int i=0; i<buf.length; i++) {
double angle = i / (8000.0 / hz) * 2.0 * Math.PI;
buf[i] = (byte)(Math.sin(angle) * 127.0 * vol);
}
// shape the front and back ends of the wave form
for (int i=0; i<20 && i < buf.length / 2; i++) {
buf[i] = (byte)(buf[i] * i / 20);
buf[buf.length - 1 - i] = (byte)(buf[buf.length - 1 - i] *
i / 20);
}
af = new AudioFormat(8000f,8,1,true,false);
try {
sdl = AudioSystem.getSourceDataLine(af,mixer.getMixerInfo());
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
}
}
/**
* @param buf
* @param af
* @param sdl
* @throws LineUnavailableException
*/
public void emit() {
if (sdl == null) return;
try {
sdl.open(af);
sdl.start();
sdl.write(buf,0,buf.length);
sdl.drain();
sdl.close();
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
}
}
}
| 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.decision;
/**
* Listener interface for receiving <code>SessionData.DecisionEvent</code>s.
*/
public interface DecisionEventListener extends java.util.EventListener {
/**
* This method will be invoked when a SessionData.DecisionEvent is fired.
*
* @param updateEvent
* the event that has occured.
*/
public void updateEvent(DecisionEvent updateEvent);
}
| 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.decision;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.Mixer;
/**
* Play a sampled sound.
* Requires an uncompressed format (WAV), not a compressed (MP3) format.
*
* @author jflamy
*/
public class Sound {
Mixer mixer;
private InputStream resource;
public Sound(Mixer mixer, String soundRelativeURL) throws IllegalArgumentException {
this.mixer = mixer;
this.resource = Sound.class.getResourceAsStream(soundRelativeURL);
}
public synchronized void emit() {
try {
if (mixer == null) return;
final AudioInputStream inputStream = AudioSystem.getAudioInputStream(resource);
final Clip clip = AudioSystem.getClip(mixer.getMixerInfo());
clip.open(inputStream);
// clip.start() creates a native thread 'behind the scenes'
// unless this is added, it never goes away
// ref: http://stackoverflow.com/questions/837974/determine-when-to-close-a-sound-playing-thread-in-java
clip.addLineListener( new LineListener() {
@Override
public void update(LineEvent evt) {
if (evt.getType() == LineEvent.Type.STOP) {
evt.getLine().close();
}
}
});
clip.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 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.decision;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Speakers {
final static Logger logger = LoggerFactory.getLogger(Speakers.class);
public static void main(String[] args) throws Exception {
List<Mixer> mixers = getOutputs();
for (Mixer mixer: mixers) {
System.out.println(mixer.getMixerInfo().getName());
new Speakers().testSound(mixer);
}
}
/**
* @return
*/
public static List<Mixer> getOutputs() {
List<Mixer> mixers = outputs(AudioSystem.getMixer(null), AudioSystem.getMixerInfo());
return mixers;
}
/**
* @param defaultMixer
* @param infos
*/
protected static List<Mixer> outputs(Mixer defaultMixer, Mixer.Info[] infos) {
List<Mixer> mixers = new ArrayList<Mixer>();
for (Mixer.Info info : infos) {
Mixer mixer = AudioSystem.getMixer(info);
try {
if (! mixer.getMixerInfo().toString().startsWith("Java")) {
AudioFormat af = new AudioFormat(8000f,8,1,true,false);
if (AudioSystem.getSourceDataLine(af,info) != null) {
mixers.add(mixer);
}
}
} catch (IllegalArgumentException e) {
} catch (LineUnavailableException e) {
}
}
return mixers;
}
/**
* @param mixer
*/
public synchronized void testSound(Mixer mixer) {
try {
if (mixer == null) return;
// both sounds should be heard simultaneously
new Sound(mixer,"/sounds/initialWarning2.wav").emit();
new Tone(mixer, 1100, 1200, 1.0).emit();
} catch (Exception e) {
LoggerUtils.logException(logger, e);
throw new RuntimeException(e);
}
}
/**
* @param infos
* @throws LineUnavailableException
*/
protected static void speakers(Mixer.Info[] infos)
throws LineUnavailableException {
for (Mixer.Info info : infos) {
Mixer mixer = AudioSystem.getMixer(info);
if (mixer.isLineSupported(Port.Info.SPEAKER)) {
Port port = (Port) mixer.getLine(Port.Info.SPEAKER);
port.open();
if (port.isControlSupported(FloatControl.Type.VOLUME)) {
FloatControl volume = (FloatControl) port.getControl(FloatControl.Type.VOLUME);
System.out.println(info);
System.out.println("- " + Port.Info.SPEAKER);
System.out.println(" - " + volume);
}
port.close();
}
}
}
public static List<String> getOutputNames() {
ArrayList<String> outputNames = new ArrayList<String>();
for (Mixer mixer: getOutputs()){
outputNames.add(mixer.getMixerInfo().getName());
};
return outputNames;
}
}
| 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.decision;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.mobile.IRefereeConsole;
import org.concordiainternational.competition.timer.CountdownTimerListener;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
import org.concordiainternational.competition.utils.EventHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.EventRouter;
/**
* Registers decisions from referees and notifies interested UI Components
*
* @author jflamy
*/
public class RefereeDecisionController implements CountdownTimerListener, IDecisionController {
private static final int RESET_DELAY = 4000;
/**
* 3 seconds to change decision (after all refs have selected)
*/
private static final int DECISION_REVERSAL_DELAY = 3000;
/**
* Time before displaying decision once all referees have pressed.
*/
private static final int DECISION_DISPLAY_DELAY = 1000;
Logger logger = LoggerFactory.getLogger(RefereeDecisionController.class);
Decision[] refereeDecisions = new Decision[3];
DecisionEventListener[] listeners = new DecisionEventListener[3];
private SessionData groupData;
private Tone downSignal = null;
public RefereeDecisionController(SessionData groupData) {
this.groupData = groupData;
for (int i = 0; i < refereeDecisions.length; i++) {
refereeDecisions[i] = new Decision();
}
final Platform platform = groupData.getPlatform();
try {
if (platform != null) {
downSignal = new Tone(platform.getMixer(), 1100, 1200, 1.0);
}
} catch (Exception e) {
logger.warn("no sound for platform {}",platform.getName());
}
}
long allDecisionsMadeTime = 0L; // all 3 referees have pressed
int decisionsMade = 0;
private EventRouter eventRouter;
private Boolean downSignaled = false;
private boolean blocked = true;
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#reset()
*/
@Override
public void reset() {
for (int i = 0; i < refereeDecisions.length; i++) {
refereeDecisions[i].accepted = null;
refereeDecisions[i].time = 0L;
}
allDecisionsMadeTime = 0L; // all 3 referees have pressed
decisionsMade = 0;
downSignaled = false;
groupData.setAnnouncerEnabled(true);
fireEvent(new DecisionEvent(this, DecisionEvent.Type.RESET, System.currentTimeMillis(), refereeDecisions));
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#decisionMade(int, boolean)
*/
@Override
public synchronized void decisionMade(int refereeNo, boolean accepted) {
if (isBlocked()) return;
if (refereeDecisions[refereeNo] == null) {
logger.warn("decision ignored from referee {}: {} (not in a session)",
refereeNo + 1,
(accepted ? "lift" : "no lift"));
return;
}
// can't happen: the device itself is disabled when a red is given.
// if ((refereeDecisions[refereeNo].accepted != null) && !(refereeDecisions[refereeNo].accepted)) {
// // cannot reverse from red to white.
// logger.debug("decision ignored from referee {}: {} (prior decision was {})",
// new Object[] { refereeNo + 1,
// (accepted ? "lift" : "no lift"),
// refereeDecisions[refereeNo].accepted});
// return;
// }
final long currentTimeMillis = System.currentTimeMillis();
long deltaTime = currentTimeMillis - allDecisionsMadeTime;
if (decisionsMade == 3 && deltaTime > DECISION_REVERSAL_DELAY) {
// too late to reverse decision
logger.warn("decision ignored from referee {}: {} (too late by {} ms)", new Object[] { refereeNo + 1,
(accepted ? "lift" : "no lift"), deltaTime - DECISION_REVERSAL_DELAY });
return;
}
refereeDecisions[refereeNo].accepted = accepted;
refereeDecisions[refereeNo].time = currentTimeMillis;
logger.info("decision by referee {}: {}", refereeNo + 1, (accepted ? "lift" : "no lift"));
decisionsMade = 0;
int pros = 0;
int cons = 0;
for (int i = 0; i < refereeDecisions.length; i++) {
final Boolean accepted2 = refereeDecisions[i].accepted;
if (accepted2 != null) {
decisionsMade++;
if (accepted2) pros++;
else cons++;
}
}
if (decisionsMade >= 2) {
// audible down signal is emitted right away by the main computer.
// request lifter-facing display should display the "down" signal.
// also, downSignal() signals timeKeeper that time has been stopped if they
// had not stopped it manually.
if (pros >= 2 || cons >= 2) {
synchronized (groupData.getTimer()) {
if (!downSignaled) {
new Thread(new Runnable() {
@Override
public void run() {
if (downSignal != null) {
downSignal.emit();
}
groupData.downSignal();
}
}).start();
downSignaled = true;
fireEvent(new DecisionEvent(this,
DecisionEvent.Type.DOWN, currentTimeMillis,
refereeDecisions));
logger.info("*** down signal");
}
}
} else {
logger.debug("no majority");
fireEvent(new DecisionEvent(this, DecisionEvent.Type.WAITING, currentTimeMillis, refereeDecisions));
}
} else {
// Jury sees all changes, other displays will ignore this.
synchronized (groupData.getTimer()) {
logger.debug("broadcasting");
fireEvent(new DecisionEvent(this, DecisionEvent.Type.UPDATE, currentTimeMillis, refereeDecisions));
}
}
if (decisionsMade == 3) {
// NOTE: we wait for referee keypads to be blocked (see scheduleBlock)
// before sending the decision to groupData.
// broadcast the decision
if (allDecisionsMadeTime == 0L) {
// all 3 referees have just made a choice; schedule the display
// in 3 seconds
allDecisionsMadeTime = System.currentTimeMillis();
logger.info("all decisions made {}", allDecisionsMadeTime);
groupData.setAnnouncerEnabled(false);
scheduleDisplay(currentTimeMillis);
scheduleBlock();
scheduleReset();
} else {
// referees have changed their mind
logger.debug("three + change");
fireEvent(new DecisionEvent(this, DecisionEvent.Type.UPDATE, currentTimeMillis, refereeDecisions));
}
}
}
/**
* @param currentTimeMillis
* @param goodLift
*/
private void scheduleDisplay(final long currentTimeMillis) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fireEvent(new DecisionEvent(RefereeDecisionController.this, DecisionEvent.Type.SHOW, currentTimeMillis,
refereeDecisions));
}
}, DECISION_DISPLAY_DELAY);
}
/**
*
*/
private void scheduleBlock() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// save the decision
groupData.majorityDecision(refereeDecisions);
fireEvent(new DecisionEvent(RefereeDecisionController.this, DecisionEvent.Type.BLOCK, System.currentTimeMillis(), refereeDecisions));
setBlocked(true);
}
}, DECISION_REVERSAL_DELAY);
}
/**
*
*/
private void scheduleReset() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
reset();
}
}, DECISION_REVERSAL_DELAY + RESET_DELAY);
}
/**
* 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 DECISION_EVENT_METHOD = EventHelper.findMethod(DecisionEvent.class,
// when receiving this type of event
DecisionEventListener.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(DecisionEvent 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);
}
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#addListener(org.concordiainternational.competition.decision.DecisionEventListener)
*/
@Override
public void addListener(DecisionEventListener listener) {
logger.debug("add listener {}", listener); //$NON-NLS-1$
getEventRouter().addListener(DecisionEvent.class, listener, DECISION_EVENT_METHOD);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#removeListener(org.concordiainternational.competition.decision.DecisionEventListener)
*/
@Override
public void removeListener(DecisionEventListener listener) {
if (eventRouter != null) {
logger.debug("hide listener {}", listener); //$NON-NLS-1$
eventRouter.removeListener(DecisionEvent.class, listener, DECISION_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.
*/
/**
* @return the object's event router.
*/
private EventRouter getEventRouter() {
if (eventRouter == null) {
eventRouter = new EventRouter();
logger
.trace("new event router for RefereeDecisionController " + System.identityHashCode(this) + " = " + System.identityHashCode(eventRouter)); //$NON-NLS-1$ //$NON-NLS-2$
}
return eventRouter;
}
// timer events
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#finalWarning(int)
*/
@Override
public void finalWarning(int timeRemaining) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#forceTimeRemaining(int, org.concordiainternational.competition.ui.CompetitionApplication, org.concordiainternational.competition.ui.TimeStoppedNotificationReason)
*/
@Override
public void forceTimeRemaining(int startTime, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#initialWarning(int)
*/
@Override
public void initialWarning(int timeRemaining) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#noTimeLeft(int)
*/
@Override
public void noTimeLeft(int timeRemaining) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#normalTick(int)
*/
@Override
public void normalTick(int timeRemaining) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#pause(int, org.concordiainternational.competition.ui.CompetitionApplication, org.concordiainternational.competition.ui.TimeStoppedNotificationReason)
*/
@Override
public void pause(int timeRemaining, CompetitionApplication app, TimeStoppedNotificationReason reason) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#start(int)
*/
@Override
public void start(int timeRemaining) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#stop(int, org.concordiainternational.competition.ui.CompetitionApplication, org.concordiainternational.competition.ui.TimeStoppedNotificationReason)
*/
@Override
public void stop(int timeRemaining, CompetitionApplication app, TimeStoppedNotificationReason reason) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.decision.IDecisionController#addListener(org.concordiainternational.competition.ui.IRefereeConsole, int)
*/
@Override
public void addListener(IRefereeConsole refereeConsole, int refereeIndex) {
if (listeners[refereeIndex] != null) {
logger.trace("removing previous ORefereeConsole listener {}",listeners[refereeIndex]);
removeListener(listeners[refereeIndex]);
}
addListener(refereeConsole);
listeners[refereeIndex] = refereeConsole;
logger.trace("adding new ORefereeConsole listener {}",listeners[refereeIndex]);
}
@Override
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
@Override
public boolean isBlocked() {
return blocked && (groupData.getCurrentSession() != null);
}
@Override
public Lifter getLifter() {
return groupData.getCurrentLifter();
}
}
| 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.webapp;
import java.io.BufferedWriter;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.icepush.servlet.MainServlet;
import com.vaadin.terminal.gwt.server.ApplicationServlet;
@SuppressWarnings("serial")
public class PushServlet extends ApplicationServlet {
private MainServlet pushServlet;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
pushServlet = new MainServlet(servletConfig.getServletContext());
}
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getRequestURI().endsWith(".icepush")) {
// delegate the Push request to the IcePush servlet
try {
pushServlet.service(request, response);
} catch (ServletException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
// Vaadin request
super.service(request, response);
}
}
@Override
public void destroy() {
super.destroy();
pushServlet.shutdown();
}
@Override
protected void writeAjaxPageHtmlHeader(BufferedWriter page, String title, String themeUri, HttpServletRequest req) throws IOException {
super.writeAjaxPageHtmlHeader(page, title, themeUri, req);
// REFACTOR: detect browser
// the following is mobile safari specific (iPod). does not harm other browsers.
// there is no easy way to make this conditional without overriding the whole
// writeAjaxPage method, which is not worth it at this stage.
// page.write("<meta name='viewport' content='width=device-width' />");
// page.write("<meta name='apple-mobile-web-app-capable' content='yes' />");
page.append("<meta name=\"viewport\" content="
+ "\"user-scalable=no, width=device-width, "
+ "initial-scale=1.0, maximum-scale=1.0;\" />");
page.append("<meta name=\"apple-touch-fullscreen\" content=\"yes\" />");
page.append("<meta name=\"apple-mobile-web-app-capable\" "
+ "content=\"yes\" />");
page.append("<meta name=\"apple-mobile-web-app-status-bar-style\" "
+ "content=\"black\" />");
page.append("<link rel=\"apple-touch-icon\" "
+ "href=\"TouchKit/VAADIN/themes/touch/img/icon.png\" />");
page.append("<link rel=\"apple-touch-startup-image\" "
+ "href=\"TouchKit/VAADIN/themes/touch/img/startup.png\" />");
}
}
| 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.webapp;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.decision.Speakers;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.nec.NECDisplay;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.event.def.OverrideMergeEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy Called when the application is started to initialize the
* database and other global features (serial communication ports)
*/
public class WebApplicationConfiguration implements HbnSessionManager, ServletContextListener {
private static Logger logger = LoggerFactory.getLogger(WebApplicationConfiguration.class);
private static EntityManagerFactory sessionFactory = null;
private static final boolean TEST_MODE = false;
public static final boolean NECShowsLifterImmediately = true;
public static final boolean DEFAULT_STICKINESS = true;
private static AnnotationConfiguration cnf;
public static NECDisplay necDisplay = null;
/**
* this constructor sets the default values if the full parameterized
* constructor has not been called first (which is normally the case). If
* the full constructor has been called first, then the existing factory is
* returned.
*
* @return a Hibernate session factory
*/
public static EntityManagerFactory getSessionFactory() {
// this call sets the default values if the parameterized constructor
// has not
// been called first (which is normally the case). If the full
// constructor
// has been called first, then the existing factory is returned.
if (sessionFactory != null) return sessionFactory;
else throw new RuntimeException("should have called getSessionFactory(testMode,dbPath) first."); //$NON-NLS-1$
}
/**
* Full constructor, normally invoked first.
*
* @param testMode
* true if the database runs in memory, false is there is a
* physical database
* @param dbPath
* @return
*/
public static EntityManagerFactory getSessionFactory(boolean testMode, String dbPath) {
if (sessionFactory == null) {
try {
cnf = new AnnotationConfiguration();
//derbySetup(testMode, dbPath, cnf);
h2Setup(testMode, dbPath, cnf);
cnf.setProperty(Environment.USER, "sa"); //$NON-NLS-1$
cnf.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); //$NON-NLS-1$
// the classes we store in the database.
cnf.addAnnotatedClass(Lifter.class);
cnf.addAnnotatedClass(CompetitionSession.class);
cnf.addAnnotatedClass(Platform.class);
cnf.addAnnotatedClass(Category.class);
cnf.addAnnotatedClass(Competition.class);
cnf.addAnnotatedClass(CompetitionSession.class);
// cnf.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider"); //$NON-NLS-1$
cnf.setProperty("hibernate.cache.region.factory_class", "net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory"); //$NON-NLS-1$ //$NON-NLS-2$
cnf.setProperty("hibernate.cache.use_second_level_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
cnf.setProperty("hibernate.cache.use_query_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
// cnf.setProperty(Environment.CACHE_PROVIDER,"org.hibernate.cache.HashtableCacheProvider");
// the following line is necessary because the Lifter class uses
// the Lift class several times (one for each lift), which would normally force
// us to override the column names to ensure they are unique. Hibernate
// supports this with an extension.
// cnf.setNamingStrategy(DefaultComponentSafeNamingStrategy.INSTANCE);
// listeners
cnf.setListener("merge", new OverrideMergeEventListener()); //$NON-NLS-1$
sessionFactory = (EntityManagerFactory) cnf.buildSessionFactory();
// create the standard categories, etc.
// if argument is > 0, create sample data as well.
EntityManager sess = sessionFactory.createEntityManager();
sess.joinTransaction();
Category.insertStandardCategories(sess, Locale.getDefault());
insertInitialData(5, sess, testMode);
sess.flush();
sess.close();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
ex.printStackTrace(System.err);
throw new ExceptionInInitializerError(ex);
}
}
return sessionFactory;
}
/**
* @param testMode
* @param dbPath
* @param cnf1
* @throws IOException
*/
private static void h2Setup(boolean testMode, String dbPath, AnnotationConfiguration cnf1) throws IOException {
cnf1.setProperty(Environment.DRIVER, "org.h2.Driver"); //$NON-NLS-1$
if (testMode) {
cnf1.setProperty(Environment.URL, "jdbc:h2:mem:competition"); //$NON-NLS-1$
cnf1.setProperty(Environment.SHOW_SQL, "false"); //$NON-NLS-1$
cnf1.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); //$NON-NLS-1$
} else {
File file = new File(dbPath).getParentFile(); //$NON-NLS-1$
if (!file.exists()) {
boolean status = file.mkdirs();
if (! status) {
throw new RuntimeException("could not create directories for "+file.getCanonicalPath());
}
}
cnf1.setProperty(Environment.SHOW_SQL, "false"); //$NON-NLS-1$
cnf1.setProperty(Environment.URL, "jdbc:h2:file:" + dbPath); //$NON-NLS-1$
String ddlMode = "create"; //$NON-NLS-1$
file = new File(dbPath + ".h2.db"); //$NON-NLS-1$
if (file.exists()) {
ddlMode = "update"; //$NON-NLS-1$
} else {
file = new File(dbPath + ".data.db"); //$NON-NLS-1$
if (file.exists()) {
ddlMode = "update"; //$NON-NLS-1$
}
}
logger.info("Using Hibernate mode {} (file {} exists={}", new Object[] { ddlMode, file.getAbsolutePath(), Boolean.toString(file.exists()) }); //$NON-NLS-1$
cnf1.setProperty(Environment.HBM2DDL_AUTO, ddlMode);
// throw new
// ExceptionInInitializerError("Production database configuration not specified");
}
cnf1.setProperty(Environment.DIALECT, H2Dialect.class.getName());
}
/**
* @param testMode
* @param dbPath
* @param cnf1
*/
@SuppressWarnings("unused")
private static void derbySetup(boolean testMode, String dbPath, AnnotationConfiguration cnf1) {
if (testMode) {
cnf1.setProperty(Environment.DRIVER, "org.h2.Driver"); //$NON-NLS-1$
cnf1.setProperty(Environment.URL, "jdbc:h2:mem:competition"); //$NON-NLS-1$
cnf1.setProperty(Environment.SHOW_SQL, "false"); //$NON-NLS-1$
cnf1.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); //$NON-NLS-1$
} else {
cnf1.setProperty(Environment.DRIVER, "org.apache.derby.jdbc.EmbeddedDriver"); //$NON-NLS-1$
cnf1.setProperty(Environment.SHOW_SQL, "false"); //$NON-NLS-1$
String ddlMode = "create"; //$NON-NLS-1$
String suffix=";create=true";
File file = new File(dbPath); //$NON-NLS-1$
if (file.exists()) {
ddlMode = "update"; //$NON-NLS-1$
} else {
file = new File(dbPath); //$NON-NLS-1$
if (file.exists()) {
ddlMode = "update"; //$NON-NLS-1$
}
}
logger.info(
"Using Hibernate mode {} (file {} exists={}",
new Object[] { ddlMode, file.getAbsolutePath(), Boolean.toString(file.exists()) }); //$NON-NLS-1$
cnf1.setProperty(Environment.HBM2DDL_AUTO, ddlMode);
cnf1.setProperty(Environment.URL, "jdbc:derby:" + dbPath + suffix); //$NON-NLS-1$
// throw new ExceptionInInitializerError("Production database configuration not specified");
}
cnf1.setProperty(Environment.DIALECT, DerbyDialect.class.getName());
}
/**
* Insert initial data if the database is empty.
*
* @param liftersToLoad
* @param sess
* @param testMode
*/
public static void insertInitialData(int liftersToLoad, EntityManager sess, boolean testMode) {
if (sess.createCriteria(CompetitionSession.class).list().size() == 0) {
// empty database
Competition competition = new Competition();
competition.setFederation(Messages.getString("Competition.defaultFederation", Locale.getDefault())); //$NON-NLS-1$
competition.setFederationAddress(Messages.getString(
"Competition.defaultFederationAddress", Locale.getDefault())); //$NON-NLS-1$
competition.setFederationEMail(Messages
.getString("Competition.defaultFederationEMail", Locale.getDefault())); //$NON-NLS-1$
competition.setFederationWebSite(Messages.getString(
"Competition.defaultFederationWebSite", Locale.getDefault())); //$NON-NLS-1$
Calendar w = Calendar.getInstance();
w.set(Calendar.MILLISECOND, 0);
w.set(Calendar.SECOND, 0);
w.set(Calendar.MINUTE, 0);
w.set(Calendar.HOUR_OF_DAY, 8);
Calendar c = (Calendar) w.clone();
c.add(Calendar.HOUR_OF_DAY, 2);
if (testMode) {
setupTestData(competition, liftersToLoad, sess, w, c);
} else {
setupEmptyCompetition(competition, sess);
}
sess.persist(competition);
} else {
// database contains data, leave it alone.
}
}
/**
* Create an empty competition.
* Set-up the defaults for using the timekeeping and refereeing features.
* @param competition
*
* @param sess
*/
protected static void setupEmptyCompetition(Competition competition, EntityManager sess) {
Platform platform1 = new Platform("Platform"); //$NON-NLS-1$
setDefaultMixerName(platform1);
platform1.setHasDisplay(false);
platform1.setShowDecisionLights(true);
// collar
platform1.setNbC_2_5(1);
// small plates
platform1.setNbS_0_5(1);
platform1.setNbS_1(1);
platform1.setNbS_1_5(1);
platform1.setNbS_2(1);
platform1.setNbS_2_5(1);
// large plates, regulation set-up
platform1.setNbL_2_5(0);
platform1.setNbL_5(0);
platform1.setNbL_10(1);
platform1.setNbL_15(1);
platform1.setNbL_20(1);
platform1.setNbL_25(1);
// competition template
File templateFile;
URL templateUrl = platform1.getClass().getResource("/templates/teamResults/TeamResultSheetTemplate_Standard.xls");
try {
templateFile = new File(templateUrl.toURI());
competition.setResultTemplateFileName(templateFile.getCanonicalPath());
} catch (URISyntaxException e) {
templateFile = new File(templateUrl.getPath());
} catch (IOException e) {
}
sess.persist(platform1);
CompetitionSession groupA = new CompetitionSession("A", null, null); //$NON-NLS-1$
sess.persist(groupA);
CompetitionSession groupB = new CompetitionSession("B", null, null); //$NON-NLS-1$#
sess.persist(groupB);
CompetitionSession groupC = new CompetitionSession("C", null, null); //$NON-NLS-1$
sess.persist(groupC);
}
/**
* @param competition
* @param liftersToLoad
* @param sess
* @param w
* @param c
*/
protected static void setupTestData(Competition competition, int liftersToLoad,
EntityManager sess, Calendar w, Calendar c) {
Platform platform1 = new Platform("Gym 1"); //$NON-NLS-1$
sess.persist(platform1);
Platform platform2 = new Platform("Gym 2"); //$NON-NLS-1$
sess.persist(platform1);
sess.persist(platform2);
CompetitionSession groupA = new CompetitionSession("A", w.getTime(), c.getTime()); //$NON-NLS-1$
groupA.setPlatform(platform1);
CompetitionSession groupB = new CompetitionSession("B", w.getTime(), c.getTime()); //$NON-NLS-1$
groupB.setPlatform(platform2);
CompetitionSession groupC = new CompetitionSession("C", w.getTime(), c.getTime()); //$NON-NLS-1$
groupC.setPlatform(platform1);
sess.persist(groupA);
sess.persist(groupB);
sess.persist(groupC);
insertSampleLifters(liftersToLoad, sess, groupA, groupB, groupC);
}
/**
* @param platform1
*/
protected static void setDefaultMixerName(Platform platform1) {
String mixerName = null;
try {
mixerName = Speakers.getOutputNames().get(0);
platform1.setMixerName(mixerName);
} catch (Exception e) {
// leave mixerName null
}
}
private static void insertSampleLifters(int liftersToLoad, EntityManager sess, CompetitionSession groupA, CompetitionSession groupB,
CompetitionSession groupC) {
final String[] fnames = { "Peter", "Albert", "Joshua", "Mike", "Oliver", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"Paul", "Alex", "Richard", "Dan", "Umberto", "Henrik", "Rene", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
"Fred", "Donald" }; //$NON-NLS-1$ //$NON-NLS-2$
final String[] lnames = { "Smith", "Gordon", "Simpson", "Brown", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
"Clavel", "Simons", "Verne", "Scott", "Allison", "Gates", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
"Rowling", "Barks", "Ross", "Schneider", "Tate" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
Random r = new Random(0);
for (int i = 0; i < liftersToLoad; i++) {
Lifter p = new Lifter();
p.setCompetitionSession(groupA);
p.setFirstName(fnames[r.nextInt(fnames.length)]);
p.setLastName(lnames[r.nextInt(lnames.length)]);
sess.persist(p);
// System.err.println("group A - "+InputSheetHelper.toString(p));
}
for (int i = 0; i < liftersToLoad; i++) {
Lifter p = new Lifter();
p.setCompetitionSession(groupB);
p.setFirstName(fnames[r.nextInt(fnames.length)]);
p.setLastName(lnames[r.nextInt(lnames.length)]);
sess.persist(p);
// System.err.println("group B - "+InputSheetHelper.toString(p));
}
sess.flush();
}
/*
* We implement HbnSessionManager as a convenience; when a domain class
* needs access to persistance, and we don't want to pass in another
* HbnSessionManager such as the application, we use this one. (non-Javadoc)
*
* @see
* com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager#getHbnSession()
*/
@Override
public EntityManager getHbnSession() {
return getSessionFactory().createEntityManager();
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
WebApplicationConfiguration.getSessionFactory().close(); // Free all
// templates,
// should free
// H2
h2Shutdown();
if (necDisplay != null) {
necDisplay.close();
}
necDisplay = null;
logger.debug("contextDestroyed() done"); //$NON-NLS-1$
}
/**
* Try to shutdown H2 cleanly.
*/
private void h2Shutdown() {
Connection connection = null;
try {
connection = cnf.buildSettings().getConnectionProvider().getConnection();
Statement stmt = connection.createStatement();
try {
stmt.execute("SHUTDOWN"); //$NON-NLS-1$
} finally {
stmt.close();
}
} catch (HibernateException e) {
LoggerUtils.logException(logger, e);
} catch (SQLException e) {
LoggerUtils.logException(logger, e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LoggerUtils.logException(logger, e);
}
}
}
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
ServletContext sCtx = arg0.getServletContext();
String dbPath = sCtx.getInitParameter("dbPath"); //$NON-NLS-1$
String appName = sCtx.getServletContextName();
if (dbPath != null) {
WebApplicationConfiguration.getSessionFactory(TEST_MODE, dbPath).createEntityManager();
} else {
WebApplicationConfiguration.getSessionFactory(TEST_MODE, "db/" + appName).createEntityManager(); //$NON-NLS-1$
}
if (necDisplay != null) {
necDisplay.close();
necDisplay = null;
}
final String comPortName = sCtx.getInitParameter("comPort"); //$NON-NLS-1$
getNecDisplay(comPortName);
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.setDefault(new Locale(defaultLanguage,defaultCountry));
logger.info("Default JVM Locale set to: {}", Locale.getDefault()); //$NON-NLS-1$
logger.debug("contextInitialized() done"); //$NON-NLS-1$
}
/**
* @param comPortName
* @throws RuntimeException
*/
public static void getNecDisplay(final String comPortName) throws RuntimeException {
try {
if (comPortName != null && !comPortName.isEmpty()) {
necDisplay = new NECDisplay();
necDisplay.setComPortName(comPortName);
}
} catch (Exception e) {
logger.warn("Could not open port {} {}",comPortName,e.getMessage());
}
}
}
| 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.spreadsheet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletContext;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import com.vaadin.terminal.SystemError;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* @author IT Mill
* @author jflamy - adapted from example in the Book of Vaadin.
*
*/
public class SpreadsheetUploader extends CustomComponent implements Upload.SucceededListener, Upload.FailedListener,
Upload.Receiver, ApplicationView {
private static final long serialVersionUID = 6843262937708809785L;
final private static Logger logger = LoggerFactory.getLogger(SpreadsheetUploader.class);
Panel root; // Root element for contained components.
Panel resultPanel; // Panel that contains the uploaded image.
File file; // File to write to.
private CompetitionApplication app;
private Label status;
private Locale locale;
private String viewName;
public SpreadsheetUploader(boolean initFromFragment, String viewName) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.app = CompetitionApplication.getCurrent();
this.locale = app.getLocale();
root = new Panel(Messages.getString("SpreadsheetUploader.SpreadsheetUpload", locale)); //$NON-NLS-1$
setCompositionRoot(root);
// Create the Upload component.
//final Upload upload = new Upload(Messages.getString("SpreadsheetUploader.ChooseFile",locale), this); //$NON-NLS-1$
final Upload upload = new Upload("", this); //$NON-NLS-1$
upload.setImmediate(true); // start immediately as soon as the file is
// selected.
// Use a custom button caption instead of plain "Upload".
upload.setButtonCaption(Messages.getString("SpreadsheetUploader.UploadNow", locale)); //$NON-NLS-1$
// Listen for events regarding the success of upload.
upload.addListener((Upload.SucceededListener) this);
upload.addListener((Upload.FailedListener) this);
root.addComponent(upload);
root.addComponent(new Label());
// Create a panel for displaying the uploaded file.
resultPanel = new Panel();
status = new Label(Messages.getString("SpreadsheetUploader.NoSpreadsheetUploadedYet", locale)); //$NON-NLS-1$
resultPanel.addComponent(status);
root.addComponent(resultPanel);
}
// Callback method to begin receiving the upload.
@Override
public OutputStream receiveUpload(String filename, String MIMEType) {
FileOutputStream fos = null; // Output stream to write to
try {
ServletContext sCtx = app.getServletContext();
String dirName = sCtx.getRealPath("registration"); //$NON-NLS-1$
File dir = new File(dirName);
logger.debug(dir.getAbsolutePath());
if (!dir.exists()) dir.mkdirs();
File longPath = new File(filename);
filename = longPath.getName();
file = new File(dir, filename);
logger.debug("writing to {}", file.getAbsolutePath()); //$NON-NLS-1$
// Open the file for writing.
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
// Error while opening the file. Not reported here.
e.printStackTrace();
this.setComponentError(new SystemError(e));
throw new SystemError(e);
}
return fos; // Return the output stream to write to
}
// This is called if the upload is finished.
@Override
public void uploadSucceeded(Upload.SucceededEvent event) {
// Log the upload on screen.
final String messageFormat = Messages.getString("SpreadsheetUploader.Status", locale); //$NON-NLS-1$
final String mimeType = event.getMIMEType();
status.setValue(MessageFormat.format(messageFormat, event.getFilename(), mimeType));
processUploadedFile(mimeType);
}
/**
* @param mimeType
* @throws SystemError
*/
private void processUploadedFile(String mimeType) throws SystemError {
// process the file
logger.debug("reading from: {}", file); //$NON-NLS-1$
final FileResource fileResource = new FileResource(file, getApplication());
DownloadStream ds = fileResource.getStream();
if (file.getPath().endsWith(".csv")) {
processCSV(ds);
} else if (mimeType.endsWith("xls") || mimeType.endsWith("excel")) {
processXLS(ds);
} else {
throw new RuntimeException("Unknown format.");
}
}
private void processCSV(DownloadStream ds) {
try {
final Session hbnSession = app.getHbnSession();
InputCSVHelper iCSV = new InputCSVHelper(app);
List<Lifter> lifters = iCSV.getAllLifters(ds.getStream(), app);
for (Lifter curLifter : lifters) {
hbnSession.save(curLifter);
}
} catch (Throwable t) {
t.printStackTrace();
throw new SystemError(t);
}
}
private void processXLS(DownloadStream ds) {
try {
final WeighInSheet weighInSheet = new WeighInSheet(app);
final Session hbnSession = app.getHbnSession();
weighInSheet.readHeader(ds.getStream(), app);
List<Lifter> lifters = weighInSheet.getAllLifters(ds.getStream(), app);
for (Lifter curLifter : lifters) {
hbnSession.save(curLifter);
}
} catch (Throwable t) {
t.printStackTrace();
throw new SystemError(t);
}
}
// This is called if the upload fails.
@Override
public void uploadFailed(Upload.FailedEvent event) {
// Log the failure on screen.
final String messageFormat = Messages.getString("SpreadsheetUploader.UploadingFailure", locale); //$NON-NLS-1$
final String mimeType = event.getMIMEType();
status.setValue(MessageFormat.format(messageFormat, event.getFilename(), mimeType));
}
@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() {
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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
/**
* Encapsulate a spreadsheet as a StreamSource so that it can be used as a
* source of data when the user clicks on a link. This class converts the output
* stream produced by the
* {@link OutputSheet#writeWorkBook(WorkBookHandle, OutputStream)} method to an
* input stream that the Vaadin framework can consume.
*/
@SuppressWarnings("serial")
public class JXLSLifterCard extends JXLSWorkbookStreamSource {
/**
* Number of rows in a card
*/
final static int CARD_SIZE = 10;
/**
* Number of cards per page
*/
final static int CARDS_PER_PAGE = 2;
/**
*
*/
public JXLSLifterCard() {
super(false);
}
public JXLSLifterCard(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
@SuppressWarnings("unused")
private final static Logger logger = LoggerFactory.getLogger(JXLSLifterCard.class);
@Override
public InputStream getTemplate() throws IOException {
String templateName = "/LifterCardTemplate_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected void getSortedLifters() {
this.lifters = LifterSorter.registrationOrderCopy(new LifterContainer(app, isExcludeNotWeighed()).getAllPojos());
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource#postProcess(org.apache.poi.ss.usermodel.Workbook)
*/
@Override
protected void postProcess(Workbook workbook) {
setPageBreaks(workbook);
}
private void setPageBreaks(Workbook workbook) {
Sheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
sheet.setAutobreaks(false);
int increment = CARDS_PER_PAGE*CARD_SIZE + (CARDS_PER_PAGE-1);
for (int curRowNum = increment; curRowNum < lastRowNum;) {
sheet.setRowBreak(curRowNum-1);
curRowNum += increment;
}
}
}
| 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.spreadsheet;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellRange;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
/**
*
* @author jflamy
*
*/
public abstract class OutputSheet {
private Logger logger = LoggerFactory.getLogger(OutputSheet.class);
protected CompetitionSession competitionSession;
protected CategoryLookup categoryLookup;
protected CompetitionApplication app;
public OutputSheet() {
}
public OutputSheet(CategoryLookup categoryLookup, CompetitionApplication app, CompetitionSession competitionSession) {
init(categoryLookup, app, competitionSession);
}
/**
* @param categoryLookup1
* @param app1
* @param competitionSession1
*/
public void init(CategoryLookup categoryLookup1, CompetitionApplication app1, CompetitionSession competitionSession1) {
this.categoryLookup = categoryLookup1;
this.app = app1;
this.competitionSession = competitionSession1;
if (competitionSession1 != null){
logger.debug("resultSheet session = {} {}",System.identityHashCode(competitionSession1), competitionSession1.getReferee3());
}
}
public void writeLifters(List<Lifter> lifters, OutputStream out) throws CellTypeMismatchException,
CellNotFoundException, RowNotFoundException, IOException, WorkSheetNotFoundException {
WorkBookHandle workBookHandle = null;
try {
if (lifters.isEmpty()) {
// should have been dealt with earlier
// this prevents a loop in the spreadsheet processing if it has
// not.
throw new RuntimeException(Messages.getString(
"OutputSheet.EmptySpreadsheet", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
// get the data sheet
workBookHandle = new WorkBookHandle(getTemplate());
setupWorkbook(workBookHandle);
final WorkSheetHandle workSheet = workBookHandle.getWorkSheet(0);
// fill-in the header.
writeHeader(workSheet);
// process data sheet
int i = 0;
for (Lifter curLifter : lifters) {
writeLifter(curLifter, workSheet, categoryLookup, i++);
}
removeLastRowIfInserting(workSheet, i + InputSheetHelper.START_ROW);
cleanUpLifters(workSheet,i);
// write out
writeWorkBook(workBookHandle, out);
} finally {
// close files
if (out != null) out.close();
if (workBookHandle != null) workBookHandle.close();
if (getTemplate() != null) getTemplate().close();
logger.debug("done writing, closed files and handles."); //$NON-NLS-1$
}
}
protected void cleanUpLifters(WorkSheetHandle workSheet, int i) throws CellTypeMismatchException, CellNotFoundException {
}
protected void setupWorkbook(WorkBookHandle workBookHandle) {
}
/**
* Override this method to do nothing if you are not inserting rows.
*
* @param workSheet
* @param i
* @throws RowNotFoundException
*/
protected void removeLastRowIfInserting(final WorkSheetHandle workSheet, int rownum) throws RowNotFoundException {
workSheet.removeRow(rownum);
}
/**
* Write top and bottom part of spreadsheet.
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
*/
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
workSheet.getCell("A1").setVal(competition.getFederation()); //$NON-NLS-1$
workSheet.getCell("A2").setVal(competition.getFederationAddress()); //$NON-NLS-1$
workSheet.getCell("A3").setVal(competition.getFederationWebSite()); //$NON-NLS-1$
workSheet.getCell("B4").setVal(competition.getFederationEMail()); //$NON-NLS-1$
if (competitionSession != null) {
setCellValue(workSheet, "L4", competitionSession.getName());
}
workSheet.getCell("L1").setVal(competition.getCompetitionName()); //$NON-NLS-1$
workSheet.getCell("L2").setVal(competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) workSheet.getCell("L3").setVal(SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
workSheet.getCell("T2").setVal(competition.getCompetitionCity()); //$NON-NLS-1$
workSheet.getCell("T3").setVal(competition.getCompetitionOrganizer()); //$NON-NLS-1$
final Integer invitedIfBornBefore = competition.getInvitedIfBornBefore();
if (invitedIfBornBefore != null && invitedIfBornBefore > 0)
workSheet.getCell("T4").setVal(invitedIfBornBefore); //$NON-NLS-1$
writeGroup(workSheet);
}
}
/**
* Try to set the cell value; if it fails, try to create the cell.
*
* @param workSheet
* @param cellAddress
* @param value
*/
protected void setCellValue(WorkSheetHandle workSheet, String cellAddress, Object value) {
try {
workSheet.getCell(cellAddress).setVal(value); //$NON-NLS-1$
} catch (Exception e) {
workSheet.add(value, cellAddress);
}
}
/**
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
*/
protected void writeGroup(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
if (competitionSession != null) {
setCellValue(workSheet, "L4", competitionSession.getName());
} else {
setCellValue(workSheet, "K4", "");// clear the cell;
setCellValue(workSheet, "L4", "");// clear the cell;
}
}
abstract void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int rownum)
throws CellTypeMismatchException, CellNotFoundException;
/**
* @param workBookHandle
* @param out
* @throws IOException
*/
void writeWorkBook(WorkBookHandle workBookHandle, OutputStream out) throws IOException {
BufferedOutputStream bout = new BufferedOutputStream(out);
workBookHandle.writeBytes(bout);
bout.flush();
bout.close();
}
public void setCategoryLookup(CategoryLookup categoryLookup) {
this.categoryLookup = categoryLookup;
}
public CategoryLookup getCategoryLookup() {
return categoryLookup;
}
abstract public InputStream getTemplate() throws IOException;
abstract protected List<Lifter> getLifters(boolean excludeNotWeighed);
/**
* @param workSheet
* @param firstRow
* @param lastCol
* @param lastRow
* @param firstCol
*/
protected void setPrintArea(WorkSheetHandle workSheet, int firstRow, int firstCol, final int lastRow, int lastCol) {
CellRange cellRange = null;
int[] rangeCoords = null;
try {
logger.trace("setPrintArea for {}", workSheet.getSheetName());
rangeCoords = new int[] { firstRow, firstCol, lastRow, lastCol };
logger.trace("sheet {} : print area coords: {}, range: {}", new Object[] { workSheet.getSheetName(),
rangeCoords, cellRange });
cellRange = new CellRange(workSheet, rangeCoords);
workSheet.setPrintArea(cellRange);
} catch (Exception e) {
LoggerUtils.logException(logger, e);
logger.error("sheet {} : print area coords: {}, range: {}", new Object[] { workSheet.getSheetName(),
rangeCoords, cellRange });
}
}
/**
* @param workSheet
*/
protected void setFooterLeft(WorkSheetHandle workSheet) {
final Competition competition = SheetUtils.getCompetition();
final Date competitionDate = competition.getCompetitionDate();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(competitionDate);
workSheet.setFooterText("&L" + competition.getCompetitionName() + " (" + s + ")" + "&R&P");
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellHandle;
import com.extentech.ExtenXLS.FormatHandle;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellPositionConflictException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
/**
*
* @author jflamy
*
*/
public class LifterCardSheet extends OutputSheet {
protected static final String TEMPLATE_XLS = "/LifterCardTemplate.xls"; //$NON-NLS-1$
Logger logger = LoggerFactory.getLogger(LifterCardSheet.class);
final static int TEMPLATE_ROWS = 11;
final static int TEMPLATE_COLUMNS = 8;
int nbCardsPrinted = 0; // how many cards we have printed so far
public LifterCardSheet() {
}
public LifterCardSheet(CategoryLookup categoryLookup, CompetitionApplication app, CompetitionSession competitionSession) {
super(categoryLookup, app, competitionSession);
}
@Override
public void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int ignored)
throws CellTypeMismatchException, CellNotFoundException {
int rowNum = (nbCardsPrinted * TEMPLATE_ROWS) - (nbCardsPrinted / 2);
if (nbCardsPrinted > 0) {
createNewCard(rowNum, workSheet); // copy rows to the bottom of the
// spreadsheet.
}
workSheet.getCell(rowNum, 1).setVal(lifter.getLastName().toUpperCase() + ", " + lifter.getFirstName());
workSheet.getCell(rowNum, 5).setVal(lifter.getClub());
workSheet.getCell(rowNum + 2, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rowNum + 2, 3).setVal(lifter.getCompetitionSession().getName());
if (Competition.isMasters()) {
workSheet.getCell(rowNum + 2, 5).setVal(lifter.getMastersAgeGroupInterval());
} else {
workSheet.getCell(rowNum + 2, 4).setVal("");
workSheet.getCell(rowNum + 2, 5).setVal("");
workSheet.getCell(rowNum + 2, 5).setBorderLineStyle(FormatHandle.BORDER_NONE);
}
final Category category = lifter.getRegistrationCategory();
workSheet.getCell(rowNum + 2, 7).setVal((category != null ? category.getName() : ""));
nbCardsPrinted++;
}
/**
* @param rownum
* @param worksheet
*/
private void createNewCard(int rownum, WorkSheetHandle worksheet) {
int row = 0;
int column = 0;
int templateRows = TEMPLATE_ROWS;
// we do two cards per page. The last row is the spacer between the top
// and
// bottom card; on bottom cards we don't copy the spacer.
if ((nbCardsPrinted % 2) == 1) {
// we we are printing the bottom one.
templateRows--;
}
// System.err.println("nbcards = "+nbCardsPrinted+" rownum = "+rownum+" templateRows = "+templateRows);
for (row = 0; row < templateRows;) {
for (column = 0; column < TEMPLATE_COLUMNS;) {
try {
CellHandle sourceCell = worksheet.getCell(row, column);
final int destination = row + rownum;
CellHandle.copyCellToWorkSheet(sourceCell, worksheet, destination, column);
} catch (CellNotFoundException e) {
// ignore (do not copy empty cells).
} catch (CellPositionConflictException e) {
LoggerUtils.logException(logger, e);
}
column++;
}
row++;
}
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(TEMPLATE_XLS);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + TEMPLATE_XLS);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
return LifterSorter.registrationOrderCopy(Lifter.getAll());
}
@Override
protected void removeLastRowIfInserting(WorkSheetHandle workSheet, int rownum) throws RowNotFoundException {
// do nothing
}
@Override
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
// do nothing
}
@Override
protected void setupWorkbook(WorkBookHandle workBookHandle) {
super.setupWorkbook(workBookHandle);
// workBookHandle.setDupeStringMode(WorkBookHandle.ALLOWDUPES);
workBookHandle.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE);
// System.getProperties().put(com.extentech.formats.XLS.WorkBook.CONVERTMULBLANKS, "false");
}
@Override
protected void cleanUpLifters(WorkSheetHandle workSheet, int nbCards) throws CellTypeMismatchException, CellNotFoundException {
// Horrible workaround. For some reason, cell E5 cannot be set before copying the lifter card
// Yes, you read right. In fact, even changing cell E5 in the template proper breaks things.
int curCard = 0;
boolean done = false;
while (!done ) {
final int cardsPerPage = 2;
int curCardRowNum = curCard * TEMPLATE_ROWS - ((curCard+cardsPerPage) / cardsPerPage) + 1;
try {
setLocalizedStrings(workSheet, curCardRowNum);
} catch (CellNotFoundException e) {
done = true;
}
curCard++;
}
}
/**
* @param workSheet
* @param curCardRowNum
* @throws CellNotFoundException
*/
protected void setLocalizedStrings(WorkSheetHandle workSheet,
int curCardRowNum) throws CellNotFoundException {
CellHandle cell;
cell = workSheet.getCell(curCardRowNum + 4, 1);
cell.setVal(null);
cell.setVal("Arraché");
cell = workSheet.getCell(curCardRowNum + 4, 4);
cell.setVal(null);
cell.setVal("Épaulé-jeté");
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class JXLSStartingList extends JXLSWorkbookStreamSource {
public JXLSStartingList(){
super(false);
}
public JXLSStartingList(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
Logger logger = LoggerFactory.getLogger(JXLSStartingList.class);
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
final Session hbnSession = CompetitionApplication.getCurrent().getHbnSession();
List<Competition> competitionList = hbnSession.createCriteria(Competition.class).list();
Competition competition = competitionList.get(0);
getReportingBeans().put("competition",competition);
}
@Override
public InputStream getTemplate() throws IOException {
String templateName = "/StartSheetTemplate_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected void getSortedLifters() {
this.lifters = LifterSorter.registrationOrderCopy(new LifterContainer(app, isExcludeNotWeighed()).getAllPojos());
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
public class StartList extends OutputSheet {
private HbnSessionManager hbnSessionManager;
/**
* Create a sheet.
* If this constructor is used, or newInstance is called, then
* {@link #init(CategoryLookup, CompetitionApplication, CompetitionSession)} must also be called.
*/
public StartList() {
this.hbnSessionManager = CompetitionApplication.getCurrent();
}
public StartList(HbnSessionManager hbnSessionManager) {
this.hbnSessionManager = hbnSessionManager;
}
protected static final String TEMPLATE_XLS = "/StartSheetTemplate.xls"; //$NON-NLS-1$
final static Logger logger = LoggerFactory.getLogger(StartList.class);
@Override
public void writeLifters(List<Lifter> lifters, OutputStream out) throws CellTypeMismatchException,
CellNotFoundException, RowNotFoundException, IOException, WorkSheetNotFoundException {
WorkBookHandle workBookHandle = null;
try {
if (lifters.isEmpty()) {
// should have been dealt with earlier
// this prevents a loop in the spreadsheet processing if it has
// not.
throw new RuntimeException(Messages.getString(
"OutputSheet.EmptySpreadsheet", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
// get the data sheet
workBookHandle = new WorkBookHandle(getTemplate());
WorkSheetHandle workSheet;
// Create the start list.
try {
workSheet = workBookHandle.getWorkSheet(0);
new StartSheet(hbnSessionManager).writeStartSheet(lifters, workSheet);
} catch (WorkSheetNotFoundException wnf) {
LoggerUtils.logException(logger, wnf);
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// write out
writeWorkBook(workBookHandle, out);
} finally {
// close files
if (out != null) out.close();
if (workBookHandle != null) workBookHandle.close();
if (getTemplate() != null) getTemplate().close();
logger.debug("done writing, closed files and handles."); //$NON-NLS-1$
}
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(TEMPLATE_XLS);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + TEMPLATE_XLS);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
final List<Lifter> allLifters = new LifterContainer(app, excludeNotWeighed).getAllPojos();
final List<Lifter> registrationOrderCopy = LifterSorter.registrationOrderCopy(allLifters);
return registrationOrderCopy;
}
/*
* (non-Javadoc)
*
* @see
* org.concordiainternational.competition.spreadsheet.OutputSheet#writeLifter
* (org.concordiainternational.competition.data.Lifter,
* com.extentech.ExtenXLS.WorkSheetHandle,
* org.concordiainternational.competition.data.CategoryLookup, int)
*/
@Override
void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int rownum)
throws CellTypeMismatchException, CellNotFoundException {
// Intentionally empty
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CategoryLookupByName;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.CompetitionSessionLookup;
import org.concordiainternational.competition.data.Lifter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.constraint.IsIncludedIn;
import org.supercsv.cellprocessor.constraint.StrRegEx;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.util.CSVContext;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* Read registration data in CSV format.
* The file is expected to contain a header line, as illustrated:
* <pre>lastName,firstName,gender,club,birthDate,registrationCategory,competitionSession,qualifyingTotal
Lamy,Jean-François,M,C-I,1961,m69,H1,140</pre>
*
* Note that the birthDate field is actually a birth year.
* registrationCategory and competitionSession must be valid entries in the database.
*
* @author Jean-François Lamy
*
*/
public class InputCSVHelper implements InputSheet {
final private Logger logger = LoggerFactory.getLogger(InputCSVHelper.class);
private CompetitionSessionLookup competitionSessionLookup;
private CategoryLookupByName categoryLookupByName;
private CellProcessor[] processors;
InputCSVHelper(HbnSessionManager hbnSessionManager) {
initProcessors(hbnSessionManager);
}
/**
* Configure the cell validators and value converters.
*
* @param hbnSessionManager to access current database.
*/
private void initProcessors(HbnSessionManager hbnSessionManager) {
categoryLookupByName = new CategoryLookupByName(hbnSessionManager);
competitionSessionLookup = new CompetitionSessionLookup(hbnSessionManager);
List<CompetitionSession> sessionList = CompetitionSession.getAll();
Set<Object> sessionNameSet = new HashSet<Object>();
for (CompetitionSession s : sessionList) {
sessionNameSet.add(s.getName());
}
List<Category> categoryList = CategoryLookup.getSharedInstance().getCategories();
Set<Object> categoryNameSet = new HashSet<Object>();
for (Category c : categoryList) {
categoryNameSet.add(c.getName());
}
processors = new CellProcessor[] {
null, // last name, as is.
null, // first name, as is.
new StrRegEx("[mfMF]"), // gender
null, // club, as is.
new StrRegEx("(19|20)[0-9][0-9]", new ParseInt()), // birth year
new Optional(new IsIncludedIn(categoryNameSet, new AsCategory())), // registrationCategory
new IsIncludedIn(sessionNameSet, new AsCompetitionSession()), // sessionName
new Optional(new ParseInt()), // registration total
};
}
@Override
public synchronized List<Lifter> getAllLifters(InputStream is, HbnSessionManager sessionMgr) throws IOException,
CellNotFoundException, WorkSheetNotFoundException {
LinkedList<Lifter> allLifters = new LinkedList<Lifter>() ;
CsvBeanReader cbr = new CsvBeanReader(new InputStreamReader(is), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = cbr.getCSVHeader(true);
Lifter lifter;
while( (lifter = cbr.read(Lifter.class, header, processors)) != null) {
logger.debug("adding {}", toString(lifter));
allLifters.add(lifter);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
cbr.close();
} catch (Exception e) {
// ignored
}
}
return allLifters;
}
@SuppressWarnings("unused")
private class AsCategory extends CellProcessorAdaptor {
public AsCategory() {
super();
}
public AsCategory(CellProcessor next) {
super(next);
}
@Override
public Object execute(Object value, CSVContext context) {
final Category result = categoryLookupByName.lookup((String) value);
return next.execute(result, context);
}
}
@SuppressWarnings("unused")
private class AsCompetitionSession extends CellProcessorAdaptor {
public AsCompetitionSession() {
super();
}
public AsCompetitionSession(CellProcessor next) {
super(next);
}
@Override
public Object execute(Object value, CSVContext context) {
final CompetitionSession result = competitionSessionLookup.lookup((String) value);
return next.execute(result, context);
}
}
/*
* (non-Javadoc)
*/
@Override
public List<Lifter> getGroupLifters(InputStream is, String aGroup, HbnSessionManager session) throws IOException,
CellNotFoundException, WorkSheetNotFoundException {
List<Lifter> groupLifters = new ArrayList<Lifter>();
for (Lifter curLifter : getAllLifters(is, session)) {
if (aGroup.equals(curLifter.getCompetitionSession())) {
groupLifters.add(curLifter);
}
}
return groupLifters;
}
public static String toString(Lifter lifter, boolean includeTimeStamp) {
return InputSheetHelper.toString(lifter,includeTimeStamp);
}
public static String toString(Lifter lifter) {
return toString(lifter, true);
}
}
| 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.spreadsheet;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
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.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellHandle;
import com.extentech.ExtenXLS.CellRange;
import com.extentech.ExtenXLS.FormatHandle;
import com.extentech.ExtenXLS.RowHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy
*
*/
public class IndividualSheet extends ResultSheet {
String templateName = SheetUtils.getCompetition().getResultTemplateFileName();
public IndividualSheet(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
}
/**
*
*/
private static final int CATEGORY_BACKGROUND = FormatHandle.COLOR_GRAY50;
private static final int INDIVIDUAL_COLS = 23;
private Category prevCategory;
private int rownum;
private FormatHandle spacerFormat;
private FormatHandle categoryFormatCenter;
private FormatHandle categoryFormatLeft;
private FormatHandle categoryFormatRight;
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(IndividualSheet.class);
private void writeIndividualLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
Category category = null;
if (WinningOrderComparator.useRegistrationCategory) {
category = lifter.getRegistrationCategory();
} else {
category = lifter.getCategory();
}
if (!category.equals(prevCategory)) {
createCategoryHeading(workSheet, INDIVIDUAL_COLS - 1, category);
}
prevCategory = category;
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne.
workSheet.getCell(rownum, 0).setVal(lifter.getMembership());
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
workSheet.getCell(rownum, 5).setVal((category != null ? category.getName() : null));
workSheet.getCell(rownum, 6).setVal(lifter.getBodyWeight());
workSheet.getCell(rownum, 7).setVal(lifter.getClub());
workSheet.getCell(rownum, 8).setVal(lifter.getBirthDate());
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getSnatch1ActualLift()));
workSheet.getCell(rownum, 10).setVal(SheetUtils.fixValue(lifter.getSnatch2ActualLift()));
workSheet.getCell(rownum, 11).setVal(SheetUtils.fixValue(lifter.getSnatch3ActualLift()));
final Integer snatchRank = lifter.getSnatchRank();
workSheet.getCell(rownum, 13).setVal(SheetUtils.fixRank(snatchRank));
workSheet.getCell(rownum, 14).setVal(SheetUtils.fixValue(lifter.getCleanJerk1ActualLift()));
workSheet.getCell(rownum, 15).setVal(SheetUtils.fixValue(lifter.getCleanJerk2ActualLift()));
workSheet.getCell(rownum, 16).setVal(SheetUtils.fixValue(lifter.getCleanJerk3ActualLift()));
final Integer cleanJerkRank = lifter.getCleanJerkRank();
workSheet.getCell(rownum, 18).setVal(SheetUtils.fixRank(cleanJerkRank));
workSheet.getCell(rownum, 19).setVal(SheetUtils.fixValue(lifter.getTotal()));
final Integer rank = lifter.getRank();
workSheet.getCell(rownum, 20).setVal(SheetUtils.fixRank(rank));
// FIXME: replace this with a lookup or copy correctly formula from spreadsheet.
if (templateName.endsWith("JeuxQuebec.xls")) {
final int bestSnatch = lifter.getBestSnatch();
final int sr = (bestSnatch > 0 ? 58-snatchRank : 0);
final int bestCJ = lifter.getBestCleanJerk();
final int cjr = (bestCJ > 0 ? 58-cleanJerkRank : 0);
final int tr = (bestSnatch > 0 && bestCJ > 0 ? 58 - rank : 0);
if (!lifter.isInvited()) {
workSheet.getCell(rownum, 21).setVal(sr + cjr + tr);
} else {
workSheet.getCell(rownum, 21).setVal(Messages.getString("Lifter.InvitedAbbreviated", CompetitionApplication.getCurrentLocale()));
}
workSheet.getCell(rownum, 22).setVal(lifter.getCategorySinclair());
} else {
workSheet.getCell(rownum, 21).setVal(lifter.getSinclair());
workSheet.getCell(rownum, 22).setVal(lifter.getCategorySinclair());
}
rownum++;
}
/**
* @param lifters
* @param workSheet
* @param gender
* @throws CellTypeMismatchException
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
void writeIndividualSheet(List<Lifter> lifters, WorkSheetHandle workSheet, String gender)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
spacerFormat = defineSpacerFormat(workSheet);
categoryFormatCenter = defineCategoryFormatCenter(workSheet);
categoryFormatLeft = defineCategoryFormatLeft(workSheet);
categoryFormatRight = defineCategoryFormatRight(workSheet);
// fill-in the header.
writeHeader(workSheet);
setFooterLeft(workSheet);
// table heading
// setRepeatedLinesFormat(workSheet);
// process data sheet
rownum = InputSheetHelper.START_ROW;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeIndividualLifter(curLifter, workSheet, categoryLookup);
}
}
removeLastRowIfInserting(workSheet, rownum);
setPrintArea(workSheet, InputSheetHelper.START_ROW - 2, 0, rownum - 1, INDIVIDUAL_COLS - 1);
}
/**
* @param workSheet
*/
@SuppressWarnings("unused")
private void setRepeatedLinesFormat(WorkSheetHandle workSheet) {
int[] rangeCoords = new int[] { 5, 0, 6, INDIVIDUAL_COLS - 1 };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setBackgroundColor(FormatHandle.COLOR_GRAY25);
fh.addCellRange(cellRange);
} catch (Exception e) {
}
}
/**
* @param workSheet
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
private int createCategoryHeading(WorkSheetHandle workSheet, int nbCols, Category category)
throws CellNotFoundException, RowNotFoundException {
workSheet.insertRow(rownum, true);
RowHandle row = workSheet.getRow(rownum);
row.setHeight(200);
for (int i = 0; i <= nbCols; i++) {
final CellHandle cell = workSheet.getCell(rownum, i);
cell.setFormatHandle(spacerFormat);
}
rownum++;
workSheet.insertRow(rownum, true);
CellHandle cell = workSheet.getCell(rownum, 0);
// create a bilingual category label.
String catCode = "CategoryLong." + category.getName();
// fix category code to be a legal property name.
if (catCode.contains(">")) {
catCode = catCode.replace(">", "gt");
}
String name = Messages.getString(catCode, Locale.FRENCH) + " - " + Messages.getString(catCode, Locale.ENGLISH);
cell.setVal(name);
int[] rangeCoords = new int[] { rownum, 0, rownum, nbCols };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
cellRange.mergeCells(true);
categoryFormatCenter.addCellRange(cellRange);
} catch (Exception e) {
}
cell = workSheet.getCell(rownum, 0);
cell.setFormatHandle(categoryFormatLeft);
cell = workSheet.getCell(rownum, nbCols);
cell.setFormatHandle(categoryFormatRight);
rownum++;
return rownum;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineSpacerFormat(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderTopColor(FormatHandle.COLOR_BLACK);
fh.setBorderBottomColor(FormatHandle.COLOR_BLACK);
fh.setBorderLeftColor(FormatHandle.COLOR_WHITE);
fh.setBorderRightColor(FormatHandle.COLOR_WHITE);
fh.setBackgroundColor(FormatHandle.COLOR_WHITE);
fh.setFontColor(FormatHandle.COLOR_WHITE);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatCenter(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setBorderLeftColor(FormatHandle.COLOR_WHITE);
fh.setBorderRightColor(FormatHandle.COLOR_WHITE);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatRight(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setBorderLeftColor(CATEGORY_BACKGROUND);
fh.setBorderRightColor(FormatHandle.COLOR_BLACK);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatLeft(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setFontWeight(FormatHandle.BOLD);
fh.setFontColor(FormatHandle.COLOR_WHITE);
fh.setBorderLeftColor(FormatHandle.COLOR_BLACK);
fh.setBorderRightColor(CATEGORY_BACKGROUND);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param fh
*/
private void defineCategoryBackground(FormatHandle fh) {
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderTopColor(FormatHandle.COLOR_BLACK);
fh.setBorderBottomColor(FormatHandle.COLOR_BLACK);
fh.setBackgroundColor(CATEGORY_BACKGROUND);
fh.setFontColor(FormatHandle.COLOR_WHITE);
}
@Override
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
setCellValue(workSheet, "K1", competition.getCompetitionName()); //$NON-NLS-1$
setCellValue(workSheet, "K2", competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) setCellValue(workSheet, "K3", SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
setCellValue(workSheet, "T2", competition.getCompetitionCity()); //$NON-NLS-1$
setCellValue(workSheet, "T3", competition.getCompetitionOrganizer()); //$NON-NLS-1$
writeGroup(workSheet);
}
}
/**
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
*/
@Override
protected void writeGroup(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
if (competitionSession != null) {
setCellValue(workSheet, "K4", competitionSession.getName());
} else {
setCellValue(workSheet, "J4", "");// clear the cell;
setCellValue(workSheet, "K4", "");// clear the cell;
}
}
}
| 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.spreadsheet;
import java.util.List;
import java.util.TreeSet;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy
*
*/
public class TeamSheet extends ResultSheet {
public TeamSheet(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
}
private int lifterRankWithinTeam;
private String previousClub;
private String previousGender;
private LifterSorter lifterSorter = new LifterSorter();
private static final int CLUB_OFFSET = 6; // first row for clubs (starting
// at 0)
private static final int LIFTER_OFFSET = 6; // first row for lifters
// (starting at 0)
/**
* @param curLifter
* @param workSheet
* @param categoryLookup1
* @param rankingType
* @param i
* @throws CellNotFoundException
* @throws CellTypeMismatchException
*/
private void writeTeamLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1,
int lifterIndex, Ranking rankingType) throws CellTypeMismatchException, CellNotFoundException {
lifterIndex = lifterIndex + LIFTER_OFFSET;
final String club = lifter.getClub();
final String gender = lifter.getGender();
if (!club.equals(previousClub) || !gender.equals(previousGender)) {
lifterRankWithinTeam = 1;
}
workSheet.add(club, lifterIndex, 0).setVal(club);
workSheet.add(lifter.getLastName(), lifterIndex, 1);
workSheet.add(lifter.getFirstName(), lifterIndex, 2);
workSheet.add(gender, lifterIndex, 3);
workSheet.add(lifter.getBodyWeight(), lifterIndex, 4);
logger.debug("lifter {} lifterIndex {}", lifter.getLastName(),lifterIndex);
workSheet.add(club + "_" + gender, lifterIndex, 5);
switch (rankingType) {
case SNATCH: {
workSheet.add(lifter.getBestSnatch(), lifterIndex, 6);
break;
}
case CLEANJERK: {
workSheet.add(lifter.getBestCleanJerk(), lifterIndex, 6);
break;
}
case TOTAL: {
workSheet.add(lifter.getTotal(), lifterIndex, 6);
break;
}
case CUSTOM: {
workSheet.add(lifter.getCustomScore(), lifterIndex, 6);
break;
}
}
if (lifter.isInvited()) {
final String message = Messages.getString(
"ResultSheet.InvitedAbbreviation", CompetitionApplication.getCurrentLocale());
workSheet.add(message, lifterIndex, 6); //$NON-NLS-1$
//workSheet.add((Integer)0, lifterIndex, 9);
} else {
final Integer rank = lifterSorter .getRank(lifter, rankingType);
if (rank <= 0) {
workSheet.add(rank, lifterIndex, 7);
// rank within team is computed by the Excel spreadsheet through
// a formula.
// this allows on-site changes to ranks.
// workSheet.add(0,lifterIndex,9);
} else {
workSheet.add(rank, lifterIndex, 7);
// rank within team is computed by the Excel spreadsheet through
// a formula.
// this allows on-site changes to ranks.
// workSheet.add(lifterRankWithinTeam,lifterIndex,9);
lifterRankWithinTeam++;
}
}
previousClub = club;
previousGender = gender;
}
/**
* @param lifters
* @param workSheet
* @param rankingType
* @param clubs
* @param gender
* @throws Exception
*/
void writeTeamSheet(List<Lifter> lifters, WorkSheetHandle workSheet, Ranking rankingType, TreeSet<String> clubs,
String gender) throws Exception {
int i = 0;
previousGender = null;
previousClub = null;
lifterRankWithinTeam = 0;
setFooterLeft(workSheet);
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeTeamLifter(curLifter, workSheet, categoryLookup, i++, rankingType);
}
}
writeClubs(workSheet, clubs);
}
/**
* @param clubs
* @throws Exception
*/
private void writeClubs(WorkSheetHandle workSheet, TreeSet<String> clubs) throws Exception {
int rowNum = CLUB_OFFSET;
int lastCol = 16;
try {
// check whether the template has two columns for the number of
// athletes
workSheet.getCell(rowNum - 1, lastCol);
} catch (CellNotFoundException cnf) {
lastCol = 15;
}
for (String club : clubs) {
workSheet.add(club, rowNum, 12);
rowNum++;
}
setPrintArea(workSheet, CLUB_OFFSET - 1, 12, rowNum - 1, lastCol);
}
public void writeTeamSheetCombined(List<Lifter> lifters, WorkSheetHandle workSheet, TreeSet<String> clubs, String gender) throws Exception {
setFooterLeft(workSheet);
// logger.debug("writing snatch");
previousGender = null;
previousClub = null;
lifterRankWithinTeam = 0;
int i = 0;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeTeamLifter(curLifter, workSheet, categoryLookup, i++, Ranking.SNATCH);
}
}
// logger.debug("writing clean-and-jerk");
previousGender = null;
previousClub = null;
lifterRankWithinTeam = 0;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeTeamLifter(curLifter, workSheet, categoryLookup, i++, Ranking.CLEANJERK);
}
}
// logger.debug("writing total");
previousGender = null;
previousClub = null;
lifterRankWithinTeam = 0;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeTeamLifter(curLifter, workSheet, categoryLookup, i++, Ranking.TOTAL);
}
}
writeClubs(workSheet, clubs);
}
public int getLifterRankWithinTeam() {
return lifterRankWithinTeam;
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.concordiainternational.competition.data.Lifter;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
public interface InputSheet {
public abstract List<Lifter> getAllLifters(InputStream is, HbnSessionManager session) throws CellNotFoundException,
IOException, WorkSheetNotFoundException, InterruptedException, Throwable;
public abstract List<Lifter> getGroupLifters(InputStream is, String aGroup, HbnSessionManager session)
throws CellNotFoundException, IOException, WorkSheetNotFoundException, InterruptedException, Throwable;
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
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.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
/**
* The Jury sheet is used when the Jury rates officials for promotion.
*
* @author jflamy
*
*/
public class JurySheet extends OutputSheet {
protected static final String TEMPLATE_XLS = "/JurySheetTemplate.xls"; //$NON-NLS-1$
private static final int START_ROW = 7;
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(JurySheet.class);
public JurySheet() {
}
public JurySheet(CategoryLookup categoryLookup, CompetitionApplication app, CompetitionSession competitionSession) {
super(categoryLookup, app, competitionSession);
}
/**
* @see org.concordiainternational.competition.spreadsheet.OutputSheet#writeLifter(org.concordiainternational.competition.data.Lifter,
* com.extentech.ExtenXLS.WorkSheetHandle,
* org.concordiainternational.competition.data.CategoryLookup, int)
*/
@Override
public void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int rownum)
throws CellTypeMismatchException, CellNotFoundException {
rownum = rownum + START_ROW;
final String lastName = lifter.getLastName();
workSheet.getCell(rownum, 1).setVal(lastName != null ? lastName : ""); //$NON-NLS-1$
final String firstName = lifter.getFirstName();
workSheet.getCell(rownum, 2).setVal(firstName != null ? firstName : ""); //$NON-NLS-1$
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(TEMPLATE_XLS);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + TEMPLATE_XLS);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
return LifterSorter.displayOrderCopy(new LifterContainer(app, excludeNotWeighed).getAllPojos());
}
private String group;
/*
* (non-Javadoc)
*
* @see org.concordia_international.reader.ResultSheet#getGroup()
*/
public String getGroup() {
return this.group;
}
/*
* (non-Javadoc)
*
* @see
* org.concordia_international.reader.ResultSheet#setGroup(java.lang.String)
*/
public void setGroup(String group) {
this.group = group;
}
@Override
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = app.getHbnSession().createCriteria(Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
if (group != null) workSheet.getCell("D6").setVal(group); //$NON-NLS-1$
workSheet.getCell("C2").setVal(competition.getCompetitionName()); //$NON-NLS-1$
workSheet.getCell("C3").setVal(competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) workSheet.getCell("I3").setVal(SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
}
}
@Override
protected void removeLastRowIfInserting(WorkSheetHandle workSheet, int i) throws RowNotFoundException {
// Do nothing; we do not insert rows, so we don't have to hide an
// extra one inserted prior to writing data
}
}
| 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.spreadsheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Result sheet, with team rankings
*
* @author jflamy
*
*/
public class JXLSCompetitionBook extends JXLSWorkbookStreamSource {
private static final long serialVersionUID = 1L;
final private static int TEAMSHEET_FIRST_ROW = 5;
@SuppressWarnings("unused")
private Logger logger = LoggerFactory.getLogger(JXLSCompetitionBook.class);
public JXLSCompetitionBook(){
// by default, we exclude athletes who did not weigh in.
super(true);
}
public JXLSCompetitionBook(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
@Override
public InputStream getTemplate() throws IOException {
String resultTemplateFileName = SheetUtils.getCompetition().getResultTemplateFileName();
File templateFile = new File(resultTemplateFileName);
if (!templateFile.exists()) {
// can't happen unless system is misconfigured.
throw new IOException("resource not found: " + resultTemplateFileName); //$NON-NLS-1$
}
FileInputStream resourceAsStream = new FileInputStream(templateFile);
return resourceAsStream;
}
@SuppressWarnings("unchecked")
@Override
public void init() {
super.init();
final Session hbnSession = CompetitionApplication.getCurrent().getHbnSession();
List<Competition> competitionList = hbnSession.createCriteria(Competition.class).list();
Competition competition = competitionList.get(0);
getReportingBeans().put("competition",competition);
}
@Override
protected void getSortedLifters() {
HashMap<String, Object> reportingBeans = getReportingBeans();
this.lifters = new LifterContainer(CompetitionApplication.getCurrent(),isExcludeNotWeighed()).getAllPojos();
if (lifters.isEmpty()) {
// prevent outputting silliness.
throw new RuntimeException(Messages.getString(
"OutputSheet.EmptySpreadsheet", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
// extract club lists
TreeSet<String> clubs = new TreeSet<String>();
for (Lifter curLifter : lifters) {
clubs.add(curLifter.getClub());
}
reportingBeans.put("clubs",clubs);
final LifterSorter lifterSorter = new LifterSorter();
List<Lifter> sortedLifters;
List<Lifter> sortedMen = null;
List<Lifter> sortedWomen = null;
sortedLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.SNATCH);
lifterSorter.assignCategoryRanks(sortedLifters, Ranking.SNATCH);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mSn",sortedMen);
reportingBeans.put("wSn",sortedWomen);
sortedLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.CLEANJERK);
lifterSorter.assignCategoryRanks(sortedLifters, Ranking.CLEANJERK);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mCJ",sortedMen);
reportingBeans.put("wCJ",sortedWomen);
sortedLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.TOTAL);
lifterSorter.assignCategoryRanks(sortedLifters, Ranking.TOTAL);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mTot",sortedMen);
reportingBeans.put("wTot",sortedWomen);
sortedLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.SINCLAIR);
lifterSorter.assignSinclairRanksAndPoints(sortedLifters, Ranking.SINCLAIR);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mSinclair",sortedMen);
reportingBeans.put("wSinclair",sortedWomen);
// team-oriented rankings. These put all the lifters from the same team together,
// sorted from best to worst, so that the top "n" can be given points
sortedLifters = LifterSorter.teamRankingOrderCopy(lifters, Ranking.CUSTOM);
lifterSorter.assignCategoryRanks(sortedLifters, Ranking.CUSTOM);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mCustom",sortedMen);
reportingBeans.put("wCustom",sortedWomen);
sortedLifters = LifterSorter.teamRankingOrderCopy(lifters, Ranking.COMBINED);
lifterSorter.assignCategoryRanks(sortedLifters, Ranking.COMBINED);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mCombined",sortedMen);
reportingBeans.put("wCombined",sortedWomen);
LifterSorter.teamRankingOrder(sortedLifters, Ranking.TOTAL);
sortedMen = new ArrayList<Lifter>(sortedLifters.size());
sortedWomen = new ArrayList<Lifter>(sortedLifters.size());
splitByGender(sortedLifters, sortedMen, sortedWomen);
reportingBeans.put("mTeam",sortedMen);
reportingBeans.put("wTeam",sortedWomen);
reportingBeans.put("mwTeam",sortedLifters);
}
@Override
protected void configureTransformer(XLSTransformer transformer) {
super.configureTransformer(transformer);
transformer.markAsFixedSizeCollection("clubs");
transformer.markAsFixedSizeCollection("mTeam");
transformer.markAsFixedSizeCollection("wTeam");
transformer.markAsFixedSizeCollection("mwTeam");
transformer.markAsFixedSizeCollection("mCombined");
transformer.markAsFixedSizeCollection("wCombined");
transformer.markAsFixedSizeCollection("mCustom");
transformer.markAsFixedSizeCollection("wCustom");
}
/* team result sheets need columns hidden, print area fixed
* @see org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource#postProcess(org.apache.poi.ss.usermodel.Workbook)
*/
@Override
protected void postProcess(Workbook workbook) {
super.postProcess(workbook);
@SuppressWarnings("unchecked")
int nbClubs = ((Set<String>) getReportingBeans().get("clubs")).size();
setTeamSheetPrintArea(workbook, "MT", nbClubs);
setTeamSheetPrintArea(workbook, "WT", nbClubs);
setTeamSheetPrintArea(workbook, "MWT", nbClubs);
setTeamSheetPrintArea(workbook, "MXT", nbClubs);
setTeamSheetPrintArea(workbook, "WXT", nbClubs);
setTeamSheetPrintArea(workbook, "MCT", nbClubs);
setTeamSheetPrintArea(workbook, "WCT", nbClubs);
translateSheets(workbook);
workbook.setForceFormulaRecalculation(true);
}
private void setTeamSheetPrintArea(Workbook workbook, String sheetName, int nbClubs) {
int sheetIndex = workbook.getSheetIndex(sheetName);
if (sheetIndex >= 0) {
workbook.setPrintArea(sheetIndex, 0, 4, TEAMSHEET_FIRST_ROW, TEAMSHEET_FIRST_ROW+nbClubs);
}
}
private void translateSheets(Workbook workbook) {
//TODO: also set headers and footers
int nbSheets = workbook.getNumberOfSheets();
for (int sheetIndex = 0; sheetIndex < nbSheets; sheetIndex++) {
Sheet curSheet = workbook.getSheetAt(sheetIndex);
String sheetName = curSheet.getSheetName();
workbook.setSheetName(sheetIndex,Messages.getString("CompetitionBook."+sheetName, CompetitionApplication.getCurrentLocale()));
String leftHeader = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_LeftHeader", CompetitionApplication.getCurrentLocale());
if (leftHeader != null) curSheet.getHeader().setLeft(leftHeader);
String centerHeader = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_CenterHeader", CompetitionApplication.getCurrentLocale());
if (centerHeader != null) curSheet.getHeader().setCenter(centerHeader);
String rightHeader = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_RightHeader", CompetitionApplication.getCurrentLocale());
if (rightHeader != null) curSheet.getHeader().setRight(rightHeader);
String leftFooter = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_LeftFooter", CompetitionApplication.getCurrentLocale());
if (leftFooter != null) curSheet.getFooter().setLeft(leftFooter);
String centerFooter = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_CenterFooter", CompetitionApplication.getCurrentLocale());
if (centerFooter != null) curSheet.getFooter().setCenter(centerFooter);
String rightFooter = Messages.getStringNullIfMissing("CompetitionBook."+sheetName+"_RightFooter", CompetitionApplication.getCurrentLocale());
if (rightFooter != null) curSheet.getFooter().setRight(rightFooter);
}
}
private void splitByGender(List<Lifter> sortedLifters,
List<Lifter> sortedMen, List<Lifter> sortedWomen) {
for (Lifter l: sortedLifters) {
if ("m".equalsIgnoreCase(l.getGender())) {
sortedMen.add(l);
} else {
sortedWomen.add(l);
}
}
}
}
| 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.spreadsheet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.generators.WeightFormatter;
import org.hibernate.HibernateException;
/**
* @author jflamy
*
*/
public class SheetUtils {
private static Competition competition;
private static SimpleDateFormat dateFormat = new SimpleDateFormat(Messages.getString(
"OutputSheet.DateFormat", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
static public String fixRank(Integer rank) {
if (rank == null || rank == 0) {
return ""; //$NON-NLS-1$
} else if (rank > 0) {
return Integer.toString(rank);
} else return Messages.getString("ResultSheet.InvitedAbbreviation", CompetitionApplication.getCurrentLocale()); //$NON-NLS-1$
}
static public Object fixValue(String value) {
try {
return WeightFormatter.parseInt(value);
} catch (NumberFormatException e) {
return "-"; //$NON-NLS-1$
}
}
static public Integer fixValue(Integer val) {
return val; // do nothing
}
/**
* @param competitionDate
* @return
*/
static Object getShortDate(Date competitionDate) {
return dateFormat.format(competitionDate);
}
/**
* @return
* @throws HibernateException
*/
@SuppressWarnings("unchecked")
static Competition getCompetition() throws HibernateException {
if (competition == null) {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) competition = competitions.get(0);
}
return competition;
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.HashMap;
import java.util.List;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.vaadin.terminal.StreamResource;
/**
* Encapsulate a spreadsheet as a StreamSource so that it can be used as a
* source of data when the user clicks on a link. This class converts the output
* stream produced by the
* {@link OutputSheet#writeWorkBook(WorkBookHandle, OutputStream)} method to an
* input stream that the vaadin framework can consume.
*/
@SuppressWarnings("serial")
public abstract class JXLSWorkbookStreamSource implements StreamResource.StreamSource {
private final static Logger logger = LoggerFactory.getLogger(JXLSWorkbookStreamSource.class);
protected CategoryLookup categoryLookup;
protected CompetitionApplication app;
protected List<Lifter> lifters;
private HashMap<String, Object> reportingBeans;
private boolean excludeNotWeighed;
public JXLSWorkbookStreamSource(boolean excludeNotWeighed) {
this.excludeNotWeighed = excludeNotWeighed;
this.app = CompetitionApplication.getCurrent();
init();
}
protected void init() {
setReportingBeans(new HashMap<String,Object>());
getSortedLifters();
if (lifters != null) {
getReportingBeans().put("lifters",lifters);
}
getReportingBeans().put("masters",Competition.isMasters());
}
/**
* Return lifters as they should be sorted.
*/
abstract protected void getSortedLifters();
@Override
public InputStream getStream() {
try {
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(new Runnable() {
@Override
public void run() {
try {
XLSTransformer transformer = new XLSTransformer();
configureTransformer(transformer);
HashMap<String, Object> reportingBeans2 = getReportingBeans();
Workbook workbook = transformer.transformXLS(getTemplate(),reportingBeans2);
postProcess(workbook);
workbook.write(out);
} catch (IOException e) {
// ignore
} catch (Throwable e) {
LoggerUtils.logException(logger, e);
throw new RuntimeException(e);
}
}
}).start();
return in;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
protected void configureTransformer(XLSTransformer transformer) {
// do nothing, to be overridden as needed,
}
protected void postProcess(Workbook workbook) {
// do nothing, to be overridden as needed,
}
/**
* Erase a pair of adjoining cells.
* @param workbook
* @param rownum
* @param cellnum
*/
public void zapCellPair(Workbook workbook, int rownum, int cellnum) {
Row row = workbook.getSheetAt(0).getRow(rownum);
final Cell cellLeft = row.getCell(cellnum);
cellLeft.setCellValue("");
row.getCell(19).setCellValue("");
CellStyle blank = workbook.createCellStyle();
blank.setBorderBottom(CellStyle.BORDER_NONE);
row.getCell(cellnum+1).setCellStyle(blank);
}
public InputStream getTemplate() throws IOException {
String templateName = "/competitionBook/CompetitionBook_Total_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("Resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
public int size() {
return lifters.size();
}
public List<Lifter> getLifters() {
return lifters;
}
public void setReportingBeans(HashMap<String, Object> jXLSBeans) {
this.reportingBeans = jXLSBeans;
}
public HashMap<String, Object> getReportingBeans() {
return reportingBeans;
}
public void setExcludeNotWeighed(boolean excludeNotWeighed) {
this.excludeNotWeighed = excludeNotWeighed;
}
public boolean isExcludeNotWeighed() {
return excludeNotWeighed;
}
}
| 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.spreadsheet;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import com.vaadin.terminal.StreamResource;
/**
* Encapsulate a PDF as a StreamSource so that it can be used as a source of
* data when the user clicks on a link. This class converts the output stream
* produced by the writePDF method to an input stream that the Vaadin framework
* can consume.
*/
@SuppressWarnings("serial")
public class PDFStreamSource implements StreamResource.StreamSource {
@Override
public InputStream getStream() {
try {
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(new Runnable() {
@Override
public void run() {
try {
writePdf(out);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}).start();
return in;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
protected void writePdf(PipedOutputStream out) {
// call PDF library to write on "out"
}
}
| 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.spreadsheet;
import java.util.Date;
import java.util.List;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.lifterSort.WinningOrderComparator;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellHandle;
import com.extentech.ExtenXLS.CellRange;
import com.extentech.ExtenXLS.FormatHandle;
import com.extentech.ExtenXLS.RowHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy
*
*/
public class MastersIndividualSheet extends IndividualSheet {
public MastersIndividualSheet(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
}
private static final int AGEGROUP_BACKGROUND = FormatHandle.COLOR_BLACK;
private static final int CATEGORY_BACKGROUND = FormatHandle.COLOR_GRAY50;
private static final int INDIVIDUAL_COLS = 23;
private Category prevCategory;
private String prevAgeGroup;
private int rownum;
private FormatHandle spacerFormat;
private FormatHandle categoryFormatCenter;
private FormatHandle categoryFormatLeft;
private FormatHandle categoryFormatRight;
@SuppressWarnings("unused")
private FormatHandle ageGroupFormat;
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(MastersIndividualSheet.class);
private void writeIndividualLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
Category category = null;
String ageGroup = "";
// create an age group boundary if needed
ageGroup = lifter.getMastersAgeGroup();
// logger.debug("lifter {} agegroup {}",lifter,ageGroup);
boolean newHeadingRequired = false;
if (!ageGroup.equals(prevAgeGroup)) {
createAgeGroupHeading(workSheet, INDIVIDUAL_COLS - 1, lifter.getMastersGenderAgeGroupInterval());
// logger.debug("different");
newHeadingRequired = true;
}
prevAgeGroup = ageGroup;
// create a category header if needed
if (WinningOrderComparator.useRegistrationCategory) {
category = lifter.getRegistrationCategory();
} else {
category = lifter.getCategory();
}
if (!category.equals(prevCategory) || newHeadingRequired) {
createCategoryHeading(workSheet, INDIVIDUAL_COLS - 1, category, lifter);
}
prevCategory = category;
// add the lifter
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne.
workSheet.getCell(rownum, 0).setVal(lifter.getMembership());
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
workSheet.getCell(rownum, 5).setVal((category != null ? category.getName() : null));
workSheet.getCell(rownum, 6).setVal(lifter.getBodyWeight());
workSheet.getCell(rownum, 7).setVal(lifter.getClub());
workSheet.getCell(rownum, 8).setVal(lifter.getBirthDate());
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getSnatch1ActualLift()));
workSheet.getCell(rownum, 10).setVal(SheetUtils.fixValue(lifter.getSnatch2ActualLift()));
workSheet.getCell(rownum, 11).setVal(SheetUtils.fixValue(lifter.getSnatch3ActualLift()));
workSheet.getCell(rownum, 13).setVal(SheetUtils.fixRank(lifter.getSnatchRank()));
workSheet.getCell(rownum, 14).setVal(SheetUtils.fixValue(lifter.getCleanJerk1ActualLift()));
workSheet.getCell(rownum, 15).setVal(SheetUtils.fixValue(lifter.getCleanJerk2ActualLift()));
workSheet.getCell(rownum, 16).setVal(SheetUtils.fixValue(lifter.getCleanJerk3ActualLift()));
workSheet.getCell(rownum, 18).setVal(SheetUtils.fixRank(lifter.getCleanJerkRank()));
workSheet.getCell(rownum, 19).setVal(SheetUtils.fixValue(lifter.getTotal()));
workSheet.getCell(rownum, 20).setVal(SheetUtils.fixRank(lifter.getRank()));
workSheet.getCell(rownum, 21).setVal(lifter.getSinclair());
workSheet.getCell(rownum, INDIVIDUAL_COLS - 1).setVal(lifter.getSMM());
rownum++;
}
/**
* @param lifters
* @param workSheet
* @param gender
* @throws CellTypeMismatchException
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
@Override
void writeIndividualSheet(List<Lifter> lifters, WorkSheetHandle workSheet, String gender)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
spacerFormat = defineSpacerFormat(workSheet);
categoryFormatCenter = defineCategoryFormatCenter(workSheet);
categoryFormatLeft = defineCategoryFormatLeft(workSheet);
categoryFormatRight = defineCategoryFormatRight(workSheet);
ageGroupFormat = defineAgeGroupFormat(workSheet);
// fill-in the header.
writeHeader(workSheet);
setFooterLeft(workSheet);
// table heading
// setRepeatedLinesFormat(workSheet);
// process data sheet
rownum = InputSheetHelper.START_ROW;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeIndividualLifter(curLifter, workSheet, categoryLookup);
}
}
removeLastRowIfInserting(workSheet, rownum);
setPrintArea(workSheet, InputSheetHelper.START_ROW - 2, 0, rownum - 1, INDIVIDUAL_COLS - 1);
}
/**
* @param workSheet
*/
@SuppressWarnings("unused")
private void setRepeatedLinesFormat(WorkSheetHandle workSheet) {
int[] rangeCoords = new int[] { 5, 0, 6, INDIVIDUAL_COLS - 1 };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setBackgroundColor(FormatHandle.COLOR_GRAY25);
fh.addCellRange(cellRange);
} catch (Exception e) {
}
}
/**
* @param workSheet
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
private int createAgeGroupHeading(WorkSheetHandle workSheet, int nbCols, String ageGroup)
throws CellNotFoundException, RowNotFoundException {
return rownum;
/*
* addSpacer(workSheet, nbCols);
*
* workSheet.insertRow(rownum,true); CellHandle cell =
* workSheet.getCell(rownum, 0);
*
* cell.setVal(ageGroup); // // create a bilingual age group label. //
* String ageGroupCode = "AgeGroup."+ageGroup; // // fix category code
* to be a legal property name. // if (ageGroupCode.contains("+")) { //
* ageGroupCode = ageGroupCode.replace("+", "plus"); // } // String name
* = // Messages.getString(ageGroupCode,Locale.FRENCH) + " - " + //
* Messages.getString(ageGroupCode,Locale.ENGLISH); //
* cell.setVal(name);
*
* int[] rangeCoords = new int[]{rownum,0,rownum,nbCols}; try {
* CellRange cellRange = new CellRange(workSheet,rangeCoords);
* cellRange.mergeCells(true); ageGroupFormat.addCellRange(cellRange); }
* catch (Exception e) {}
*
*
* rownum++; return rownum;
*/
}
/**
* @param workSheet
* @param nbCols
* @throws RowNotFoundException
*/
private void addSpacer(WorkSheetHandle workSheet, int nbCols) throws RowNotFoundException {
try {
workSheet.insertRow(rownum, true);
} catch (Exception e1) {
}
RowHandle row = workSheet.getRow(rownum);
row.setHeight(200);
for (int i = 0; i <= nbCols; i++) {
final CellHandle cell = workSheet.add("", rownum, i);
cell.setFormatHandle(spacerFormat);
}
rownum++;
}
/**
* @param workSheet
* @param nbCols
* @param category
* @param lifter
* @return
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
private int createCategoryHeading(WorkSheetHandle workSheet, int nbCols, Category category, Lifter lifter)
throws CellNotFoundException, RowNotFoundException {
addSpacer(workSheet, nbCols);
workSheet.insertRow(rownum, true);
CellHandle cell = workSheet.getCell(rownum, 0);
// // create a bilingual category label.
// String catCode = "CategoryLong."+category.getName();
// // fix category code to be a legal property name.
// if (catCode.contains(">")) {
// catCode = catCode.replace(">", "gt");
// }
// String name =
// Messages.getString(catCode,Locale.FRENCH) + " - " +
// Messages.getString(catCode,Locale.ENGLISH);
// cell.setVal(name);
cell.setVal(lifter.getMastersGenderAgeGroupInterval() + " " + lifter.getShortCategory());
int[] rangeCoords = new int[] { rownum, 0, rownum, nbCols };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
cellRange.mergeCells(true);
categoryFormatCenter.addCellRange(cellRange);
} catch (Exception e) {
}
cell = workSheet.getCell(rownum, 0);
cell.setFormatHandle(categoryFormatLeft);
cell = workSheet.getCell(rownum, nbCols);
cell.setFormatHandle(categoryFormatRight);
rownum++;
return rownum;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineSpacerFormat(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderTopColor(FormatHandle.COLOR_BLACK);
fh.setBorderBottomColor(FormatHandle.COLOR_BLACK);
fh.setBorderLeftColor(FormatHandle.COLOR_WHITE);
fh.setBorderRightColor(FormatHandle.COLOR_WHITE);
fh.setBackgroundColor(FormatHandle.COLOR_WHITE);
fh.setFontColor(FormatHandle.COLOR_WHITE);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineAgeGroupFormat(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderColor(FormatHandle.COLOR_BLACK);
fh.setBackgroundColor(AGEGROUP_BACKGROUND);
fh.setFontColor(FormatHandle.COLOR_WHITE);
fh.setBorderLeftColor(FormatHandle.COLOR_BLACK);
fh.setBorderRightColor(FormatHandle.COLOR_BLACK);
fh.setBorderLineStyle(FormatHandle.BORDER_THIN);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatCenter(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setBorderLeftColor(FormatHandle.COLOR_WHITE);
fh.setBorderRightColor(FormatHandle.COLOR_WHITE);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatRight(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setBorderLeftColor(CATEGORY_BACKGROUND);
fh.setBorderRightColor(FormatHandle.COLOR_BLACK);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineCategoryFormatLeft(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineCategoryBackground(fh);
fh.setFontWeight(FormatHandle.BOLD);
fh.setFontColor(FormatHandle.COLOR_WHITE);
fh.setBorderLeftColor(FormatHandle.COLOR_BLACK);
fh.setBorderRightColor(CATEGORY_BACKGROUND);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param fh
*/
private void defineCategoryBackground(FormatHandle fh) {
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderTopColor(FormatHandle.COLOR_BLACK);
fh.setBorderBottomColor(FormatHandle.COLOR_BLACK);
fh.setBackgroundColor(CATEGORY_BACKGROUND);
fh.setFontColor(FormatHandle.COLOR_WHITE);
}
@Override
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
setCellValue(workSheet, "K1", competition.getCompetitionName()); //$NON-NLS-1$
setCellValue(workSheet, "K2", competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) setCellValue(workSheet, "K3", SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
setCellValue(workSheet, "T2", competition.getCompetitionCity()); //$NON-NLS-1$
setCellValue(workSheet, "T3", competition.getCompetitionOrganizer()); //$NON-NLS-1$
writeGroup(workSheet);
}
}
/**
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
*/
@Override
protected void writeGroup(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
if (competitionSession != null) {
setCellValue(workSheet, "K4", competitionSession.getName());
} else {
setCellValue(workSheet, "J4", "");// clear the cell;
setCellValue(workSheet, "K4", "");// clear the cell;
}
}
}
| 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.spreadsheet;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.vaadin.terminal.StreamResource;
/**
* Encapsulate a spreadsheet as a StreamSource so that it can be used as a
* source of data when the user clicks on a link. This class converts the output
* stream produced by the
* {@link OutputSheet#writeWorkBook(WorkBookHandle, OutputStream)} method to an
* input stream that the vaadin framework can consume.
*/
@SuppressWarnings("serial")
public class OutputSheetStreamSource<T extends OutputSheet> implements StreamResource.StreamSource {
private final static Logger logger = LoggerFactory.getLogger(OutputSheetStreamSource.class);
private final T outputSheet;
private List<Lifter> lifters;
public OutputSheetStreamSource(Class<T> parameterizedClass, CompetitionApplication app, boolean excludeNotWeighed) {
CategoryLookup categoryLookup = CategoryLookup.getSharedInstance(app);
try {
this.outputSheet = parameterizedClass.newInstance();
} catch (Exception t) {
throw new RuntimeException(t);
}
outputSheet.init(categoryLookup, app, app.getCurrentCompetitionSession());
this.lifters = outputSheet.getLifters(excludeNotWeighed);
}
@Override
public InputStream getStream() {
try {
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
logger.debug("starting getStream"); //$NON-NLS-1$
new Thread(new Runnable() {
@Override
public void run() {
try {
outputSheet.writeLifters(lifters, out);
} catch (Throwable e) {
LoggerUtils.logException(logger, e);
throw new RuntimeException(e);
}
}
}).start();
logger.debug("returning inputStream"); //$NON-NLS-1$
return in;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public int size() {
return lifters.size();
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* Result sheet, with team rankings
*
* @author jflamy
*
*/
public class MastersGroupResults extends ResultSheet {
public MastersGroupResults(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
this.hbnSessionManager = hbnSessionManager;
}
protected static String templateXls = "/ResultSheetTemplate_Masters.xls"; //$NON-NLS-1$
private Logger logger = LoggerFactory.getLogger(MastersGroupResults.class);
Competition competition;
private HbnSessionManager hbnSessionManager;
@Override
public void writeLifters(List<Lifter> lifters, OutputStream out) throws CellTypeMismatchException,
CellNotFoundException, RowNotFoundException, IOException, WorkSheetNotFoundException {
WorkBookHandle workBookHandle = null;
try {
if (lifters.isEmpty()) {
// should have been dealt with earlier
// this prevents a loop in the spreadsheet processing if it has
// not.
throw new RuntimeException(Messages.getString(
"OutputSheet.EmptySpreadsheet", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
// extract club lists
TreeSet<String> clubs = new TreeSet<String>();
for (Lifter curLifter : lifters) {
clubs.add(curLifter.getClub());
}
// produce point rankings.
List<Lifter> teamRankingLifters;
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.TOTAL);
LifterSorter.assignMedals(teamRankingLifters);
// extract Canada lifters
List<Lifter> canadaLifters = new ArrayList<Lifter>();
for (Lifter curLifter : lifters) {
if ("CAN".equals(curLifter.getClub())) {
canadaLifters.add(curLifter);
}
}
// get the data sheet
workBookHandle = new WorkBookHandle(getTemplate());
WorkSheetHandle workSheet;
// Result sheet, panam
try {
workSheet = workBookHandle.getWorkSheet("Results");
new MastersIndividualSheet(hbnSessionManager).writeIndividualSheet(lifters, workSheet, null);
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Result sheet, canada
try {
workSheet = workBookHandle.getWorkSheet("Canada");
new MastersIndividualSheet(hbnSessionManager).writeIndividualSheet(canadaLifters, workSheet, null);
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// write out
writeWorkBook(workBookHandle, out);
} finally {
// close files
if (out != null) out.close();
if (workBookHandle != null) workBookHandle.close();
if (getTemplate() != null) getTemplate().close();
logger.debug("done writing, closed files and handles."); //$NON-NLS-1$
}
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(templateXls);
// File templateFile = new
// File(SheetUtils.getCompetition().getResultTemplateFileName());
// FileInputStream resourceAsStream = new FileInputStream(templateFile);
//if (resourceAsStream == null) {throw new IOException("file not found: "+templateFile.getAbsolutePath());} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
final List<Lifter> resultsOrderCopy = LifterSorter.resultsOrderCopy(new LifterContainer(app).getAllPojos(),
Ranking.TOTAL);
return resultsOrderCopy;
}
@Override
protected void writeHeader(WorkSheetHandle workSheet)
throws CellTypeMismatchException, CellNotFoundException {
super.writeHeader(workSheet);
if (competitionSession != null) {
//logger.debug("writeHeader {} {}",System.identityHashCode(competitionSession),competitionSession.getReferee3());
String announcer = competitionSession.getAnnouncer();
workSheet.getCell("C11").setVal(announcer != null ? announcer : ""); //$NON-NLS-1$
String marshall = competitionSession.getMarshall();
workSheet.getCell("G11").setVal(marshall != null ? marshall : ""); //$NON-NLS-1$
String timeKeeper = competitionSession.getTimeKeeper();
workSheet.getCell("M11").setVal(timeKeeper != null ? timeKeeper : ""); //$NON-NLS-1$
String technicalController = competitionSession.getTechnicalController();
workSheet.getCell("T11").setVal(technicalController != null ? technicalController : ""); //$NON-NLS-1$
String referee1 = competitionSession.getReferee1();
workSheet.getCell("C14").setVal(referee1 != null ? referee1 : ""); //$NON-NLS-1$
String referee2 = competitionSession.getReferee2();
workSheet.getCell("G14").setVal(referee2 != null ? referee2 : ""); //$NON-NLS-1$
String referee3 = competitionSession.getReferee3();
workSheet.getCell("M14").setVal(referee3 != null ? referee3 : ""); //$NON-NLS-1$
writeGroup(workSheet);
}
}
}
| 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.spreadsheet;
import org.concordiainternational.competition.data.Lifter;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
public interface LifterReader {
Lifter readLifter(WorkSheetHandle sheet, int lifterNumber);
void createInputSheetHelper(HbnSessionManager hbnSessionManager);
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import net.sf.jxls.transformer.XLSTransformer;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class JXLSJurySheet extends JXLSWorkbookStreamSource {
private JXLSJurySheet(){
super(true);
}
public JXLSJurySheet(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
Logger logger = LoggerFactory.getLogger(JXLSJurySheet.class);
private Competition competition;
@Override
protected void init() {
super.init();
competition = Competition.getAll().get(0);
getReportingBeans().put("competition",competition);
getReportingBeans().put("session",app.getCurrentCompetitionSession());
}
@Override
public InputStream getTemplate() throws IOException {
String templateName = "/JurySheetTemplate_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected void getSortedLifters() {
this.lifters = LifterSorter.displayOrderCopy(new LifterContainer(app, isExcludeNotWeighed()).getAllPojos());
LifterSorter.assignMedals(lifters);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource#configureTransformer(net.sf.jxls.transformer.XLSTransformer)
*/
@Override
protected void configureTransformer(XLSTransformer transformer) {
transformer.markAsFixedSizeCollection("lifters");
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class JXLSWeighInSheet extends JXLSWorkbookStreamSource {
private JXLSWeighInSheet(){
super(true);
}
public JXLSWeighInSheet(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
Logger logger = LoggerFactory.getLogger(JXLSWeighInSheet.class);
private Competition competition;
@Override
protected void init() {
super.init();
competition = Competition.getAll().get(0);
getReportingBeans().put("competition",competition);
getReportingBeans().put("session",app.getCurrentCompetitionSession());
}
@Override
public InputStream getTemplate() throws IOException {
String templateName = "/WeighInSheetTemplate_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected void getSortedLifters() {
this.lifters = LifterSorter.displayOrderCopy(new LifterContainer(app, isExcludeNotWeighed()).getAllPojos());
LifterSorter.assignMedals(lifters);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource#postProcess(org.apache.poi.ss.usermodel.Workbook)
*/
@Override
protected void postProcess(Workbook workbook) {
if (Competition.invitedIfBornBefore() <= 0) {
zapCellPair(workbook,3,18);
}
final CompetitionSession currentCompetitionSession = app.getCurrentCompetitionSession();
if (currentCompetitionSession == null) {
zapCellPair(workbook,3,10);
}
}
}
| 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.spreadsheet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellHandle;
import com.extentech.ExtenXLS.CellRange;
import com.extentech.ExtenXLS.FormatHandle;
import com.extentech.ExtenXLS.RowHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellPositionConflictException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.ColumnNotFoundException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy
*
*/
public class StartSheet extends ResultSheet {
public StartSheet(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
}
/**
*
*/
private static final int CATEGORY_BACKGROUND = FormatHandle.COLOR_GRAY50;
private static final int INDIVIDUAL_COLS = 10;
private CompetitionSession prevGroup;
private int rownum;
private int groupIx;
private FormatHandle spacerFormat;
// private FormatHandle groupFormatCenter;
private FormatHandle groupFormatLeft;
private FormatHandle groupFormatRight;
private static Logger logger = LoggerFactory.getLogger(StartSheet.class);
private void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
CompetitionSession competitionSession1 = lifter.getCompetitionSession();
if (!competitionSession1.equals(prevGroup)) {
createGroupHeading(workSheet, INDIVIDUAL_COLS - 1, competitionSession1);
}
prevGroup = competitionSession1;
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne.
workSheet.getCell(rownum, 0).setVal(groupIx);
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
workSheet.getCell(rownum, 5).setVal(lifter.getClub());
workSheet.getCell(rownum, 6).setVal(lifter.getBirthDate());
final Integer ageGroup = lifter.getAgeGroup();
final String endOfAgeGroup = endOfGroup(ageGroup, lifter.getGender());
workSheet.getCell(rownum, 7).setVal(ageGroup + endOfAgeGroup);
final Category registrationCategory = lifter.getRegistrationCategory();
workSheet.getCell(rownum, 8).setVal(registrationCategory!= null ? registrationCategory.getName() : null);
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getQualifyingTotal()));
rownum++;
groupIx++;
}
/**
* Handle men over 80 and women over 65.
*
* @param ageGroup
* @param gender
* @return
*/
private String endOfGroup(final Integer ageGroup, String gender) {
if (ageGroup == null) return "";
if ("m".equalsIgnoreCase(gender)) {
if (ageGroup == 80) {
return "+";
} else {
return "-" + (ageGroup + 4);
}
} else {
if (ageGroup == 65) {
return "+";
} else {
return "-" + (ageGroup + 4);
}
}
}
/**
* @param lifters
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
void writeStartSheet(List<Lifter> lifters, WorkSheetHandle workSheet) throws CellTypeMismatchException,
CellNotFoundException, RowNotFoundException {
spacerFormat = defineSpacerFormat(workSheet);
// groupFormatCenter = defineGroupFormatCenter(workSheet);
groupFormatLeft = defineGroupFormatLeft(workSheet);
groupFormatRight = defineGroupFormatRight(workSheet);
// fill-in the header.
writeHeader(workSheet);
setFooterLeft(workSheet);
// table heading
// setRepeatedLinesFormat(workSheet);
// process data sheet
rownum = InputSheetHelper.START_ROW;
for (Lifter curLifter : lifters) {
writeLifter(curLifter, workSheet, categoryLookup);
}
removeLastRowIfInserting(workSheet, rownum);
setPrintArea(workSheet, 0, // InputSheetHelper.START_ROW-2,
0, rownum - 1, INDIVIDUAL_COLS - 1);
if (!Competition.isMasters()) {
// hide the age group information
try {
CellHandle sourceCell;
workSheet.getCell("G3").remove(true);
sourceCell = workSheet.getCell("H3");
sourceCell.moveTo("G3");
workSheet.getCell("G4").remove(true);
sourceCell = workSheet.getCell("H4");
sourceCell.moveTo("G4");
workSheet.getCol("H").setHidden(true);
} catch (ColumnNotFoundException e) {
LoggerUtils.logException(logger, e);
} catch (CellPositionConflictException e) {
LoggerUtils.logException(logger, e);
}
}
}
/**
* @param workSheet
*/
@SuppressWarnings("unused")
private void setRepeatedLinesFormat(WorkSheetHandle workSheet) {
int[] rangeCoords = new int[] { 5, 0, 6, INDIVIDUAL_COLS - 1 };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setBackgroundColor(FormatHandle.COLOR_GRAY25);
fh.addCellRange(cellRange);
} catch (Exception e) {
}
}
@Override
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
workSheet.getCell("D2").setVal(competition.getCompetitionName()); //$NON-NLS-1$
workSheet.getCell("D3").setVal(competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) workSheet.getCell("D4").setVal(SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
workSheet.getCell("I3").setVal(competition.getCompetitionCity()); //$NON-NLS-1$
workSheet.getCell("I4").setVal(competition.getCompetitionOrganizer()); //$NON-NLS-1$
}
}
/**
* @param workSheet
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
private int createGroupHeading(WorkSheetHandle workSheet, int nbCols, CompetitionSession competitionSession1) throws CellNotFoundException,
RowNotFoundException {
groupIx = 1;
workSheet.insertRow(rownum, true);
RowHandle row = workSheet.getRow(rownum);
row.setHeight(200);
for (int i = 0; i <= nbCols; i++) {
final CellHandle cell = workSheet.getCell(rownum, i);
cell.setFormatHandle(spacerFormat);
}
rownum++;
workSheet.insertRow(rownum, true);
CellHandle cell = workSheet.getCell(rownum, 0);
// create a group label
String groupCode = competitionSession1.getName();
cell.setVal(groupCode);
int[] rangeCoords = new int[] { rownum, 0, rownum, 2 };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
cellRange.mergeCells(true);
groupFormatLeft.addCellRange(cellRange);
} catch (Exception e) {
}
// cell = workSheet.getCell(rownum, 0);
// cell.setFormatHandle(groupFormatLeft);
// cell = workSheet.getCell(rownum, nbCols);
// cell.setFormatHandle(groupFormatRight);
cell = workSheet.getCell(rownum, 3);
Date weighInTime = competitionSession1.getWeighInTime();
Date competitionTime = competitionSession1.getCompetitionTime();
String weighIn = weighInTime != null ? formatDate(weighInTime) : Messages.getString("StartSheet.TBA",CompetitionApplication.getCurrentLocale());
String start = competitionTime != null ? formatDate(competitionTime) : Messages.getString("StartSheet.TBA",CompetitionApplication.getCurrentLocale());
cell.setVal("Weigh-in/Pesée: " + weighIn + " " + "Start/Début: "+ start);
rangeCoords = new int[] { rownum, 3, rownum, nbCols };
try {
CellRange cellRange = new CellRange(workSheet, rangeCoords);
cellRange.mergeCells(true);
groupFormatRight.addCellRange(cellRange);
} catch (Exception e) {
}
// cell = workSheet.getCell(rownum, 0);
// cell.setFormatHandle(groupFormatLeft);
// cell = workSheet.getCell(rownum, nbCols);
// cell.setFormatHandle(groupFormatRight);
rownum++;
return rownum;
}
final static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
/**
* @param weighInTime
* @return
*/
private String formatDate(Date weighInTime) {
return simpleDateFormat.format(weighInTime);
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineSpacerFormat(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderTopColor(FormatHandle.COLOR_BLACK);
fh.setBorderBottomColor(FormatHandle.COLOR_BLACK);
fh.setBorderLeftColor(FormatHandle.COLOR_WHITE);
fh.setBorderRightColor(FormatHandle.COLOR_WHITE);
fh.setBackgroundColor(FormatHandle.COLOR_WHITE);
fh.setFontColor(FormatHandle.COLOR_WHITE);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineGroupFormatRight(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineGroupBackground(fh);
fh.setFontWeight(FormatHandle.DEFAULT_FONT_WEIGHT);
fh.setFontColor(FormatHandle.COLOR_WHITE);
fh.setLeftBorderLineStyle(FormatHandle.BORDER_NONE);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param workSheet
* @param i
* @throws CellNotFoundException
*/
private FormatHandle defineGroupFormatLeft(WorkSheetHandle workSheet) {
FormatHandle fh = new FormatHandle(workSheet.getWorkBook());
defineGroupBackground(fh);
fh.setFontWeight(FormatHandle.BOLD);
fh.setFontColor(FormatHandle.COLOR_WHITE);
fh.setBorderLeftColor(FormatHandle.COLOR_BLACK);
fh.setRightBorderLineStyle(FormatHandle.BORDER_NONE);
fh.setHorizontalAlignment(FormatHandle.ALIGN_CENTER);
fh.setVerticalAlignment(FormatHandle.ALIGN_VERTICAL_CENTER);
return fh;
}
/**
* @param fh
*/
private void defineGroupBackground(FormatHandle fh) {
fh.setPattern(FormatHandle.PATTERN_FILLED);
fh.setBorderLineStyle(FormatHandle.BORDER_THIN);
fh.setBorderColor(FormatHandle.COLOR_BLACK);
fh.setBackgroundColor(CATEGORY_BACKGROUND);
fh.setFontColor(FormatHandle.COLOR_WHITE);
}
}
| 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.spreadsheet;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
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.ui.CompetitionApplication;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* @author jflamy
*
*/
public class SinclairSheet extends ResultSheet {
public SinclairSheet(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
}
private int rownum = 0;
private void writeSinclairLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1)
throws CellTypeMismatchException, CellNotFoundException {
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne.
int firstRow = 0;
workSheet.getCell(rownum, firstRow).setVal(lifter.getMembership());
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
if (WinningOrderComparator.useRegistrationCategory) {
final Category category = lifter.getRegistrationCategory();
workSheet.getCell(rownum, 5).setVal((category != null ? category.getName() : null));
} else {
final Category category = lifter.getCategory();
workSheet.getCell(rownum, 5).setVal((category != null ? category.getName() : null));
}
workSheet.getCell(rownum, 6).setVal(lifter.getBodyWeight());
workSheet.getCell(rownum, 7).setVal(lifter.getClub());
workSheet.getCell(rownum, 8).setVal(lifter.getBirthDate());
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getSnatch1ActualLift()));
workSheet.getCell(rownum, 10).setVal(SheetUtils.fixValue(lifter.getSnatch2ActualLift()));
workSheet.getCell(rownum, 11).setVal(SheetUtils.fixValue(lifter.getSnatch3ActualLift()));
workSheet.getCell(rownum, 13).setVal(SheetUtils.fixValue(lifter.getCleanJerk1ActualLift()));
workSheet.getCell(rownum, 14).setVal(SheetUtils.fixValue(lifter.getCleanJerk2ActualLift()));
workSheet.getCell(rownum, 15).setVal(SheetUtils.fixValue(lifter.getCleanJerk3ActualLift()));
workSheet.getCell(rownum, 17).setVal(SheetUtils.fixValue(lifter.getTotal()));
workSheet.getCell(rownum, 18).setVal(lifter.getSinclair());
workSheet.getCell(rownum, 19).setVal(getSinclairValue(lifter));
final Integer sinclairRank = lifter.getSinclairRank();
if (lifter.isInvited()) {
final Locale currentLocale = CompetitionApplication.getCurrentLocale();
workSheet.getCell(rownum, 20).setVal(Messages.getString("Lifter.InvitedAbbreviated", currentLocale));
} else if (sinclairRank > firstRow) {
workSheet.getCell(rownum, 20).setVal(sinclairRank);
} else {
workSheet.getCell(rownum, 20).setVal("-");
}
// final Group group = lifter.getGroup();
// workSheet.getCell(rownum,22).setVal((group != null ? group.getName()
// : null));
rownum++;
}
/**
* @param lifter
* @return
*/
private Double getSinclairValue(Lifter lifter) {
if (Competition.isMasters()) {
return lifter.getSMM();
} else {
return lifter.getCategorySinclair();
}
}
/**
* @param lifters
* @param workSheet
* @param gender
* @throws CellTypeMismatchException
* @throws CellNotFoundException
* @throws RowNotFoundException
*/
void writeSinclairSheet(List<Lifter> lifters, WorkSheetHandle workSheet, String gender)
throws CellTypeMismatchException, CellNotFoundException, RowNotFoundException {
// fill-in the header.
writeHeader(workSheet);
setFooterLeft(workSheet);
// process data sheet
rownum = InputSheetHelper.START_ROW;
for (Lifter curLifter : lifters) {
if (gender == null || gender.equals(curLifter.getGender())) {
writeSinclairLifter(curLifter, workSheet, categoryLookup);
}
}
removeLastRowIfInserting(workSheet, rownum);
setPrintArea(workSheet, InputSheetHelper.START_ROW - 2, 0, rownum - 1, 20);
}
@Override
@SuppressWarnings("unchecked")
protected void writeHeader(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
List<Competition> competitions = CompetitionApplication.getCurrent().getHbnSession().createCriteria(
Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
setCellValue(workSheet, "K1", competition.getCompetitionName()); //$NON-NLS-1$
setCellValue(workSheet, "K2", competition.getCompetitionSite()); //$NON-NLS-1$
final Date competitionDate = competition.getCompetitionDate();
if (competitionDate != null) setCellValue(workSheet, "K3", SheetUtils.getShortDate(competitionDate)); //$NON-NLS-1$
setCellValue(workSheet, "T2", competition.getCompetitionCity()); //$NON-NLS-1$
setCellValue(workSheet, "T3", competition.getCompetitionOrganizer()); //$NON-NLS-1$
writeGroup(workSheet);
}
}
/**
* @param workSheet
* @throws CellTypeMismatchException
* @throws CellNotFoundException
*/
@Override
protected void writeGroup(WorkSheetHandle workSheet) throws CellTypeMismatchException, CellNotFoundException {
if (competitionSession != null) {
setCellValue(workSheet, "K4", competitionSession.getName());
} else {
setCellValue(workSheet, "J4", "");// clear the cell;
setCellValue(workSheet, "K4", "");// clear the cell;
}
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
*
* @author jflamy
*
*/
public class ResultSheet extends OutputSheet implements InputSheet, LifterReader {
protected static final String TEMPLATE_XLS = "/ResultSheetTemplate.xls"; //$NON-NLS-1$
Logger logger = LoggerFactory.getLogger(ResultSheet.class);
private InputSheetHelper lifterReaderHelper;
/**
* Create a sheet.
* If this constructor is used, or newInstance is called, then
* {@link #init(CategoryLookup, CompetitionApplication, CompetitionSession)} must also be called.
*/
public ResultSheet() {
}
public ResultSheet(HbnSessionManager hbnSessionManager) {
createInputSheetHelper(hbnSessionManager);
}
public ResultSheet(CategoryLookup categoryLookup, CompetitionApplication app, CompetitionSession competitionSession) {
super(categoryLookup, app, competitionSession);
createInputSheetHelper(app);
}
@Override
public void init(CategoryLookup categoryLookup1, CompetitionApplication app1,
CompetitionSession competitionSession1) {
super.init(categoryLookup1, app1, competitionSession1);
createInputSheetHelper(app1);
}
@Override
public void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int rownum)
throws CellTypeMismatchException, CellNotFoundException {
rownum = rownum + InputSheetHelper.START_ROW;
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne.
workSheet.getCell(rownum, 0).setVal(lifter.getMembership());
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
//logger.debug("lifter {} gender <{}>",lifter,gender);
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
workSheet.getCell(rownum, 5).setVal(lifter.getDisplayCategory());
workSheet.getCell(rownum, 6).setVal(lifter.getBodyWeight());
workSheet.getCell(rownum, 7).setVal(lifter.getClub());
workSheet.getCell(rownum, 8).setVal(lifter.getBirthDate());
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getSnatch1ActualLift()));
workSheet.getCell(rownum, 10).setVal(SheetUtils.fixValue(lifter.getSnatch2ActualLift()));
workSheet.getCell(rownum, 11).setVal(SheetUtils.fixValue(lifter.getSnatch3ActualLift()));
workSheet.getCell(rownum, 13).setVal(SheetUtils.fixValue(lifter.getCleanJerk1ActualLift()));
workSheet.getCell(rownum, 14).setVal(SheetUtils.fixValue(lifter.getCleanJerk2ActualLift()));
workSheet.getCell(rownum, 15).setVal(SheetUtils.fixValue(lifter.getCleanJerk3ActualLift()));
workSheet.getCell(rownum, 17).setVal(SheetUtils.fixValue(lifter.getTotal()));
workSheet.getCell(rownum, 18).setVal(SheetUtils.fixRank(lifter.getRank()));
workSheet.getCell(rownum, 20).setVal(lifter.getSinclair());
workSheet.getCell(rownum, 21).setVal(lifter.getCategorySinclair());
final CompetitionSession group = lifter.getCompetitionSession();
workSheet.getCell(rownum,22).setVal((group != null ? group.getName(): null));
}
/**
* Fill in a lifter record from a row in the spreadsheet.
*
* @param lifterNumber
* index of the lifter, starting at 0
* @throws CellNotFoundException
*/
@Override
public Lifter readLifter(WorkSheetHandle sheet, int lifterNumber) {
int row = lifterNumber + InputSheetHelper.START_ROW;
Lifter lifter = new Lifter();
// read in values; getInt returns null if the cell is empty as opposed
// to a number or -
try {
lifter.setMembership(lifterReaderHelper.getString(sheet, row, 0));
lifter.setLotNumber(lifterReaderHelper.getInt(sheet, row, 1));
final String lastName = lifterReaderHelper.getString(sheet, row, 2);
final String firstName = lifterReaderHelper.getString(sheet, row, 3);
if (lastName.isEmpty() && firstName.isEmpty()) {
return null; // no data on this row.
}
lifter.setLastName(lastName);
lifter.setFirstName(firstName);
lifter.setGender(lifterReaderHelper.getGender(sheet, row, InputSheetHelper.GENDER_COLUMN));
lifter.setRegistrationCategory(lifterReaderHelper.getCategory(sheet, row, 5));
lifter.setBodyWeight(lifterReaderHelper.getDouble(sheet, row, InputSheetHelper.BODY_WEIGHT_COLUMN));
lifter.setClub(lifterReaderHelper.getString(sheet, row, 7));
lifter.setBirthDate(lifterReaderHelper.getInt(sheet, row, 8));
lifter.setSnatch1ActualLift(lifterReaderHelper.getString(sheet, row, 9));
lifter.setSnatch2ActualLift(lifterReaderHelper.getString(sheet, row, 10));
lifter.setSnatch3ActualLift(lifterReaderHelper.getString(sheet, row, 11));
lifter.setCleanJerk1ActualLift(lifterReaderHelper.getString(sheet, row, 13));
lifter.setCleanJerk2ActualLift(lifterReaderHelper.getString(sheet, row, 14));
lifter.setCleanJerk3ActualLift(lifterReaderHelper.getString(sheet, row, 15 ));
try {
lifter.setCompetitionSession(lifterReaderHelper.getCompetitionSession(sheet, row, 22));
} catch (CellNotFoundException e) {
}
try {
lifter.setQualifyingTotal(lifterReaderHelper.getInt(sheet, row, 24));
} catch (CellNotFoundException e) {
}
logger.debug(InputSheetHelper.toString(lifter, false));
return lifter;
} catch (CellNotFoundException c) {
logger.debug(c.toString());
return null;
}
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(TEMPLATE_XLS);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + TEMPLATE_XLS);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
final List<Lifter> resultsOrderCopy = LifterSorter.resultsOrderCopy(new LifterContainer(app).getAllPojos(),
Ranking.TOTAL);
LifterSorter.assignMedals(resultsOrderCopy);
return resultsOrderCopy;
}
@Override
protected void writeHeader(WorkSheetHandle workSheet)
throws CellTypeMismatchException, CellNotFoundException {
super.writeHeader(workSheet);
if (competitionSession != null) {
//logger.debug("writeHeader {} {}",System.identityHashCode(competitionSession),competitionSession.getReferee3());
String announcer = competitionSession.getAnnouncer();
workSheet.getCell("C11").setVal(announcer != null ? announcer : ""); //$NON-NLS-1$
String marshall = competitionSession.getMarshall();
workSheet.getCell("G11").setVal(marshall != null ? marshall : ""); //$NON-NLS-1$
String timeKeeper = competitionSession.getTimeKeeper();
workSheet.getCell("M11").setVal(timeKeeper != null ? timeKeeper : ""); //$NON-NLS-1$
String technicalController = competitionSession.getTechnicalController();
workSheet.getCell("S11").setVal(technicalController != null ? technicalController : ""); //$NON-NLS-1$
String referee1 = competitionSession.getReferee1();
workSheet.getCell("C14").setVal(referee1 != null ? referee1 : ""); //$NON-NLS-1$
String referee2 = competitionSession.getReferee2();
workSheet.getCell("G14").setVal(referee2 != null ? referee2 : ""); //$NON-NLS-1$
String referee3 = competitionSession.getReferee3();
workSheet.getCell("M14").setVal(referee3 != null ? referee3 : ""); //$NON-NLS-1$
writeGroup(workSheet);
}
}
@Override
public List<Lifter> getAllLifters(InputStream is, HbnSessionManager session)
throws CellNotFoundException, IOException,
WorkSheetNotFoundException, InterruptedException, Throwable {
return lifterReaderHelper.getAllLifters(is, session);
}
@Override
public List<Lifter> getGroupLifters(InputStream is, String aGroup,
HbnSessionManager session) throws CellNotFoundException,
IOException, WorkSheetNotFoundException, InterruptedException,
Throwable {
return lifterReaderHelper.getGroupLifters(is, aGroup, session);
}
@Override
public void createInputSheetHelper(HbnSessionManager hbnSessionManager) {
lifterReaderHelper = new InputSheetHelper(hbnSessionManager,this);
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CategoryLookupByName;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.CompetitionSessionLookup;
import org.concordiainternational.competition.data.Gender;
import org.concordiainternational.competition.data.Lifter;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.CellHandle;
import com.extentech.ExtenXLS.DateConverter;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
public class InputSheetHelper implements InputSheet {
final private static Logger logger = LoggerFactory.getLogger(InputSheetHelper.class);
// constants
final static int START_ROW = 7;
static final int GENDER_COLUMN = 4;
static final int BODY_WEIGHT_COLUMN = 6;
private CategoryLookup categoryLookup;
private CompetitionSessionLookup competitionSessionLookup;
private CategoryLookupByName categoryLookupByName;
private LifterReader reader;
private WorkBookHandle workBookHandle;
private WorkSheetHandle workSheet;
InputSheetHelper(HbnSessionManager hbnSessionManager, LifterReader reader) {
categoryLookup = CategoryLookup.getSharedInstance(hbnSessionManager);
categoryLookupByName = new CategoryLookupByName(hbnSessionManager);
competitionSessionLookup = new CompetitionSessionLookup(hbnSessionManager);
this.reader = reader;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.spreadsheet.InputSheet#getAllLifters(java.io.InputStream, com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager)
*/
@Override
public synchronized List<Lifter> getAllLifters(InputStream is, HbnSessionManager sessionMgr) throws IOException,
CellNotFoundException, WorkSheetNotFoundException {
LinkedList<Lifter> allLifters;
try {
getWorkSheet(is);
// process data sheet
allLifters = new LinkedList<Lifter>();
LifterReader lifterReader = reader;
for (int i = 0; true; i++) {
final Lifter lifter = lifterReader.readLifter(workSheet, i);
if (lifter != null) {
allLifters.add(lifter);
// System.err.println("added lifter " +
// InputSheetHelper.toString(lifter));
} else {
break;
}
}
// readHeader(workSheet,sessionMgr.getHbnSession());
} finally {
// close workbook file and hide lock
if (workBookHandle != null) workBookHandle.close();
if (is != null) is.close();
}
return allLifters;
}
/**
* @param is
* @throws WorkSheetNotFoundException
*/
protected void getWorkSheet(InputStream is)
throws WorkSheetNotFoundException {
// get the data sheet
if (workSheet == null) {
workBookHandle = new WorkBookHandle(is);
workSheet = workBookHandle.getWorkSheet(0);
}
}
public void readHeader(InputStream is, HbnSessionManager sessionMgr)
throws CellNotFoundException, WorkSheetNotFoundException, IOException {
try {
getWorkSheet(is);
readHeader(sessionMgr.getHbnSession());
} finally {
// close workbook file and hide lock
if (workBookHandle != null) workBookHandle.close();
if (is != null) is.close();
}
}
/*
* (non-Javadoc)
*
* @see
* org.concordia_international.reader.ResultSheet#getGroup(java.lang.String)
*/
@Override
public List<Lifter> getGroupLifters(InputStream is, String aGroup, HbnSessionManager session) throws IOException,
CellNotFoundException, WorkSheetNotFoundException {
List<Lifter> groupLifters = new ArrayList<Lifter>();
for (Lifter curLifter : getAllLifters(is, session)) {
if (aGroup.equals(curLifter.getCompetitionSession())) {
groupLifters.add(curLifter);
}
}
return groupLifters;
}
public static String toString(Lifter lifter, boolean includeTimeStamp) {
final Category category = lifter.getCategory();
final CompetitionSession competitionSession = lifter.getCompetitionSession();
final Date lastLiftTime = lifter.getLastLiftTime();
return (new StringBuilder())
.append(" lastName=" + lifter.getLastName()) //$NON-NLS-1$
.append(" firstName=" + lifter.getFirstName()) //$NON-NLS-1$
.append(" membership=" + lifter.getMembership()) //$NON-NLS-1$
.append(" lotNumber=" + lifter.getLotNumber()) //$NON-NLS-1$
.append(" group=" + (competitionSession != null ? competitionSession.getName() : null)) //$NON-NLS-1$
.append(" club=" + lifter.getClub()) //$NON-NLS-1$
.append(" gender=" + lifter.getGender()) //$NON-NLS-1$
.append(" bodyWeight=" + lifter.getBodyWeight()) //$NON-NLS-1$
.append(" birthDate=" + lifter.getBirthDate()) //$NON-NLS-1$
.append(" registrationCategory=" + lifter.getRegistrationCategory()) //$NON-NLS-1$
.append(" category=" + (category != null ? category.getName() : null)) //$NON-NLS-1$
.append(" snatch1ActualLift=" + lifter.getSnatch1ActualLift()) //$NON-NLS-1$
.append(" snatch2=" + lifter.getSnatch2ActualLift()) //$NON-NLS-1$
.append(" snatch3=" + lifter.getSnatch3ActualLift()) //$NON-NLS-1$
.append(" bestSnatch=" + lifter.getBestSnatch()) //$NON-NLS-1$
.append(" cleanJerk1ActualLift=" + lifter.getCleanJerk1ActualLift()) //$NON-NLS-1$
.append(" cleanJerk2=" + lifter.getCleanJerk2ActualLift()) //$NON-NLS-1$
.append(" cleanJerk3=" + lifter.getCleanJerk3ActualLift()) //$NON-NLS-1$
.append(
includeTimeStamp ? (" lastLiftTime=" + (lastLiftTime != null ? lastLiftTime.getTime() : null)) : "") //$NON-NLS-1$ //$NON-NLS-2$
.append(" total=" + lifter.getTotal()) //$NON-NLS-1$
.append(" totalRank=" + lifter.getRank()) //$NON-NLS-1$
.toString();
}
public static String toString(Lifter lifter) {
return toString(lifter, true);
}
public Integer getInt(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
CellHandle cell = sheet.getCell(row, column);
Integer intVal = (cell != null ? cell.getIntVal() : null);
return intVal;
}
public Double getDouble(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
CellHandle cell = sheet.getCell(row, column);
Double val = (cell != null ? cell.getDoubleVal() : null);
return val;
}
public String getString(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
CellHandle cell = sheet.getCell(row, column);
return cell.getStringVal().trim();
}
/**
* Fill in a lifter record from a row in the spreadsheet.
*
* @param lifterNumber
* index of the lifter, starting at 0
* @throws CellNotFoundException
*/
Lifter readLifter(WorkSheetHandle sheet, int lifterNumber) {
int row = lifterNumber + START_ROW;
Lifter lifter = new Lifter();
// read in values; getInt returns null if the cell is empty as opposed
// to a number or -
try {
lifter.setMembership(getString(sheet, row, 0));
lifter.setLotNumber(getInt(sheet, row, 1));
final String lastName = getString(sheet, row, 2);
final String firstName = getString(sheet, row, 3);
if (lastName.isEmpty() && firstName.isEmpty()) {
return null; // no data on this row.
}
lifter.setLastName(lastName);
lifter.setFirstName(firstName);
lifter.setGender(getGender(sheet, row, GENDER_COLUMN));
lifter.setRegistrationCategory(getCategory(sheet, row, 5));
lifter.setBodyWeight(getDouble(sheet, row, BODY_WEIGHT_COLUMN));
lifter.setClub(getString(sheet, row, 7));
lifter.setBirthDate(getInt(sheet, row, 8));
lifter.setSnatch1Declaration(getString(sheet, row, 9));
lifter.setSnatch1ActualLift(getString(sheet, row, 10));
lifter.setSnatch2ActualLift(getString(sheet, row, 11));
lifter.setSnatch3ActualLift(getString(sheet, row, 12));
lifter.setCleanJerk1Declaration(getString(sheet, row, 14));
lifter.setCleanJerk1ActualLift(getString(sheet, row, 15));
lifter.setCleanJerk2ActualLift(getString(sheet, row, 16));
lifter.setCleanJerk3ActualLift(getString(sheet, row, 17));
lifter.setCompetitionSession(getCompetitionSession(sheet, row, 22));
try {
lifter.setQualifyingTotal(getInt(sheet, row, 24));
} catch (CellNotFoundException e) {
}
logger.debug(toString(lifter, false));
return lifter;
} catch (CellNotFoundException c) {
logger.debug(c.toString());
return null;
}
}
@SuppressWarnings( { "unchecked" })
public void readHeader(Session hbnSession) throws CellNotFoundException {
List<Competition> competitions = hbnSession.createCriteria(Competition.class).list();
if (competitions.size() > 0) {
final Competition competition = competitions.get(0);
competition.setFederation(workSheet.getCell("A1").getStringVal()); //$NON-NLS-1$
competition.setFederationAddress(workSheet.getCell("A2").getStringVal()); //$NON-NLS-1$
competition.setFederationWebSite(workSheet.getCell("A3").getStringVal()); //$NON-NLS-1$
competition.setFederationEMail(workSheet.getCell("B4").getStringVal()); //$NON-NLS-1$
competition.setCompetitionName(workSheet.getCell("I1").getStringVal()); //$NON-NLS-1$
competition.setCompetitionSite(workSheet.getCell("I2").getStringVal()); //$NON-NLS-1$
final CellHandle dateCell = workSheet.getCell("I3");
Date nDate = DateConverter.getDateFromCell(dateCell) ;
competition.setCompetitionDate(nDate);
// String dateString = dateCell.getStringVal(); //$NON-NLS-1$
// if (dateString != null && !dateString.trim().isEmpty()) {
// try {
// } catch (NumberFormatException e) {
// // TODO: handle exception
// }
// Date date = DateTime.parse(dateString).toDate();
// competition.setCompetitionDate(date);
// } else {
// competition.setCompetitionDate(new Date());
// }
competition.setCompetitionCity(workSheet.getCell("T2").getStringVal()); //$NON-NLS-1$
competition.setCompetitionOrganizer(workSheet.getCell("T3").getStringVal()); //$NON-NLS-1$
competition.setInvitedIfBornBefore(workSheet.getCell("T4").getIntVal()); //$NON-NLS-1$
}
}
Category getCategory(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
// first try category as written
String catString = getString(sheet, row, column);
Category lookup = categoryLookupByName.lookup(catString);
if (lookup != null) return lookup;
// else try category made up from sex and category.
String genderString = getString(sheet, row, GENDER_COLUMN);
lookup = categoryLookupByName.lookup(genderString + catString);
if (lookup != null) return lookup;
// else try bodyWeight and sex
final String gender = getGender(sheet, row, GENDER_COLUMN);
final Double bodyweight = getDouble(sheet, row, BODY_WEIGHT_COLUMN);
lookup = categoryLookup.lookup(gender, bodyweight);
if (lookup != null) return lookup;
return null;
}
/**
* @param sheet
* @param row
* @param column
* @return
* @throws CellNotFoundException
*/
public String getGender(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
final String genderString = getString(sheet, row, column);
if (genderString != null && genderString.trim().length() > 0) {
return Gender.valueOf(genderString.toUpperCase()).toString();
} else {
return null;
}
}
public CompetitionSession getCompetitionSession(WorkSheetHandle sheet, int row, int column) throws CellNotFoundException {
// try group as written
String catString = getString(sheet, row, column);
CompetitionSession lookup = competitionSessionLookup.lookup(catString);
if (lookup != null) return lookup;
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.spreadsheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.TreeSet;
import org.concordiainternational.competition.data.CategoryLookup;
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.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.LoggerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkBookHandle;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.RowNotFoundException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* Result sheet, with team rankings
*
* @author jflamy
*
*/
public class CompetitionBook extends ResultSheet {
protected static String templateXls = "/TeamResultSheetTemplate_Standard.xls"; //$NON-NLS-1$
private Logger logger = LoggerFactory.getLogger(CompetitionBook.class);
Competition competition;
private HbnSessionManager hbnSessionManager;
/**
* Create a sheet.
* If this constructor is used, or newInstance is called, then
* {@link #init(CategoryLookup, CompetitionApplication, CompetitionSession)} must also be called.
* OutputSheetStreamSource does call init() correctly.
*/
public CompetitionBook() {
}
public CompetitionBook(HbnSessionManager hbnSessionManager) {
super(hbnSessionManager);
this.hbnSessionManager = hbnSessionManager;
}
@Override
public void init(CategoryLookup categoryLookup1, CompetitionApplication app1,
CompetitionSession competitionSession1) {
super.init(categoryLookup1, app1, competitionSession1);
this.hbnSessionManager = app1;
createInputSheetHelper(app1);
}
@Override
public void writeLifters(List<Lifter> lifters, OutputStream out) throws CellTypeMismatchException,
CellNotFoundException, RowNotFoundException, IOException, WorkSheetNotFoundException {
WorkBookHandle workBookHandle = null;
try {
if (lifters.isEmpty()) {
// should have been dealt with earlier
// this prevents a loop in the spreadsheet processing if it has
// not.
throw new RuntimeException(Messages.getString(
"OutputSheet.EmptySpreadsheet", CompetitionApplication.getCurrentLocale())); //$NON-NLS-1$
}
// extract club lists
TreeSet<String> clubs = new TreeSet<String>();
for (Lifter curLifter : lifters) {
clubs.add(curLifter.getClub());
}
// produce point rankings.
final LifterSorter lifterSorter = new LifterSorter();
List<Lifter> teamRankingLifters;
List<Lifter> sinclairLifters;
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.SNATCH);
lifterSorter.assignCategoryRanks(teamRankingLifters, Ranking.SNATCH);
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.CLEANJERK);
lifterSorter.assignCategoryRanks(teamRankingLifters, Ranking.CLEANJERK);
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.TOTAL);
lifterSorter.assignCategoryRanks(teamRankingLifters, Ranking.TOTAL);
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.CUSTOM);
lifterSorter.assignCategoryRanks(teamRankingLifters, Ranking.CUSTOM);
sinclairLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.SINCLAIR);
teamRankingLifters = LifterSorter.resultsOrderCopy(lifters, Ranking.SINCLAIR);
lifterSorter.assignSinclairRanksAndPoints(teamRankingLifters, Ranking.SINCLAIR);
// this final sort is used to put all the lifters from the same
// team together. The ranking is arbitrary, TOTAL happens to be convenient.
LifterSorter.teamRankingOrder(teamRankingLifters, Ranking.TOTAL);
// get the data sheet
workBookHandle = new WorkBookHandle(getTemplate());
WorkSheetHandle workSheet;
// Result sheet, men
try {
workSheet = workBookHandle.getWorkSheet("Hommes 6 essais");
if (Competition.isMasters()) {
new MastersIndividualSheet(hbnSessionManager).writeIndividualSheet(lifters, workSheet, "M");
} else {
new IndividualSheet(hbnSessionManager).writeIndividualSheet(lifters, workSheet, "M");
}
workSheet.setSheetName(Messages.getString("CompetionBook.M6", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Result sheet, women
try {
workSheet = workBookHandle.getWorkSheet("Femmes 6 essais");
if (Competition.isMasters()) {
new MastersIndividualSheet(hbnSessionManager).writeIndividualSheet(lifters, workSheet, "F");
} else {
new IndividualSheet(hbnSessionManager).writeIndividualSheet(lifters, workSheet, "F");
}
workSheet.setSheetName(Messages.getString("CompetionBook.F6", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Sinclair sheet, men
try {
workSheet = workBookHandle.getWorkSheet("Hommes Sinclair");
new SinclairSheet(hbnSessionManager).writeSinclairSheet(sinclairLifters, workSheet, "M");
workSheet.setSheetName(Messages.getString("CompetionBook.MS", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Sinclair sheet, women
try {
workSheet = workBookHandle.getWorkSheet("Femmes Sinclair");
new SinclairSheet(hbnSessionManager).writeSinclairSheet(sinclairLifters, workSheet, "F");
workSheet.setSheetName(Messages.getString("CompetionBook.FS", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Men Total ranking
try {
workSheet = workBookHandle.getWorkSheet("Hommes équipes");
new TeamSheet(hbnSessionManager).writeTeamSheet(teamRankingLifters, workSheet, Ranking.TOTAL, clubs, "M");
workSheet.setSheetName(Messages.getString("CompetionBook.MT", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Women total ranking
try {
workSheet = workBookHandle.getWorkSheet("Femmes équipes");
new TeamSheet(hbnSessionManager).writeTeamSheet(teamRankingLifters, workSheet, Ranking.TOTAL, clubs, "F");
workSheet.setSheetName(Messages.getString("CompetionBook.FT", CompetitionApplication.getCurrentLocale()));
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Team Total ranking
try {
workSheet = workBookHandle.getWorkSheet("Mixte équipes");
workSheet.setSheetName(Messages.getString("CompetionBook.AT", CompetitionApplication.getCurrentLocale()));
new TeamSheet(hbnSessionManager).writeTeamSheet(teamRankingLifters, workSheet, Ranking.TOTAL, clubs, null);
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Team Custom ranking
try {
workSheet = workBookHandle.getWorkSheet("Spécial équipes");
workSheet.setSheetName(Messages.getString("CompetionBook.XT", CompetitionApplication.getCurrentLocale()));
new TeamSheet(hbnSessionManager).writeTeamSheet(teamRankingLifters, workSheet, Ranking.CUSTOM, clubs, null);
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// Team Combined ranking; write each team three times (sn, cj, tot).
try {
workSheet = workBookHandle.getWorkSheet("Somme équipes");
workSheet.setSheetName(Messages.getString("CompetionBook.CT", CompetitionApplication.getCurrentLocale()));
new TeamSheet(hbnSessionManager).writeTeamSheetCombined(teamRankingLifters, workSheet, clubs, null);
} catch (WorkSheetNotFoundException wnf) {
} catch (Exception e) {
LoggerUtils.logException(logger, e);
}
// write out
writeWorkBook(workBookHandle, out);
} finally {
// close files
if (out != null) out.close();
if (workBookHandle != null) workBookHandle.close();
if (getTemplate() != null) getTemplate().close();
logger.debug("done writing, closed files and handles."); //$NON-NLS-1$
}
}
@Override
public InputStream getTemplate() throws IOException {
// final InputStream resourceAsStream =
// app.getResourceAsStream(templateXls);
File templateFile = new File(SheetUtils.getCompetition().getResultTemplateFileName());
FileInputStream resourceAsStream = new FileInputStream(templateFile);
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
final List<Lifter> resultsOrderCopy = LifterSorter.resultsOrderCopy(new LifterContainer(app).getAllPojos(),
Ranking.TOTAL);
return resultsOrderCopy;
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.concordiainternational.competition.data.CategoryLookup;
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.lifterSort.LifterSorter;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.extentech.ExtenXLS.WorkSheetHandle;
import com.extentech.formats.XLS.CellNotFoundException;
import com.extentech.formats.XLS.CellTypeMismatchException;
import com.extentech.formats.XLS.WorkSheetNotFoundException;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
/**
* The start sheet format is able to produce a round-trip. It implements both
* the input sheet and output sheet interfaces.
*
* @author jflamy
*
*/
public class WeighInSheet extends OutputSheet implements InputSheet, LifterReader {
protected static final String TEMPLATE_XLS = "/WeighInSheetTemplate.xls"; //$NON-NLS-1$
private static final Logger logger = LoggerFactory.getLogger(WeighInSheet.class);
private InputSheetHelper lifterReaderHelper;
/**
* Create a sheet.
* If this constructor is used, or newInstance is called, then
* {@link #init(CategoryLookup, CompetitionApplication, CompetitionSession)} must also be called.
*/
public WeighInSheet() {
}
public WeighInSheet(HbnSessionManager hbnSessionManager) {
createInputSheetHelper(hbnSessionManager);
}
public WeighInSheet(CategoryLookup categoryLookup, CompetitionApplication app, CompetitionSession competitionSession) {
super(categoryLookup, app, competitionSession);
createInputSheetHelper(app);
}
@Override
public void init(CategoryLookup categoryLookup1, CompetitionApplication app1,
CompetitionSession competitionSession1) {
super.init(categoryLookup1, app1, competitionSession1);
createInputSheetHelper(app1);
}
/**
* @see org.concordiainternational.competition.spreadsheet.OutputSheet#writeLifter(org.concordiainternational.competition.data.Lifter,
* com.extentech.ExtenXLS.WorkSheetHandle,
* org.concordiainternational.competition.data.CategoryLookup, int)
*
* IMPORTANT: the columns in this routine must match those in
* {@link InputSheetHelper#readLifter(WorkSheetHandle, int)}
*/
@Override
@Deprecated
public void writeLifter(Lifter lifter, WorkSheetHandle workSheet, CategoryLookup categoryLookup1, int rownum)
throws CellTypeMismatchException, CellNotFoundException {
rownum = rownum + InputSheetHelper.START_ROW;
workSheet.insertRow(rownum, true); // insérer une nouvelle ligne
workSheet.getCell(rownum, 0).setVal(lifter.getMembership());
workSheet.getCell(rownum, 1).setVal(lifter.getLotNumber());
workSheet.getCell(rownum, 2).setVal(lifter.getLastName());
workSheet.getCell(rownum, 3).setVal(lifter.getFirstName());
final String gender = lifter.getGender();
workSheet.getCell(rownum, 4).setVal((gender != null ? gender.toString() : null));
if (Competition.isMasters()) {
workSheet.getCell(rownum, 5).setVal(lifter.getMastersLongCategory());
} else {
workSheet.getCell(rownum, 5).setVal(lifter.getDisplayCategory());
}
workSheet.getCell(rownum, 6).setVal(lifter.getBodyWeight());
workSheet.getCell(rownum, 7).setVal(lifter.getClub());
workSheet.getCell(rownum, 8).setVal(lifter.getBirthDate());
workSheet.getCell(rownum, 9).setVal(SheetUtils.fixValue(lifter.getSnatch1Declaration()));
workSheet.getCell(rownum, 10).setVal(SheetUtils.fixValue(lifter.getSnatch1ActualLift()));
workSheet.getCell(rownum, 11).setVal(SheetUtils.fixValue(lifter.getSnatch2ActualLift()));
workSheet.getCell(rownum, 12).setVal(SheetUtils.fixValue(lifter.getSnatch3ActualLift()));
workSheet.getCell(rownum, 14).setVal(SheetUtils.fixValue(lifter.getCleanJerk1Declaration()));
workSheet.getCell(rownum, 15).setVal(SheetUtils.fixValue(lifter.getCleanJerk1ActualLift()));
workSheet.getCell(rownum, 16).setVal(SheetUtils.fixValue(lifter.getCleanJerk2ActualLift()));
workSheet.getCell(rownum, 17).setVal(SheetUtils.fixValue(lifter.getCleanJerk3ActualLift()));
final CompetitionSession competitionSession1 = lifter.getCompetitionSession();
workSheet.getCell(rownum, 22).setVal((competitionSession1 != null ? competitionSession1.getName() : null));
}
/**
* Fill in a lifter record from a row in the spreadsheet.
*
* @param lifterNumber
* index of the lifter, starting at 0
* @throws CellNotFoundException
*/
@Override
public Lifter readLifter(WorkSheetHandle sheet, int lifterNumber) {
int row = lifterNumber + InputSheetHelper.START_ROW;
Lifter lifter = new Lifter();
// read in values; getInt returns null if the cell is empty as opposed
// to a number or -
try {
lifter.setMembership(lifterReaderHelper.getString(sheet, row, 0));
lifter.setLotNumber(lifterReaderHelper.getInt(sheet, row, 1));
final String lastName = lifterReaderHelper.getString(sheet, row, 2);
final String firstName = lifterReaderHelper.getString(sheet, row, 3);
if (lastName.isEmpty() && firstName.isEmpty()) {
return null; // no data on this row.
}
lifter.setLastName(lastName);
lifter.setFirstName(firstName);
lifter.setGender(lifterReaderHelper.getGender(sheet, row, InputSheetHelper.GENDER_COLUMN));
lifter.setRegistrationCategory(lifterReaderHelper.getCategory(sheet, row, 5));
lifter.setBodyWeight(lifterReaderHelper.getDouble(sheet, row, InputSheetHelper.BODY_WEIGHT_COLUMN));
lifter.setClub(lifterReaderHelper.getString(sheet, row, 7));
lifter.setBirthDate(lifterReaderHelper.getInt(sheet, row, 8));
lifter.setSnatch1Declaration(lifterReaderHelper.getString(sheet, row, 9));
lifter.setSnatch1ActualLift(lifterReaderHelper.getString(sheet, row, 10));
lifter.setSnatch2ActualLift(lifterReaderHelper.getString(sheet, row, 11));
lifter.setSnatch3ActualLift(lifterReaderHelper.getString(sheet, row, 12));
lifter.setCleanJerk1Declaration(lifterReaderHelper.getString(sheet, row, 14));
lifter.setCleanJerk1ActualLift(lifterReaderHelper.getString(sheet, row, 15));
lifter.setCleanJerk2ActualLift(lifterReaderHelper.getString(sheet, row, 16));
lifter.setCleanJerk3ActualLift(lifterReaderHelper.getString(sheet, row, 17));
lifter.setCompetitionSession(lifterReaderHelper.getCompetitionSession(sheet, row, 22));
try {
lifter.setQualifyingTotal(lifterReaderHelper.getInt(sheet, row, 24));
} catch (CellNotFoundException e) {
}
logger.debug(InputSheetHelper.toString(lifter, false));
return lifter;
} catch (CellNotFoundException c) {
logger.debug(c.toString());
return null;
}
}
@Override
public InputStream getTemplate() throws IOException {
final InputStream resourceAsStream = app.getResourceAsStream(TEMPLATE_XLS);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + TEMPLATE_XLS);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected List<Lifter> getLifters(boolean excludeNotWeighed) {
return LifterSorter.displayOrderCopy(new LifterContainer(app, excludeNotWeighed).getAllPojos());
}
public void readHeader(InputStream is, HbnSessionManager session)
throws CellNotFoundException, WorkSheetNotFoundException, IOException {
lifterReaderHelper.readHeader(is, session);
return;
}
@Override
public List<Lifter> getAllLifters(InputStream is, HbnSessionManager session)
throws CellNotFoundException, IOException,
WorkSheetNotFoundException, InterruptedException, Throwable {
return lifterReaderHelper.getAllLifters(is, session);
}
@Override
public List<Lifter> getGroupLifters(InputStream is, String aGroup,
HbnSessionManager session) throws CellNotFoundException,
IOException, WorkSheetNotFoundException, InterruptedException,
Throwable {
return lifterReaderHelper.getGroupLifters(is, aGroup, session);
}
@Override
public void createInputSheetHelper(HbnSessionManager hbnSessionManager) {
lifterReaderHelper = new InputSheetHelper(hbnSessionManager,this);
}
@Override
protected void writeHeader(WorkSheetHandle workSheet)
throws CellTypeMismatchException, CellNotFoundException {
super.writeHeader(workSheet);
if (competitionSession != null) {
//logger.debug("writeHeader {} {}",System.identityHashCode(competitionSession),competitionSession.getReferee3());
String announcer = competitionSession.getAnnouncer();
workSheet.getCell("C11").setVal(announcer != null ? announcer : ""); //$NON-NLS-1$
String marshall = competitionSession.getMarshall();
workSheet.getCell("G11").setVal(marshall != null ? marshall : ""); //$NON-NLS-1$
String timeKeeper = competitionSession.getTimeKeeper();
workSheet.getCell("M11").setVal(timeKeeper != null ? timeKeeper : ""); //$NON-NLS-1$
String technicalController = competitionSession.getTechnicalController();
workSheet.getCell("S11").setVal(technicalController != null ? technicalController : ""); //$NON-NLS-1$
String referee1 = competitionSession.getReferee1();
workSheet.getCell("C14").setVal(referee1 != null ? referee1 : ""); //$NON-NLS-1$
String referee2 = competitionSession.getReferee2();
workSheet.getCell("G14").setVal(referee2 != null ? referee2 : ""); //$NON-NLS-1$
String referee3 = competitionSession.getReferee3();
workSheet.getCell("M14").setVal(referee3 != null ? referee3 : ""); //$NON-NLS-1$
writeGroup(workSheet);
}
}
}
| 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.spreadsheet;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.data.lifterSort.LifterSorter;
import org.concordiainternational.competition.data.lifterSort.LifterSorter.Ranking;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
@SuppressWarnings("serial")
public class JXLSResultSheet extends JXLSWorkbookStreamSource {
public JXLSResultSheet(){
super(true);
}
public JXLSResultSheet(boolean excludeNotWeighed) {
super(excludeNotWeighed);
}
Logger logger = LoggerFactory.getLogger(JXLSResultSheet.class);
private Competition competition;
@Override
protected void init() {
super.init();
competition = Competition.getAll().get(0);
getReportingBeans().put("competition",competition);
getReportingBeans().put("session",app.getCurrentCompetitionSession());
}
@Override
public InputStream getTemplate() throws IOException {
String templateName = "/ResultSheetTemplate_"+CompetitionApplication.getCurrentSupportedLocale().getLanguage()+".xls";
final InputStream resourceAsStream = app.getResourceAsStream(templateName);
if (resourceAsStream == null) {
throw new IOException("resource not found: " + templateName);} //$NON-NLS-1$
return resourceAsStream;
}
@Override
protected void getSortedLifters() {
this.lifters = LifterSorter.resultsOrderCopy(new LifterContainer(CompetitionApplication.getCurrent(),isExcludeNotWeighed()).getAllPojos(),
Ranking.TOTAL);
LifterSorter.assignMedals(lifters);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.spreadsheet.JXLSWorkbookStreamSource#postProcess(org.apache.poi.ss.usermodel.Workbook)
*/
@Override
protected void postProcess(Workbook workbook) {
if (Competition.invitedIfBornBefore() <= 0) {
zapCellPair(workbook,3,18);
}
final CompetitionSession currentCompetitionSession = app.getCurrentCompetitionSession();
if (currentCompetitionSession == null) {
zapCellPair(workbook,3,10);
}
}
}
| 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.mobile;
import java.net.URL;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.Window.CloseEvent;
public interface IRefereeConsole extends DecisionEventListener {
@Override
public abstract void updateEvent(final DecisionEvent updateEvent);
public abstract void refresh();
/**
* @param refereeIndex
*/
public abstract void setIndex(int refereeIndex);
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
public abstract boolean needsMenu();
/**
* @return
*/
public abstract String getFragment();
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#setParametersFromFragment(java.lang.String)
*/
public abstract void setParametersFromFragment();
/* Will be called when page is loaded.
* @see com.vaadin.terminal.URIHandler#handleURI(java.net.URL, java.lang.String)
*/
public abstract DownloadStream handleURI(URL context, String relativeUri);
/* Will be called when page is unloaded (including on refresh).
* @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window.CloseEvent)
*/
public abstract void windowClose(CloseEvent e);
}
| 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.mobile;
/**
* Attempt at using the TouchKit extension.
* Commented out: could not figure out how to reliably switch to full screen functions.
* @author jflamy
*
*/
public class TouchKitHome //extends TouchLayout
{
// @SuppressWarnings("unused")
// private static Logger logger = LoggerFactory.getLogger(TouchLayout.class);
//
// public class MJuryDisplay extends TouchLayout {
// public MJuryDisplay() {
//
// }
// }
//
// public class MJuryMemberSelect extends TouchLayout {
//
// }
//
// public class MPlatformSelect extends TouchLayout {
//
// }
//
// public class MRefereeSelect extends TouchLayout {
//
// MRefereeSelect() {
// TouchMenu menu = new TouchMenu();
// menu.addItem("1", new TouchCommand() {
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// ORefereeConsole refConsole = createRefConsole();
// TouchKitHome.this.fixLayout(refConsole);
// refConsole.setRefereeIndex(0);
// }});
// menu.addItem("2", new TouchCommand() {
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// ORefereeConsole refConsole = createRefConsole();
// TouchKitHome.this.fixLayout(refConsole);
// refConsole.setRefereeIndex(1);
// }});
// menu.addItem("3", new TouchCommand() {
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// ORefereeConsole refConsole = createRefConsole();
// TouchKitHome.this.fixLayout(refConsole);
// refConsole.setRefereeIndex(2);
// }});
// addComponent(menu);
// }
//
// }
//
// private TouchKitApplication app;
//
// public TouchKitHome() {
// app = (TouchKitApplication)CompetitionApplication.getCurrent();
//
// setCaption("Competition Pad");
//
// addComponent(new Label("<p>Refereeing functions for the "
// + "competition management application.</p>"
// , Label.CONTENT_XHTML));
//
// TouchMenu menu = new TouchMenu();
//
// menu.addItem("Platform", new TouchCommand() {
//
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// getParent().navigateTo(new MPlatformSelect());
// }
// });
//
// menu.addItem("Referee", new TouchCommand() {
//
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// getParent().navigateTo(new MRefereeSelect());
// }
// });
//
// menu.addItem("Jury Member", new TouchCommand() {
//
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// getParent().navigateTo(new MJuryMemberSelect());
// }
// });
//
// menu.addItem("Decision Display", new TouchCommand() {
//
// @Override
// public void itemTouched(TouchMenuItem selectedItem) {
// final RefereeDecisions refDecisions = createRefereeDecisions();
// addComponent(refDecisions);
// TouchKitHome.this.fixLayout(refDecisions);
// }
// });
//
// addComponent(menu);
// }
//
// /**
// * @return
// */
// private ORefereeConsole createRefConsole() {
// ORefereeConsole refConsole = new ORefereeConsole(false, "Refereeing");
// return refConsole;
// }
//
// /**
// * @param refIndex
// * @return
// */
// private RefereeDecisions createRefereeDecisions() {
// RefereeDecisions decisionLights = new RefereeDecisions(false, "DecisionLights", false);
// return decisionLights;
// }
//
// /**
// * @param component
// */
// private void fixLayout(Component component) {
// app.panel.setVisible(false);
// component.setSizeFull();
// final VerticalLayout content = (VerticalLayout)app.mainWindow.getContent();
// content.setSizeFull();
// content.addComponent(component);
// content.setExpandRatio(app.panel, 0);
// content.setExpandRatio(component, 100);
// }
}
| 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.mobile;
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.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.touchdiv.TouchDiv;
import org.vaadin.touchdiv.TouchDiv.TouchEvent;
import org.vaadin.touchdiv.TouchDiv.TouchListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Alignment;
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 MJuryConsole 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(MJuryConsole.class);
private Integer juryIndex = null;
private Label juryReminder = new Label();
private String platformName;
private String viewName;
private IDecisionController decisionController;
private TouchDiv red;
private TouchDiv white;
public MJuryConsole(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.getJuryDecisionController();
}
/**
* @param decisionController
*/
private void setupTop(final IDecisionController decisionController) {
top.setSizeFull();
top.setMargin(true);
top.setSpacing(true);
red = new TouchDiv("");
red.setHeight("90%");
red.setWidth("90%");
red.addStyleName("red");
red.addListener(new TouchListener(){
@Override
public void onTouch(TouchEvent event) {
new Thread(new Runnable() {
@Override
public void run() {
decisionController.decisionMade(juryIndex, false);
}
}).start();
redSelected();
}});
white = new TouchDiv("");
white.addStyleName("white");
white.setHeight("90%");
white.setWidth("90%");
white.addListener(new TouchListener(){
@Override
public void onTouch(TouchEvent event) {
new Thread(new Runnable() {
@Override
public void run() {
decisionController
.decisionMade(juryIndex, true);
}
}).start();
whiteSelected();
}});
top.addComponent(red);
top.setComponentAlignment(red,Alignment.MIDDLE_CENTER);
top.addComponent(white);
top.setComponentAlignment(white,Alignment.MIDDLE_CENTER);
top.setExpandRatio(red,50.0F);
top.setExpandRatio(white,50.0F);
}
/**
*
*/
private void whiteSelected() {
white.removeStyleName("decisionUnselected");
red.removeStyleName("decisionSelected");
white.addStyleName("decisionSelected");
red.addStyleName("decisionUnselected");
white.setValue("\u2714"); // heavy checkmark
red.setValue("");
resetBottom();
}
/**
*
*/
private void redSelected() {
white.removeStyleName("decisionSelected");
red.removeStyleName("decisionUnselected");
white.addStyleName("decisionUnselected");
red.addStyleName("decisionSelected");
white.setValue("");
red.setValue("\u2714"); // heavy checkmark
resetBottom();
}
/**
*
*/
private void setupBottom() {
bottom.setSizeFull();
bottom.setMargin(false);
juryReminder.setValue(juryLabel(juryIndex));
juryReminder.setSizeFull();
bottom.addComponent(juryReminder);
juryReminder.setStyleName("juryOk");
}
/**
* @param refereeIndex2
* @return
*/
private String juryLabel(Integer refereeIndex2) {
if (refereeIndex2 == null) refereeIndex2 = 0;
return Messages.getString("RefereeConsole.Jury", CompetitionApplication.getCurrentLocale()) + " "
+ (refereeIndex2 + 1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#updateEvent(org.concordiainternational.competition.decision.DecisionEvent)
*/
@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[juryIndex].accepted;
switch (updateEvent.getType()) {
case DOWN:
if (accepted == null) {
logger.info(
"jury #{} decision required after DOWN",
juryIndex + 1);
requireDecision();
}
break;
case WAITING:
if (accepted == null) {
logger.info(
"jury #{} decision required WAITING",
juryIndex + 1);
requireDecision();
}
break;
case UPDATE:
break;
case BLOCK:
// decisions are shown to the public; prevent refs from changing.
white.setEnabled(false);
red.setEnabled(false);
juryReminder.setStyleName("blocked");
//top.setEnabled(false);
break;
case RESET:
logger.info("jury #{} RESET", juryIndex + 1);
white.setStyleName("white");
red.setStyleName("red");
resetTop();
resetBottom();
requestRepaintAll();
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() {
juryReminder.setValue(Messages.getString("RefereeConsole.decisionRequired", CompetitionApplication.getCurrentLocale()));
juryReminder.setStyleName("refereeReminder");
//CompetitionApplication.getCurrent().getMainWindow().executeJavaScript("alert('wakeup')");
}
/**
* reset styles for top part
*/
private void resetTop() {
white.setEnabled(true);
red.setEnabled(true);
white.setValue("");
red.setValue("");
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#refresh()
*/
@Override
public void refresh() {
}
private void resetBottom() {
synchronized (app) {
juryReminder.setEnabled(true);
juryReminder.setValue(juryLabel(juryIndex));
juryReminder.setStyleName("juryOk");
}
app.push();
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#setRefereeIndex(int)
*/
@Override
public void setIndex(int refereeIndex) {
synchronized (app) {
this.juryIndex = refereeIndex;
juryReminder.setValue(juryLabel(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()
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#getFragment()
*/
@Override
public String getFragment() {
return viewName+"/"+(platformName == null ? "" : platformName)+"/"+((int)this.juryIndex+1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#setParametersFromFragment()
*/
@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 (juryIndex != null) {
setIndex(juryIndex);
}
}
/**
* 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)
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#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)
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#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.mobile;
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.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.touchdiv.TouchDiv;
import org.vaadin.touchdiv.TouchDiv.TouchEvent;
import org.vaadin.touchdiv.TouchDiv.TouchListener;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Alignment;
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 MRefereeConsole extends VerticalLayout implements DecisionEventListener, ApplicationView, CloseListener, URIHandler, IRefereeConsole {
private static final long serialVersionUID = 1L;
private HorizontalLayout top;
private HorizontalLayout bottom;
private SessionData masterData;
private CompetitionApplication app = CompetitionApplication.getCurrent();
private Logger logger = LoggerFactory.getLogger(MRefereeConsole.class);
private Integer refereeIndex = null;
private Label refereeReminder;
private String platformName;
private String viewName;
private IDecisionController decisionController;
private TouchDiv red;
private TouchDiv white;
public MRefereeConsole(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();
init();
}
/**
*
*/
protected void init() {
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) {
if (top == null) {
top = new HorizontalLayout();
}
top.setSizeFull();
top.setMargin(true);
top.setSpacing(true);
red = new TouchDiv("");
red.setHeight("90%");
red.setWidth("90%");
red.addStyleName("red");
red.addListener(new TouchListener(){
@Override
public void onTouch(TouchEvent event) {
redSelected();
new Thread(new Runnable() {
@Override
public void run() {
decisionController.decisionMade(refereeIndex, false);
}
}).start();
}});
white = new TouchDiv("");
white.addStyleName("white");
white.setHeight("90%");
white.setWidth("90%");
white.addListener(new TouchListener(){
@Override
public void onTouch(TouchEvent event) {
whiteSelected();
new Thread(new Runnable() {
@Override
public void run() {
decisionController
.decisionMade(refereeIndex, true);
}
}).start();
}});
top.addComponent(red);
top.setComponentAlignment(red,Alignment.MIDDLE_CENTER);
top.addComponent(white);
top.setComponentAlignment(white,Alignment.MIDDLE_CENTER);
top.setExpandRatio(red,50.0F);
top.setExpandRatio(white,50.0F);
}
/**
*
*/
private void whiteSelected() {
white.removeStyleName("decisionUnselected");
red.removeStyleName("decisionSelected");
white.addStyleName("decisionSelected");
red.addStyleName("decisionUnselected");
white.setValue("\u2714"); // heavy checkmark
red.setValue("");
doResetBottom();
}
/**
*
*/
private void redSelected() {
white.removeStyleName("decisionSelected");
red.removeStyleName("decisionUnselected");
white.addStyleName("decisionUnselected");
red.addStyleName("decisionSelected");
white.setValue("");
red.setValue("\u2714"); // heavy checkmark
disable();
doResetBottom();
}
/**
*
*/
private void setupBottom() {
refereeReminder = new Label();
refereeReminder.setValue(refereeLabel(refereeIndex));
refereeReminder.setSizeFull();
refereeReminder.setStyleName("refereeOk");
if (bottom == null) {
bottom = new HorizontalLayout();
} else {
bottom.removeAllComponents();
}
bottom.addComponent(refereeReminder);
bottom.setSizeFull();
bottom.setMargin(false);
}
/**
* @param refereeIndex2
* @return
*/
private String refereeLabel(Integer refereeIndex2) {
if (refereeIndex2 == null) refereeIndex2 = 0;
return Messages.getString("RefereeConsole.Referee", CompetitionApplication.getCurrentLocale()) + " "
+ (refereeIndex2 + 1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#updateEvent(org.concordiainternational.competition.decision.DecisionEvent)
*/
@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:
logger.trace("referee #{} UPDATE",refereeIndex + 1);
break;
case BLOCK:
logger.trace("referee #{} BLOCK", refereeIndex + 1);
// decisions are shown to the public; prevent refs from changing.
disable();
//top.setEnabled(false);
break;
case RESET:
logger.trace("referee #{} RESET", refereeIndex + 1);
reset();
break;
}
}
app.push();
}
}).start();
}
/**
*
*/
protected void disable() {
white.setEnabled(false);
red.setEnabled(false);
refereeReminder.setStyleName("blocked");
}
/**
* @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')");
}
private void reset() {
new Thread( new Runnable() {
@Override
public void run() {
top.removeAllComponents();
bottom.removeAllComponents();
MRefereeConsole.this.removeAllComponents();
init();
requestRepaintAll();
}
}).start();
}
// /**
// * reset styles for top part
// */
// private void resetTop() {
// white.setEnabled(true);
// red.setEnabled(true);
// white.setValue("");
// red.setValue("");
// }
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#refresh()
*/
@Override
public void refresh() {
}
/**
*
*/
protected void doResetBottom() {
refereeReminder.setEnabled(true);
refereeReminder.setValue(refereeLabel(refereeIndex));
refereeReminder.setStyleName("refereeOk");
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#setRefereeIndex(int)
*/
@Override
public void setIndex(int refereeIndex) {
synchronized (app) {
this.refereeIndex = refereeIndex;
UriFragmentUtility uriFragmentUtility = CompetitionApplication.getCurrent().getUriFragmentUtility();
uriFragmentUtility.setFragment(getFragment(), false);
setupBottom();
}
getDecisionController().addListener(this,refereeIndex);
app.push();
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#getFragment()
*/
@Override
public String getFragment() {
return viewName+"/"+(platformName == null ? "" : platformName)+"/"+((int)this.refereeIndex+1);
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#setParametersFromFragment()
*/
@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)
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#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)
*/
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.IRefereeConsole#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.mobile;
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.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.incubator.dashlayout.ui.HorDashLayout;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class RefereeDecisions extends VerticalLayout implements DecisionEventListener, ApplicationView {
private static final long serialVersionUID = 1L;
HorDashLayout top = new HorDashLayout();
Label[] decisionLights = new Label[3];
HorizontalLayout bottom = new HorizontalLayout();
SessionData masterData;
CompetitionApplication app = CompetitionApplication.getCurrent();
private Logger logger = LoggerFactory.getLogger(RefereeDecisions.class);
private String platformName;
private String viewName;
private boolean downShown;
private boolean juryMode;
private boolean shown;
public RefereeDecisions(boolean initFromFragment, String viewName, boolean publicFacing, boolean juryMode) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.juryMode = juryMode;
this.setStyleName("decisionPad");
this.app = CompetitionApplication.getCurrent();
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
createLights();
top.setMargin(false);
top.setSpacing(false);
setupBottom();
this.setSizeFull();
this.addComponent(top);
this.addComponent(bottom);
this.setExpandRatio(top, 90.0F);
this.setExpandRatio(bottom, 10.0F);
this.setMargin(false);
resetLights();
}
/**
*
*/
private void createLights() {
masterData = app.getMasterData(platformName);
if (juryMode) {
masterData.getJuryDecisionController().addListener(this);
} else {
masterData.getRefereeDecisionController().addListener(this);
}
top.setSizeFull();
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i] = new Label();
decisionLights[i].setSizeFull();
decisionLights[i].setStyleName("decisionLight");
decisionLights[i].addStyleName("juryLight");
top.addComponent(decisionLights[i]);
top.setExpandRatio(decisionLights[i], 100.0F / decisionLights.length);
}
}
private void setupBottom() {
bottom.setSizeFull();
Label bottomLabel = new Label(
juryMode
? Messages.getString("MobileMenu.JuryDecisions", CompetitionApplication.getCurrentLocale())
: Messages.getString("MobileMenu.RefDecisions", CompetitionApplication.getCurrentLocale()));
bottom.setStyleName(juryMode ? "juryDecisionsLabel" : "refereeDecisionsLabel");
bottomLabel.setSizeUndefined();
bottomLabel.setStyleName("refereeOk");
bottom.addComponent(bottomLabel);
bottom.setComponentAlignment(bottomLabel, Alignment.MIDDLE_CENTER);
}
@Override
public void updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
Decision[] decisions = updateEvent.getDecisions();
switch (updateEvent.getType()) {
case DOWN:
logger.debug("received DOWN event juryMode={}",juryMode);
downShown = true;
showLights(decisions, true, juryMode);
if (!juryMode) {
decisionLights[1].addStyleName("down");
}
break;
case WAITING:
logger.debug("received WAITING event");
showLights(decisions, true, juryMode);
break;
case UPDATE:
logger.debug("received UPDATE event {} && {}",juryMode,shown);
if ((juryMode && shown) || !juryMode) showLights(decisions, false, false);
if (!juryMode && downShown) decisionLights[1].addStyleName("down");
break;
case SHOW:
logger.debug("received SHOW event");
showLights(decisions, true, false);
if (!juryMode && downShown) decisionLights[1].addStyleName("down");
shown = true;
break;
case RESET:
logger.debug("received RESET event");
resetLights();
break;
case BLOCK:
if (!juryMode && downShown) decisionLights[1].removeStyleName("down");
break;
}
}
app.push();
}
}).start();
}
/**
* @param decisions
* @param showWaiting show lights while waiting for last referee
* @param doNotShowDecisions do not show the decisions as they are made
*/
private void showLights(Decision[] decisions, boolean showWaiting, boolean doNotShowDecisions) {
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i].setStyleName("decisionLight");
Boolean accepted = decisions[i].accepted;
if (accepted == null && showWaiting) {
decisionLights[i].addStyleName("waiting");
} else if (accepted != null && (!doNotShowDecisions)) {
decisionLights[i].addStyleName(accepted ? "lift" : "nolift");
} else {
decisionLights[i].addStyleName("undecided");
}
}
}
private void resetLights() {
synchronized (app) {
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i].setStyleName("decisionLight");
decisionLights[i].addStyleName("undecided");
decisionLights[i].setContentMode(Label.CONTENT_XHTML);
decisionLights[i].setValue(" ");
}
downShown = false;
shown = false;
}
app.push();
}
@Override
public void refresh() {
}
/* (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() {
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.mobile;
import java.net.URL;
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.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.LoadImage;
import org.concordiainternational.competition.ui.PlatesInfoEvent;
import org.concordiainternational.competition.ui.PlatesInfoEvent.PlatesInfoListener;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.SessionData.UpdateEvent;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.URIHandler;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Component;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
/**
* Display information about the current athlete and lift.
* Shows lifter information, decision lights, and plates loading diagram.
*
* @author jflamy
*
*/
public class MPlatesInfoView extends VerticalLayout implements
ApplicationView,
CloseListener,
PlatesInfoListener,
SessionData.UpdateEventListener,
URIHandler {
Logger logger = LoggerFactory.getLogger(MPlatesInfoView.class);
private static final long serialVersionUID = 2443396161202824072L;
private SessionData masterData;
private String platformName;
private String viewName;
private LoadImage plates;
private boolean ie;
private CompetitionApplication app;
public MPlatesInfoView(boolean initFromFragment, String viewName) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
app = CompetitionApplication.getCurrent();
this.addStyleName("loadChart");
boolean prevPusherDisabled = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
masterData = app.getMasterData(platformName);
if (app != masterData.getMasterApplication()) {
// we are not the master application; hide the menu bar.
Component menuComponent = app.components.menu;
if (menuComponent != null) menuComponent.setVisible(false);
menuComponent = app.getMobileMenu();
if (menuComponent != null) menuComponent.setVisible(false);
}
Platform.getByName(platformName);
this.setSizeFull();
this.setSpacing(true);
//horLayout = new HorizontalLayout();
WebApplicationContext context = (WebApplicationContext) app.getContext();
ie = context.getBrowser().isIE();
plates = new LoadImage(null);
plates.setMargin(true);
plates.addStyleName("zoomMedium");
//horLayout.addComponent(plates);
//horLayout.setSizeFull();
this.addComponent(plates);
this.setComponentAlignment(plates, Alignment.MIDDLE_CENTER);
// URI handler must remain, so is not part of the register/unRegister pair
app.getMainWindow().addURIHandler(this);
registerAsListener();
doDisplay();
} finally {
app.setPusherDisabled(prevPusherDisabled);
}
}
@Override
public void refresh() {
}
/**
* @param updateEvent
*/
private void doDisplay() {
synchronized (app) {
Platform.getByName(platformName);
Lifter currentLifter = masterData.getCurrentLifter();
Integer nextAttemptRequestedWeight = 0;
if (currentLifter != null) nextAttemptRequestedWeight = currentLifter.getNextAttemptRequestedWeight();
boolean done = (currentLifter != null && currentLifter.getAttemptsDone() >= 6) || nextAttemptRequestedWeight == 0;
plates.setVisible(false);
if (!done || ie) {
//logger.debug("recomputing image area: pusherDisabled = {}",app.getPusherDisabled());
plates.computeImageArea(masterData, masterData.getPlatform());
plates.setVisible(true);
//horLayout.setComponentAlignment(plates, Alignment.MIDDLE_CENTER);
//horLayout.setExpandRatio(plates, 80);
}
if (currentLifter == null) {
plates.setVisible(true);
plates.removeAllComponents();
plates.setCaption(Messages.getString("PlatesInfo.waiting", app.getLocale())); //$NON-NLS-1$
}
}
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);
}
/* (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 {
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (params.length >= 2) {
platformName = params[1];
} else {
platformName = CompetitionApplicationComponents.initPlatformName();
}
}
@Override
public void plateLoadingUpdate(PlatesInfoEvent event) {
//logger.debug("plateLoadingUpdate");
doDisplay();
}
/* 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 void registerAsListener() {
masterData.addListener(this); // weight changes
masterData.addBlackBoardListener(this); // changes in available plates
}
@Override
public void unregisterAsListener() {
masterData.removeListener(this); // weight changes
masterData.removeBlackBoardListener(this); // changes in available plates
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
//logger.debug("re-registering handlers for {} {}",this,relativeUri);
registerAsListener();
return null;
}
@Override
public void updateEvent(UpdateEvent updateEvent) {
doDisplay();
}
}
| 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.mobile;
import java.util.List;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.SessionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
public class MobileMenu extends VerticalLayout {
public static final String BUTTON_WIDTH = "6em"; //$NON-NLS-1$
public static final String BUTTON_NARROW_WIDTH = "4em"; //$NON-NLS-1$
public static final String BUTTON_HEIGHT = "3em"; //$NON-NLS-1$
private CompetitionApplication app;
private List<Platform> platforms;
private static Logger logger = LoggerFactory.getLogger(MobileMenu.class);
public MobileMenu() {
app = CompetitionApplication.getCurrent();
platforms = Platform.getAll();
if (platforms.size() > 1) {
final MPlatformSelect platformSelection = new MPlatformSelect();
this.addComponent(platformSelection);
}
final MRefereeSelect refereeSelection = new MRefereeSelect();
this.addComponent(refereeSelection);
final MRefereeDecisions refereeDecisions = new MRefereeDecisions();
this.addComponent(refereeDecisions);
final MJurySelect jurySelection = new MJurySelect();
this.addComponent(jurySelection);
final MJuryDecisions juryDecisions = new MJuryDecisions();
this.addComponent(juryDecisions);
final MPlatesInfo platesInfo = new MPlatesInfo();
this.addComponent(platesInfo);
this.setStyleName("mobileMenu"); //$NON-NLS-1$
this.setSpacing(true);
this.setMargin(true);
app.getMainWindow().executeJavaScript("scrollTo(0,1)"); //$NON-NLS-1$
}
public class MRefereeDecisions extends HorizontalLayout {
public MRefereeDecisions() {
this.setSpacing(true);
final Label label = new Label(Messages.getString("MobileMenu.RefDecisions",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
final NativeButton button = new NativeButton(Messages.getString("MobileMenu.Display",app.getLocale()), new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
RefereeDecisions refereeDecisions = createRefereeDecisions();
app.setMainLayoutContent(refereeDecisions);
}
});
button.setWidth(BUTTON_WIDTH);
button.setHeight(BUTTON_HEIGHT);
this.addComponent(button);
}
}
public class MJuryDecisions extends HorizontalLayout {
public MJuryDecisions() {
this.setSpacing(true);
final Label label = new Label(Messages.getString("MobileMenu.JuryDecisions",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
final NativeButton button = new NativeButton(Messages.getString("MobileMenu.Display",app.getLocale()), new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
RefereeDecisions refereeDecisions = createJuryDecisions();
app.setMainLayoutContent(refereeDecisions);
}
});
button.setWidth(BUTTON_WIDTH);
button.setHeight(BUTTON_HEIGHT);
this.addComponent(button);
}
}
public class MPlatesInfo extends HorizontalLayout {
public MPlatesInfo() {
this.setSpacing(true);
final Label label = new Label(Messages.getString("MobileMenu.Plates",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
final NativeButton button = new NativeButton(Messages.getString("MobileMenu.Display",app.getLocale()), new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
MPlatesInfoView plates = new MPlatesInfoView(false, Messages.getString("MobileMenu.PlatesTitle",app.getLocale())); //$NON-NLS-1$
app.setMainLayoutContent(plates);
}
});
button.setWidth(BUTTON_WIDTH);
button.setHeight(BUTTON_HEIGHT);
this.addComponent(button);
}
}
public class MJuryMemberSelect extends HorizontalLayout {
}
public class MPlatformSelect extends HorizontalLayout {
public MPlatformSelect() {
final Label label = new Label(Messages.getString("MobileMenu.Platforms",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
for (Platform platform: platforms) {
final String platformName = platform.getName();
final NativeButton button = new NativeButton(platformName, new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
app.setPlatformByName(platformName);
SessionData masterData = app.getMasterData(platformName);
logger.debug("new platform={}, new group = {}", platformName, masterData.getCurrentSession()); //$NON-NLS-1$
app.setCurrentCompetitionSession(masterData.getCurrentSession());
}
});
button.setWidth(BUTTON_WIDTH);
button.setHeight(BUTTON_HEIGHT);
this.addComponent(button);
}
}
}
public class MRefereeSelect extends HorizontalLayout {
MRefereeSelect() {
this.setSpacing(true);
final Label label = new Label(Messages.getString("MobileMenu.Referee",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
final NativeButton button1 = new NativeButton("1", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMRefereeConsole(0);
}
});
button1.setWidth(BUTTON_NARROW_WIDTH);
button1.setHeight(BUTTON_HEIGHT);
this.addComponent(button1);
final NativeButton button2 = new NativeButton("2", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMRefereeConsole(1);
}
});
button2.setWidth(BUTTON_NARROW_WIDTH);
button2.setHeight(BUTTON_HEIGHT);
this.addComponent(button2);
final NativeButton button3 = new NativeButton("3", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMRefereeConsole(2);
}
});
button3.setWidth(BUTTON_NARROW_WIDTH);
button3.setHeight(BUTTON_HEIGHT);
this.addComponent(button3);
}
}
public class MJurySelect extends HorizontalLayout {
MJurySelect() {
this.setSpacing(true);
final Label label = new Label(Messages.getString("MobileMenu.Jury",app.getLocale())); //$NON-NLS-1$
this.addComponent(label);
this.setComponentAlignment(label, Alignment.MIDDLE_LEFT);
final NativeButton button1 = new NativeButton("1", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMJuryConsole(0);
}
});
button1.setWidth(BUTTON_NARROW_WIDTH);
button1.setHeight(BUTTON_HEIGHT);
this.addComponent(button1);
final NativeButton button2 = new NativeButton("2", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMJuryConsole(1);
}
});
button2.setWidth(BUTTON_NARROW_WIDTH);
button2.setHeight(BUTTON_HEIGHT);
this.addComponent(button2);
final NativeButton button3 = new NativeButton("3", new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
CompetitionApplication.getCurrent().displayMJuryConsole(2);
}
});
button3.setWidth(BUTTON_NARROW_WIDTH);
button3.setHeight(BUTTON_HEIGHT);
this.addComponent(button3);
}
}
// /**
// * @return
// */
// private ORefereeConsole createRefConsole() {
// ORefereeConsole refConsole = new ORefereeConsole(false, "Refereeing");
// return refConsole;
// }
/**
* @param refIndex
* @return
*/
private RefereeDecisions createRefereeDecisions() {
RefereeDecisions decisionLights = new RefereeDecisions(false, "DecisionLights", false, false); //$NON-NLS-1$
return decisionLights;
}
/**
* @param refIndex
* @return
*/
private RefereeDecisions createJuryDecisions() {
RefereeDecisions decisionLights = new RefereeDecisions(false, "DecisionLights", false, true); //$NON-NLS-1$
return decisionLights;
}
}
| 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.mobile;
import org.concordiainternational.competition.ui.CompetitionApplication;
/**
* Attempt at using the TouchKit extension.
* Commented out: could not figure out how to reliably switch to full screen functions.
* @author jflamy
*
*/
public class TouchKitApplication extends CompetitionApplication {
private static final long serialVersionUID = 5474522369804563317L;
// @SuppressWarnings("unused")
// private static final Logger logger = LoggerFactory.getLogger(TouchKitApplication.class);
// public Window mainWindow;
// public TouchPanel panel;
//
// public TouchKitApplication() {
// super("/m/");
// }
//
// @Override
// public void init() {
// sharedInit();
// mainWindow = new Window("Refereeing");
// mainWindow.setSizeFull();
// setMainWindow(mainWindow);
//
// VerticalLayout vLayout = (VerticalLayout) mainWindow.getContent();
// vLayout.setMargin(false,false,false,false);
// vLayout.setSizeFull();
//
// panel = new TouchPanel();
// panel.setSizeFull();
// mainWindow.addComponent(panel);
// panel.navigateTo(new TouchKitHome());
//
// mainWindow.setApplication(this);
// setTheme("m");
// }
//
// @Override
// synchronized public void push() {
// pusher = this.ensurePusher();
// if (!pusherDisabled) {
// logger.debug("pushing with {} on window {}",pusher,mainWindow);
// pusher.push();
// }
// }
//
// /**
// * @return
// */
// @Override
// protected ICEPush ensurePusher() {
//
// if (pusher == null) {
// logger.debug("ensuring pusher");
// LoggerUtils.logException(logger, new Exception("ensurePusher wherefrom"));
// pusher = new ICEPush();
// mainWindow.addComponent(pusher);
// }
// return pusher;
// }
}
| 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.utils;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class to manage notifications from domain objects.
*
* This class allows a domain object to have multiple active editors; as long as
* there is an editor, the listener should be informed. When a domain object no
* longer has an active editor, it should stop broadcasting events to the
* listener.
*
* @author jflamy
*
* @param <Listener>
* the listening class, notified by E instances when they change
* @param <Editable>
* editable class, notifies the Listening class, edited by the Editor
* class
* @param <Editor>
* Edits the Editable, which notifies the Listener
*/
public class NotificationManager<Listener extends EventListener, Editable extends Notifier, Editor> {
Logger logger = LoggerFactory.getLogger(NotificationManager.class);
private static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
private Listener listener;
public NotificationManager(Listener listener) {
this.listener = listener;
}
Map<Editable, Set<Editor>> editorMap = new HashMap<Editable, Set<Editor>>();
synchronized public void addEditor(Editable editable, Editor editor) {
Set<Editor> set = editorMap.get(editable);
if (set == null) {
set = new HashSet<Editor>();
set.add(editor);
editorMap.put(editable, set);
} else {
set.add(editor);
}
editable.addListener(listener);
logger.debug(dump());
}
synchronized public void removeEditor(Editable editable, Editor editor) {
Set<Editor> set = editorMap.get(editable);
if (set == null) {
// nothing to do.
} else {
set.remove(editor);
if (set.size() == 0) {
// no-one is editing editable anymore
editorMap.remove(editable);
}
}
if (set == null || set.size() == 0) {
// no-one is editing the editable anymore, listener can
// stop listening for updates.
editable.removeListener(listener);
}
logger.debug(dump());
}
public String dump() {
Set<Entry<Editable, Set<Editor>>> entrySet = editorMap.entrySet();
StringBuffer sb = new StringBuffer();
sb.append("Notifiers and Editors for listener "); //$NON-NLS-1$
sb.append(listener);
sb.append(LINE_SEPARATOR);
for (Entry<Editable, Set<Editor>> entry : entrySet) {
sb.append(" "); //$NON-NLS-1$
sb.append(entry.getKey());
sb.append(": "); //$NON-NLS-1$
Set<Editor> editors = entry.getValue();
for (Editor editor : editors) {
sb.append(editor);
sb.append("; "); //$NON-NLS-1$
}
sb.append(LINE_SEPARATOR);
}
return sb.toString();
}
}
| 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.utils;
import java.util.Locale;
import org.concordiainternational.competition.i18n.Messages;
import com.vaadin.data.Item;
import com.vaadin.data.hbnutil.HbnContainer.EntityItem;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Table;
public class ItemAdapter {
/**
* @param item
* @return
*/
@SuppressWarnings("rawtypes")
public static Object getObject(final Item item) {
Object obj = null;
if (item instanceof EntityItem) {
obj = ((EntityItem) item).getPojo();
} else if (item instanceof BeanItem) {
obj = ((BeanItem<?>) item).getBean();
} else {
throw new ClassCastException(Messages.getString(
"ItemAdapter.NeitherBeanItemNorEntityItem", Locale.getDefault()) + item.getClass() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (obj == null)
throw new AssertionError(Messages.getString("ItemAdapter.ItemHasNoAttachedObject", Locale.getDefault())); //$NON-NLS-1$
return obj;
}
public static Object getObject(Table table, Object itemId) {
Item item = table.getItem(itemId);
return getObject(item);
}
}
| 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.utils;
import java.lang.reflect.Method;
public class EventHelper {
public static Method findMethod(Class<?> eventClass, Class<?> eventListenerClass, String eventProcessingMethodName) {
try {
final Method method = eventListenerClass.getDeclaredMethod(eventProcessingMethodName, eventClass);
return method;
} catch (final java.lang.NoSuchMethodException e) {
throw new java.lang.RuntimeException(e);
}
}
}
| 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.utils;
import java.util.Locale;
public interface Localized {
public void setLocale(Locale l);
public Locale getLocale();
}
| 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.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jflamy
*
*/
public class Coefficients {
static Logger logger = LoggerFactory.getLogger(Coefficients.class);
private static HashMap<Integer, Float> smm = null;
static Properties props = null;
static Double menCoefficient = null;
static Double womenCoefficient = null;
static Double menMaxWeight = null;
static Double womenMaxWeight = null;
/**
* @return
* @throws IOException
*/
private static HashMap<Integer, Float> loadSMM() {
if (props == null) loadProps();
smm = new HashMap<Integer, Float>((int) (props.size() * 1.4));
for (Entry<Object, Object> entry : props.entrySet()) {
String curKey = (String) entry.getKey();
if (curKey.startsWith("smm.")) {
smm.put(Integer.valueOf(curKey.replace("smm.", "")), Float.valueOf((String) entry.getValue()));
}
}
return smm;
}
/**
* @throws IOException
*/
private static void loadProps() {
props = new Properties();
try {
InputStream stream = CompetitionApplication.getCurrent().getResourceAsStream("/sinclair.properties");
props.load(stream);
// props.list(System.err);
} catch (IOException e) {
LoggerUtils.logException(logger, e);
}
}
/**
* @throws IOException
*
*/
private static void loadCoefficients() {
if (props == null) loadProps();
menCoefficient = Double.valueOf((String) props.get("sinclair.menCoefficient"));
menMaxWeight = Double.valueOf((String) props.get("sinclair.menMaxWeight"));
womenCoefficient = Double.valueOf((String) props.get("sinclair.womenCoefficient"));
womenMaxWeight = Double.valueOf((String) props.get("sinclair.womenMaxWeight"));
}
/**
* @return
*/
public static Double menCoefficient() {
if (menCoefficient == null) loadCoefficients();
return menCoefficient;
}
/**
* @return
*/
public static Double womenCoefficient() {
if (womenCoefficient == null) loadCoefficients();
return womenCoefficient;
}
/**
* @return
*/
public static Double menMaxWeight() {
if (menMaxWeight == null) loadCoefficients();
return menMaxWeight;
}
/**
* @return
*/
public static Double womenMaxWeight() {
if (womenMaxWeight == null) loadCoefficients();
return womenMaxWeight;
}
/**
* @param age
* @return the Sinclair-Malone-Meltzer Coefficient for that age.
* @throws IOException
*/
public static Float getSMMCoefficient(Integer age) throws IOException {
if (smm == null) loadSMM();
if (age <= 30) return 1.0F;
if (age >= 90) return smm.get(90);
return smm.get(age);
}
}
| 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.utils;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* An IdentitySet that uses reference-equality instead of object-equality.
* According to its special function it violates some design contracts of the
* <code>Set</code> interface.
*
* @author <a href="mailto:ralf DOT joachim AT syscon DOT eu">Ralf Joachim</a>
* @version $Revision: 7491 $ $Date: 2006-04-13 10:49:49 -0600 (Thu, 13 Apr
* 2006) $
* @since 0.9.9
*/
public final class IdentitySet implements Set<Object>, Serializable {
private static final long serialVersionUID = -558036228345356324L;
// --------------------------------------------------------------------------
/** Default number of buckets. */
private static final int DEFAULT_CAPACITY = 17;
/** Default load factor. */
private static final float DEFAULT_LOAD = 0.75f;
/** Default number of entries. */
private static final int DEFAULT_ENTRIES = (int) (DEFAULT_CAPACITY * DEFAULT_LOAD);
/** Default factor to increment capacity. */
private static final int DEFAULT_INCREMENT = 2;
/** First prime number to check is 3 as we prevent 2 by design. */
private static final int FIRST_PRIME_TO_CHECK = 3;
// --------------------------------------------------------------------------
/** Number of buckets. */
private int _capacity;
/** Maximum number of entries before rehashing. */
private int _maximum;
/** Buckets. */
private Entry[] _buckets;
/** Number of map entries. */
private int _entries = 0;
// --------------------------------------------------------------------------
/**
* Construct a set with default capacity.
*/
public IdentitySet() {
_capacity = DEFAULT_CAPACITY;
_maximum = DEFAULT_ENTRIES;
_buckets = new Entry[DEFAULT_CAPACITY];
}
/**
* Construct a set with given capacity.
*
* @param capacity
* The capacity of entries this set should be initialized with.
*/
public IdentitySet(final int capacity) {
_capacity = capacity;
_maximum = (int) (capacity * DEFAULT_LOAD);
_buckets = new Entry[capacity];
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#clear()
*/
@Override
public void clear() {
_capacity = DEFAULT_CAPACITY;
_maximum = DEFAULT_ENTRIES;
_buckets = new Entry[DEFAULT_CAPACITY];
_entries = 0;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#size()
*/
@Override
public int size() {
return _entries;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#isEmpty()
*/
@Override
public boolean isEmpty() {
return (_entries == 0);
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#add(java.lang.Object)
*/
@Override
public boolean add(final Object key) {
int hash = System.identityHashCode(key);
int index = hash % _capacity;
if (index < 0) {
index = -index;
}
Entry entry = _buckets[index];
Entry prev = null;
while (entry != null) {
if (entry.getKey() == key) {
// There is already a mapping for this key.
return false;
}
prev = entry;
entry = entry.getNext();
}
if (prev == null) {
// There is no previous entry in this bucket.
_buckets[index] = new Entry(key, hash);
} else {
// Next entry is empty so we have no mapping for this key.
prev.setNext(new Entry(key, hash));
}
_entries++;
if (_entries > _maximum) {
rehash();
}
return true;
}
/**
* Rehash the map into a new array with increased capacity.
*/
private void rehash() {
long nextCapacity = _capacity * DEFAULT_INCREMENT;
if (nextCapacity > Integer.MAX_VALUE) {
return;
}
nextCapacity = nextPrime(nextCapacity);
if (nextCapacity > Integer.MAX_VALUE) {
return;
}
int newCapacity = (int) nextCapacity;
Entry[] newBuckets = new Entry[newCapacity];
Entry entry = null;
Entry temp = null;
Entry next = null;
int newIndex = 0;
for (int index = 0; index < _capacity; index++) {
entry = _buckets[index];
while (entry != null) {
next = entry.getNext();
newIndex = entry.getHash() % newCapacity;
if (newIndex < 0) {
newIndex = -newIndex;
}
temp = newBuckets[newIndex];
if (temp == null) {
// First entry of the bucket.
entry.setNext(null);
} else {
// Hook entry into beginning of the buckets chain.
entry.setNext(temp);
}
newBuckets[newIndex] = entry;
entry = next;
}
}
_capacity = newCapacity;
_maximum = (int) (newCapacity * DEFAULT_LOAD);
_buckets = newBuckets;
}
/**
* Find next prime number greater than minimum.
*
* @param minimum
* The minimum (exclusive) value of the next prime number.
* @return The next prime number greater than minimum.
*/
private long nextPrime(final long minimum) {
long candidate = ((minimum + 1) / 2) * 2 + 1;
while (!isPrime(candidate)) {
candidate += 2;
}
return candidate;
}
/**
* Check for prime number.
*
* @param candidate
* Number to be checked for being a prime number.
* @return <code>true</code> if the given number is a prime number
* <code>false</code> otherwise.
*/
private boolean isPrime(final long candidate) {
if ((candidate / 2) * 2 == candidate) {
return false;
}
long stop = candidate / 2;
for (long i = FIRST_PRIME_TO_CHECK; i < stop; i += 2) {
if ((candidate / i) * i == candidate) {
return false;
}
}
return true;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#contains(java.lang.Object)
*/
@Override
public boolean contains(final Object key) {
int hash = System.identityHashCode(key);
int index = hash % _capacity;
if (index < 0) {
index = -index;
}
Entry entry = _buckets[index];
while (entry != null) {
if (entry.getKey() == key) {
return true;
}
entry = entry.getNext();
}
return false;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#remove(java.lang.Object)
*/
@Override
public boolean remove(final Object key) {
int hash = System.identityHashCode(key);
int index = hash % _capacity;
if (index < 0) {
index = -index;
}
Entry entry = _buckets[index];
Entry prev = null;
while (entry != null) {
if (entry.getKey() == key) {
// Found the entry.
if (prev == null) {
// First element in bucket matches.
_buckets[index] = entry.getNext();
} else {
// Remove the entry from the chain.
prev.setNext(entry.getNext());
}
_entries--;
return true;
}
prev = entry;
entry = entry.getNext();
}
return false;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#iterator()
*/
@Override
public Iterator<Object> iterator() {
return new IdentityIterator();
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#toArray()
*/
@Override
public Object[] toArray() {
Object[] result = new Object[_entries];
int j = 0;
for (int i = 0; i < _capacity; i++) {
Entry entry = _buckets[i];
while (entry != null) {
result[j++] = entry.getKey();
entry = entry.getNext();
}
}
return result;
}
/**
* {@inheritDoc}
*
* @see java.util.Collection#toArray(java.lang.Object[])
*/
@Override
@SuppressWarnings("unchecked")
public Object[] toArray(final Object[] a) {
Object[] result = a;
if (result.length < _entries) {
result = (Object[]) java.lang.reflect.Array.newInstance(result.getClass().getComponentType(), _entries);
}
int j = 0;
for (int i = 0; i < _capacity; i++) {
Entry entry = _buckets[i];
while (entry != null) {
result[j++] = entry.getKey();
entry = entry.getNext();
}
}
while (j < result.length) {
result[j++] = null;
}
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < _capacity; i++) {
Entry entry = _buckets[i];
while (entry != null) {
sb.append(" "); //$NON-NLS-1$
sb.append(entry.getKey().toString());
entry = entry.getNext();
}
}
return sb.toString();
}
/**
* In contrast with the design contract of the <code>Set</code> interface
* this method has not been implemented and throws a
* <code>UnsupportedOperationException</code>.
*
* {@inheritDoc}
*
* @see java.util.Set#containsAll
*/
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
/**
* This optional method has not been implemented for
* <code>IdentitySet</code> instead it throws a
* <code>UnsupportedOperationException</code> as defined in the
* <code>Set</code> interface.
*
* {@inheritDoc}
*
* @see java.util.Set#addAll
*/
@Override
public boolean addAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
/**
* This optional method has not been implemented for
* <code>IdentitySet</code> instead it throws a
* <code>UnsupportedOperationException</code> as defined in the
* <code>Set</code> interface.
*
* {@inheritDoc}
*
* @see java.util.Set#removeAll
*/
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
/**
* This optional method has not been implemented for
* <code>IdentitySet</code> instead it throws a
* <code>UnsupportedOperationException</code> as defined in the
* <code>Set</code> interface.
*
* {@inheritDoc}
*
* @see java.util.Set#retainAll
*/
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
// --------------------------------------------------------------------------
/**
* An entry of the <code>IdentitySet</code>.
*/
public final class Entry implements Serializable {
private static final long serialVersionUID = 1L;
/** Key of entry. */
private Object _key;
/** Identity hashcode of key. */
private int _hash;
/** Reference to next entry. */
private Entry _next = null;
/**
* Construct an entry.
*
* @param key
* Key of entry.
* @param hash
* Identity hashcode of key.
*/
public Entry(final Object key, final int hash) {
_key = key;
_hash = hash;
}
/**
* Get key of entry.
*
* @return Key of entry.
*/
public Object getKey() {
return _key;
}
/**
* Get identity hashcode of key.
*
* @return Identity hashcode of key.
*/
public int getHash() {
return _hash;
}
/**
* Set reference to next entry.
*
* @param next
* New reference to next entry.
*/
public void setNext(final Entry next) {
_next = next;
}
/**
* Get reference to next entry.
*
* @return Reference to next entry.
*/
public Entry getNext() {
return _next;
}
}
// --------------------------------------------------------------------------
/**
* An iterator over all entries of the <code>IdentitySet</code>.
*/
private class IdentityIterator implements Iterator<Object> {
/** Index of the current bucket. */
private int _index = 0;
/** The next entry to be returned. <code>null</code> when there is none. */
private Entry _next = _buckets[0];
private Entry _lastReturned;
/**
* Construct a iterator over all entries of the <code>IdentitySet</code>
* .
*/
public IdentityIterator() {
if (_entries > 0) {
while ((_next == null) && (++_index < _capacity)) {
_next = _buckets[_index];
}
}
}
/**
* {@inheritDoc}
*
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return (_next != null);
}
/**
* {@inheritDoc}
*
* @see java.util.Iterator#next()
*/
@Override
public Object next() {
Entry entry = _next;
if (entry == null) {
throw new NoSuchElementException();
}
_lastReturned = entry;
_next = entry.getNext();
while ((_next == null) && (++_index < _capacity)) {
_next = _buckets[_index];
}
return entry.getKey();
}
/**
* Because we are using a simple chaining list implementation, the
* straightforward implementation is ok.
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
IdentitySet.this.remove(_lastReturned.getKey());
}
}
// --------------------------------------------------------------------------
}
| 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.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.slf4j.Logger;
public class LoggerUtils {
public static void logException(Logger logger2, Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
logger2.info(sw.toString());
}
}
| 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.utils;
import java.util.EventListener;
public interface Notifier {
public void addListener(EventListener listener);
public void removeListener(EventListener listener);
}
| 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.i18n;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "i18n.messages"; //$NON-NLS-1$
// private static final ResourceBundle RESOURCE_BUNDLE =
// ResourceBundle.getBundle(BUNDLE_NAME);
private Messages() {
}
public static String getString(String key, Locale locale) {
try {
// ResourceBundle caches the bundles, so this is not as inefficient
// as it seems.
return ResourceBundle.getBundle(BUNDLE_NAME, locale).getString(key);
} catch (MissingResourceException e) {
return '«' + key + '»';
}
}
public static String getStringNullIfMissing(String key, Locale locale) {
try {
// ResourceBundle caches the bundles, so this is not as inefficient
// as it seems.
return ResourceBundle.getBundle(BUNDLE_NAME, locale).getString(key);
} catch (MissingResourceException e) {
return null;
}
}
public static String getStringWithException(String key, Locale locale) throws MissingResourceException {
return ResourceBundle.getBundle(BUNDLE_NAME, locale).getString(key);
}
}
| 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.i18n;
import java.util.Locale;
import com.vaadin.Application;
import com.vaadin.Application.CustomizedSystemMessages;
/**
* CustomizedSystemMessages extension that relies on a properties file. This
* class also maintains the language for each user, so that different users can
* get the message in their own language (once the session is under way).
*
* @author jflamy
*/
public class LocalizedSystemMessages extends CustomizedSystemMessages {
private static final long serialVersionUID = 295825699005962978L;
/**
* Locale associated with the current thread (ThreadLocal maintains a map
* from the thread an associated value so there is in effect one thread
* Locale per thread.)
*/
static ThreadLocal<Locale> threadLocale = new ThreadLocal<Locale>();
/**
* Sets the default language used for system messages emitted before the
* application has fully initialized, for example on a server restart. This
* will happen if the system message is issued before
* {@link #setThreadLocale(Locale)} has been called by the application
* (normally in an override of {@link Application#init()}.
*
* Override this method if the JVM default locale (often en_US if running on
* a server) is inappropriate.
*
* @return locale for messages issued before the Application has set its own
* locale.
*/
protected Locale getDefaultSystemMessageLocale() {
return Locale.getDefault();
}
/**
* Called by the application if it wishes to have its
* LocalizedSystemMessages shown in the user's language.
*
* @param application
* @param locale
*/
public void setThreadLocale(Locale locale) {
threadLocale.set(locale);
}
/**
* Get the application's current locale.
*
* @param application
* @return locale for the application
*/
public Locale getThreadLocale() {
Locale loc = threadLocale.get();
if (loc == null) {
return getDefaultSystemMessageLocale();
} else {
return loc;
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getCommunicationErrorCaption()
*/
@Override
public String getCommunicationErrorCaption() {
return (communicationErrorNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.communicationErrorCaption", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getCommunicationErrorMessage()
*/
@Override
public String getCommunicationErrorMessage() {
return (communicationErrorNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.communicationErrorMessage", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getInternalErrorCaption()
*/
@Override
public String getInternalErrorCaption() {
return (internalErrorNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.internalErrorCaption", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getInternalErrorMessage()
*/
@Override
public String getInternalErrorMessage() {
return (internalErrorNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.internalErrorMessage", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getOutOfSyncCaption()
*/
@Override
public String getOutOfSyncCaption() {
return (outOfSyncNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.outOfSyncCaption", getThreadLocale()) //$NON-NLS-1$
: null);
}
/**
* @return the notification message, or null for no message
*/
@Override
public String getOutOfSyncMessage() {
return (outOfSyncNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.outOfSyncMessage", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getSessionExpiredCaption()
*/
@Override
public String getSessionExpiredCaption() {
return (sessionExpiredNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.sessionExpiredCaption", getThreadLocale()) //$NON-NLS-1$
: null);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.Application.SystemMessages#getSessionExpiredMessage()
*/
@Override
public String getSessionExpiredMessage() {
return (sessionExpiredNotificationEnabled ? Messages.getString(
"LocalizedSystemMessages.sessionExpiredMessage", getThreadLocale()) //$NON-NLS-1$
: 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.i18n;
import java.util.Locale;
import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;
/**
* Example application for using localized SystemMessages configured from a
* properties file.
*
* @author jflamy
*/
@SuppressWarnings("serial")
public class LocalizedApplication extends Application {
private static LocalizedSystemMessages localizedMessages;
@Override
public void init() {
// change the system message language in case any are shown while "init"
// is running.
LocalizedSystemMessages msg = (LocalizedSystemMessages) getSystemMessages();
msg.setThreadLocale(this.getLocale()); // by default getLocale() comes
// from the user's browser.
// the following defines what will happen before and after each http
// request.
attachHttpRequestListener();
// create the initial look.
// buildMainLayout();
}
/**
* Get localized SystemMessages for this application.
*
* <p>
* This method is static; we need to call
* {@link LocalizedSystemMessages#setThreadLocale(Locale)} to change the
* language that will be used for this thread. This is typically done in a
* {@link TransactionListener#transactionStart(Application, Object)} method
* in order to associate the Locale with the thread processing the HTTP
* request.
* </p>
*
* @return the LocalizedSystemMessages for this application
*/
public static SystemMessages getSystemMessages() {
if (localizedMessages == null) localizedMessages = new LocalizedSystemMessages() {
@Override
protected Locale getDefaultSystemMessageLocale() {
return Locale.CANADA_FRENCH;
}
};
return localizedMessages;
}
/**
* Attach a listener for the begin and end of every HTTP request in the
* session. (Vaadin "transaction" equals "http request".)
*/
private void attachHttpRequestListener() {
getContext().addTransactionListener(new TransactionListener() {
private static final long serialVersionUID = 316709294485669937L;
@Override
public void transactionEnd(Application application, Object transactionData) {
}
@Override
public void transactionStart(Application application, Object transactionData) {
// force system messages to appear in user's lanquage
((LocalizedSystemMessages) getSystemMessages()).setThreadLocale(getLocale());
}
});
}
}
| 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 OJuryConsole 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(OJuryConsole.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 OJuryConsole(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 org.concordiainternational.competition.ui.components.ApplicationView;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
@SuppressWarnings("serial")
public class EmptyView extends VerticalLayout implements ApplicationView {
@Override
public void refresh() {
}
@Override
public boolean needsMenu() {
return true;
}
@Override
public void setParametersFromFragment() {
}
@Override
public String getFragment() {
return "";
}
@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;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Set;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.RuleViolationException;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
import org.concordiainternational.competition.ui.generators.CommonColumnGenerator;
import org.concordiainternational.competition.ui.list.GenericHbnList;
import org.concordiainternational.competition.utils.ItemAdapter;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
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.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
import com.vaadin.ui.Window;
public class SessionList extends GenericHbnList<CompetitionSession> implements ApplicationView {
private static final long serialVersionUID = -6455130090728823622L;
private String viewName;
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(SessionList.class);
public SessionList(boolean initFromFragment, String viewName) {
super(CompetitionApplication.getCurrent(), CompetitionSession.class, Messages.getString(
"GroupList.Groups", CompetitionApplication.getCurrent().getLocale())); //$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$
"weighInTime", //$NON-NLS-1$
"competitionTime", //$NON-NLS-1$
"platform", //$NON-NLS-1$
"categories", //$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("Group.name", locale), //$NON-NLS-1$
Messages.getString("Group.weighInTime", locale), //$NON-NLS-1$
Messages.getString("Group.competitionTime", locale), //$NON-NLS-1$
Messages.getString("Group.platform", locale), //$NON-NLS-1$
Messages.getString("Group.categories", locale), //$NON-NLS-1$
Messages.getString("Common.actions", locale), //$NON-NLS-1$
};
return COL_HEADERS;
}
/**
* Computed columnts
*/
@Override
protected void addGeneratedColumns() {
super.addGeneratedColumns();
table.removeGeneratedColumn("categories"); //$NON-NLS-1$
table.addGeneratedColumn("categories", new CommonColumnGenerator(app)); //$NON-NLS-1$
// table.removeGeneratedColumn("weighInTime"); //$NON-NLS-1$
// table.addGeneratedColumn("weighInTime", new CommonColumnGenerator(app)); //$NON-NLS-1$
// table.removeGeneratedColumn("competitionTime"); //$NON-NLS-1$
// table.addGeneratedColumn("competitionTime", new CommonColumnGenerator(app)); //$NON-NLS-1$
table.removeGeneratedColumn("platform"); //$NON-NLS-1$
table.addGeneratedColumn("platform", new CommonColumnGenerator(app)); //$NON-NLS-1$
setExpandRatios();
//table.setColumnExpandRatio("name", 0.3F);
table.setColumnExpandRatio("actions", 1.2F);
}
/**
* Default actions: delete lifters, edit.
*/
@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("GroupList.GroupMustBeEmpty", app
.getLocale()));
}
}
});
actions.addComponent(del);
Button clear = new Button(Messages.getString("GroupList.clear", app.getLocale())); //$NON-NLS-1$
clear.addListener(new ClickListener() {
private static final long serialVersionUID = 5204920602544644705L;
@Override
public void buttonClick(ClickEvent event) {
clearCompetitionSession((Long) itemId);
}
});
actions.addComponent(clear);
Button edit = new Button(Messages.getString("Common.edit", app.getLocale())); //$NON-NLS-1$
edit.addListener(new ClickListener() {
private static final long serialVersionUID = 5204920602544644705L;
@Override
public void buttonClick(ClickEvent event) {
editCompetitionSession((Long) itemId, table.getItem(itemId));
}
});
actions.addComponent(edit);
return actions;
}
});
}
/**
* Remove all lifters in the CompetitionSession
* @param itemId
*/
private void clearCompetitionSession(Long itemId) {
Item item = table.getContainerDataSource().getItem(itemId);
CompetitionSession competitionSession = (CompetitionSession) ItemAdapter.getObject(item);
int nbLifters = 0;
Set<Lifter> lifters = competitionSession.getLifters();
if (lifters != null && lifters.size() > 0) {
nbLifters = lifters.size();
competitionSession.deleteLifters((CompetitionApplication) app);
}
Locale locale = CompetitionApplication.getCurrentLocale();
String messageTemplate = Messages.getString("GroupList.erased", locale); //$NON-NLS-1$
app.getMainWindow().showNotification(MessageFormat.format(messageTemplate,nbLifters));
}
/**
* @param itemId
* @param item2
*/
private void editCompetitionSession(Long itemId, Item item2) {
CompetitionSession competitionSession = (CompetitionSession) ItemAdapter.getObject(item2);
SessionForm form = new SessionForm();
form.setItemDataSource(item2);
form.setReadOnly(false);
Window editingWindow = new Window(competitionSession.getName());
form.setWindow(editingWindow);
form.setParentList(this);
editingWindow.getContent().addComponent(form);
app.getMainWindow().addWindow(editingWindow);
editingWindow.setHeight("90%");
editingWindow.setWidth("40em");
editingWindow.center();
}
/* (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 java.text.MessageFormat;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
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.i18n.Messages;
import org.concordiainternational.competition.ui.components.ApplicationView;
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 org.vaadin.overlay.CustomOverlay;
import com.vaadin.data.Item;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
/**
* This class defines the screen layout for the announcer.
* <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>
* <ul>
* Editing the bottom part triggers recalculation of the lifting order; this in
* turn triggers an update event to all layouts that display a lifter list
* (including this one).
* </ul>
* </p>
*
* @author jflamy
*
*/
public class AnnouncerView extends VerticalSplitPanel implements
ApplicationView,
SessionData.UpdateEventListener,
EditingView,
Window.CloseListener,
URIHandler
{
private static final long serialVersionUID = 7881028819569705161L;
private static final Logger logger = LoggerFactory.getLogger(AnnouncerView.class);
public static final boolean PUSHING = true;
/** remove message after this delay (ms) */
private static final int messageRemovalMs = 5000;
private HorizontalLayout topPart;
private LifterInfo announcerInfo;
private LiftList liftList;
private LifterCardEditor lifterCardEditor;
private CompetitionApplication app;
private boolean stickyEditor = false;
private SessionData masterData;
Mode mode;
private String platformName;
private String viewName;
private String groupName;
private Notifique notifications;
public enum Mode {
ANNOUNCER, TIMEKEEPER, MARSHALL, DISPLAY
}
/**
* Create view.
*
* @param mode
*/
public AnnouncerView(boolean initFromFragment, String viewName, Mode mode) {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.app = CompetitionApplication.getCurrent();
this.mode = mode;
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
}
if (app.getPlatform() == null || !platformName.equals(app.getPlatformName())) {
app.setPlatformByName(platformName);
}
masterData = app.getMasterData(platformName);
if (mode == Mode.ANNOUNCER) {
final CompetitionSession currentGroup = masterData.getCurrentSession();
masterData.setAnnouncerView(this);
masterData.setMasterApplication(this.app);
if (groupName != null && groupName.length() > 0) {
switchGroup(new CompetitionSessionLookup(app).lookup(groupName));
} else {
app.setCurrentCompetitionSession(currentGroup);
if (currentGroup != null) {
groupName = currentGroup.getName();
}
}
}
// right hand side shows information that the announcer reads aloud
announcerInfo = new LifterInfo("topPart", masterData, mode, this); //$NON-NLS-1$
announcerInfo.addStyleName("currentLifterSummary"); //$NON-NLS-1$
//announcerInfo.setWidth(7.0F, Sizeable.UNITS_CM); //$NON-NLS-1$
announcerInfo.setMargin(true);
// left side is the lifting order, as well as the menu to switch groups.
// note: not used in timekeeper view, but until we refactor the code
// there is legacy information found inside the list that should not be there
// so we leave it there.
liftList = new LiftList(masterData, this, mode);
liftList.table.setPageLength(15);
liftList.table.setSizeFull();
liftList.setSizeFull();
topPart = new HorizontalLayout();
setupNotifications();
synchronized (app) {
boolean prevDisabled = app.getPusherDisabled();
app.setPusherDisabled(true);
topPart.setSizeFull();
if (mode != Mode.TIMEKEEPER) {
topPart.addComponent(liftList);
topPart.setExpandRatio(liftList, 100.0F);
}
announcerInfo.setSizeUndefined();
topPart.addComponent(announcerInfo);
if (mode != Mode.TIMEKEEPER) {
topPart.setExpandRatio(announcerInfo, 3.5F);
}
topPart.setComponentAlignment(announcerInfo, Alignment.TOP_LEFT);
this.setFirstComponent(topPart);
loadFirstLifterInfo(masterData,
WebApplicationConfiguration.DEFAULT_STICKINESS);
adjustSplitBarLocation();
// we are now fully initialized
masterData.setAllowAll(false);
// URI handler must remain, so is not part of the register/unRegister pair
app.getMainWindow().addURIHandler(this);
registerAsListener();
if (masterData.lifters.isEmpty()) {
logger.debug(
"switching masterData.lifters {}", masterData.lifters); //$NON-NLS-1$
switchGroup(app.getCurrentCompetitionSession());
} else {
logger.debug(
"not switching masterData.lifters {}", masterData.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 masterData
*/
public void loadFirstLifterInfo(SessionData groupData) {
final Lifter firstLifter = liftList.getFirstLifter();
logger.debug("*** first lifter = {}", firstLifter); //$NON-NLS-1$
final Item firstLifterItem = liftList.getFirstLifterItem();
announcerInfo.loadLifter(firstLifter, groupData);
updateLifterEditor(firstLifter, firstLifterItem);
liftList.clearSelection();
}
/**
* Update the lifter editor and the information panels with the first
* lifter.
*
* @param masterData
*/
public void loadFirstLifterInfo(SessionData groupData, boolean sticky) {
loadFirstLifterInfo(groupData);
if (lifterCardEditor != null) {
lifterCardEditor.setSticky(sticky);
}
}
/**
* Update the lifter editor and the information panels with the first
* lifter.
*
* @param masterData
*/
public void editFirstLifterInfo(SessionData groupData, boolean sticky) {
final Lifter firstLifter = liftList.getFirstLifter();
final Item firstLifterItem = liftList.getFirstLifterItem();
updateLifterEditor(firstLifter, firstLifterItem);
if (lifterCardEditor != null) {
lifterCardEditor.setSticky(sticky);
}
liftList.clearSelection();
}
/**
* @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(liftList, 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$
masterData.noCurrentLifter();
lifterCardEditor = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.concordiainternational.competition.ui.Refreshable#refresh()
*/
@Override
public void refresh() {
logger.debug("start refresh ----------{}", mode); //$NON-NLS-1$
CategoryLookup.getSharedInstance().reload();
liftList.refresh();
setStickyEditor(false, false);
masterData.getRefereeDecisionController().reset();
loadFirstLifterInfo(masterData);
logger.debug("end refresh ----------{}", mode); //$NON-NLS-1$
}
/**
* Set the split bar location
*/
void adjustSplitBarLocation() {
if (mode == Mode.TIMEKEEPER) {
this.setSplitPosition(0, true);
} else {
// compute percentage of split bar.
float height = app.getMainWindow().getHeight();
if (height > 0) {
this.setSplitPosition((int) ((height - 225) * 100 / height));
} else {
this.setSplitPosition(65);
}
}
}
/**
* 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(masterData, 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) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
if (updateEvent.getForceRefresh()) {
logger.debug(
"updateEvent() received in {} view -- forced refresh. ----------------------------------", mode); //$NON-NLS-1$
refresh();
} else {
logger.debug(
"updateEvent() received in {} view first is now: {}", AnnouncerView.this, updateEvent.getCurrentLifter()); //$NON-NLS-1$
liftList.updateTable();
loadFirstLifterInfo(masterData,
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(updateEvent.getCurrentLifter(),
liftList.getGroupData());
}
// updateLifterEditor(updateEvent.getCurrentLifter(),
// liftList.getFirstLifterItem());
}
}
app.push();
}
}).start();
}
/**
* Reload data according to this session's (CompetitionApplication) current
* lifter group.
*
* @param newSession
*/
private void switchGroup(final CompetitionSession newSession) {
CompetitionSession oldSession = masterData.getCurrentSession();
boolean switching = oldSession != newSession;
if (mode == Mode.ANNOUNCER) {
if (switching) {
logger.debug("=============== switching from {} to group {}", oldSession, newSession); //$NON-NLS-1$
logger.debug("=============== modifying group data {}", masterData, (newSession != null ? newSession.getName() : null)); //$NON-NLS-1$
masterData.setCurrentSession(newSession);
}
CompetitionSession currentCompetitionSession = masterData.getCurrentSession();
if (currentCompetitionSession != null) {
groupName = currentCompetitionSession.getName();
} else {
groupName = "";
}
if (switching) {
CompetitionApplication.getCurrent().getUriFragmentUtility().setFragment(getFragment(), false);
}
}
}
@Override
public void setCurrentSession(CompetitionSession competitionSession) {
setStickyEditor(false, false);
switchGroup(competitionSession);
}
/**
* @param masterData
* the masterData to set
*/
@Override
public void setSessionData(SessionData sessionData) {
this.masterData = sessionData;
}
/**
* @return the masterData
*/
public SessionData getGroupData() {
return masterData;
}
public void selectFirstLifter() {
liftList.clearSelection();
}
/* (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;
}
}
private void setupNotifications() {
// Notification area. Full width.
notifications = new Notifique(true);
notifications.setWidth("100%");
notifications.setVisibleCount(3);
// Hide messages when clicked anywhere (not only with the close
// button)
notifications.setClickListener(new Notifique.ClickListener() {
private static final long serialVersionUID = 1L;
@Override
public void messageClicked(Message message) {
message.hide();
}
});
// Display as overlay in top of the main window
Window mainWindow = CompetitionApplication.getCurrent().getMainWindow();
CustomOverlay ol = new CustomOverlay(notifications, mainWindow);
ol.addStyleName("timeStoppedNotifications");
mainWindow.addComponent(ol);
//notifications.add((Resource)null,"1!",true,Notifique.Styles.VAADIN_ORANGE,true);
}
public void displayNotification(Mode mode2, TimeStoppedNotificationReason reason) {
Locale locale = app.getLocale();
String message;
if (mode2 == null) {
message = Messages.getString("TimeStoppedNotificationReason."+reason.name(),locale);
} else {
message = MessageFormat.format(
Messages.getString("TimeStoppedNotificationReason.NotificationFormat", locale),
Messages.getString("LiftList."+mode2.name(), locale),
Messages.getString("TimeStoppedNotificationReason."+reason.name(),locale));
}
final Message addedMessage = notifications.add((Resource)null,message,true,Notifique.Styles.VAADIN_ORANGE,true);
switch (reason) {
case CURRENT_LIFTER_CHANGE:
// the announcer must acknowledge explicitly
if (this.mode != Mode.ANNOUNCER) {
scheduleMessageRemoval(addedMessage, messageRemovalMs);
}
break;
default:
// remove automatically
scheduleMessageRemoval(addedMessage, messageRemovalMs);
break;
}
}
/**
* @param addedMessage
* @param i
*/
public void scheduleMessageRemoval(final Message addedMessage, int msgRemovalMs) {
new Timer().schedule(new TimerTask(){
@Override
public void run() {
// remove message, push to client.
if (addedMessage.isVisible()) {
synchronized (app) {
addedMessage.hide();
}
app.push();
}
}
}, msgRemovalMs);
}
/**
* Register all handlers that listen to model or outside events.
*/
@Override
public void registerAsListener() {
logger.trace("registering listeners");
masterData.addListener(this);
}
/**
*
*/
@Override
public void unregisterAsListener() {
logger.trace("unregistering registering listeners");
masterData.removeListener(this);
announcerInfo.unregisterAsListener();
if (lifterCardEditor != null) {
lifterCardEditor.unregisterAsListener();
}
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
logger.trace("registering URI listeners");
registerAsListener();
return null;
}
/**
* @return the notifications
*/
public Notifique getNotifications() {
return notifications;
}
/**
* @return the liftList
*/
public LiftList getLiftList() {
return liftList;
}
}
| 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.list;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.LifterContainer;
import org.concordiainternational.competition.ui.CompetitionApplication;
import com.vaadin.Application;
/**
* This class specializes the List component to use the LifterContainer class.
* LifterContainer takes into account the currently active filters set in the
* application.
*
* @author jflamy
*
*/
public abstract class LifterHbnList extends GenericHbnList<Lifter> {
private static final long serialVersionUID = 1L;
public LifterHbnList(Application app, String caption) {
super(app, Lifter.class, caption);
}
/**
* Load container content to Table
*/
@Override
protected void loadData() {
final LifterContainer cont = new LifterContainer((CompetitionApplication) app);
table.setContainerDataSource(cont);
}
}
| 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.list;
import java.util.Iterator;
import org.concordiainternational.competition.data.CategoryLookup;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.SessionForm;
import org.concordiainternational.competition.ui.generators.CommonFieldFactory;
import org.concordiainternational.competition.ui.generators.FieldTable;
import org.concordiainternational.competition.utils.ItemAdapter;
import com.vaadin.Application;
import com.vaadin.data.Item;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
import com.vaadin.event.Action;
import com.vaadin.event.Action.Handler;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;
public abstract class GenericList<T> extends VerticalLayout {
private static final long serialVersionUID = -3014859089271158928L;
protected Application app;
public Table table;
protected Class<T> parameterizedClass;
private String tableCaption;
protected Component tableToolbar;
protected Button toggleEditModeButton;
protected Button addRowButton;
public GenericList(Application app, Class<T> parameterizedClass, String caption) {
super();
this.app = app;
this.parameterizedClass = parameterizedClass;
this.tableCaption = caption;
}
/**
* @param app
* @param parameterizedClass
* @param caption
*/
protected void init() {
buildView();
}
/**
* Builds a simple view for application with Table and a row of buttons
* below it.
*/
protected void buildView() {
final CompetitionApplication app1 = CompetitionApplication.getCurrent();
// we synchronize because specializations of this class may do all sorts of
// event-based things in their construction, and we don't want them to call
// the push() method while in the constructor (this causes the session to drop.)
synchronized (app1) {
boolean prevDisabled = app1.getPusherDisabled();
try {
app1.setPusherDisabled(true);
this.setSizeFull();
this.setMargin(true);
tableToolbar = createTableToolbar();
this.addComponent(tableToolbar);
populateAndConfigureTable();
this.addComponent(table);
positionTable();
setButtonVisibility();
} finally {
app1.setPusherDisabled(prevDisabled);
}
}
}
/**
*
*/
protected void positionTable() {
// make table consume all extra space
this.setSizeFull();
this.setExpandRatio(table, 1);
table.setSizeFull();
}
/**
* Create a "toolbar" above the table that contains a caption, and some
* buttons.
*/
protected Component createTableToolbar() {
HorizontalLayout tableToolbar1 = new HorizontalLayout();
tableToolbar1.setStyleName("tableWithButtons"); //$NON-NLS-1$
tableToolbar1.setMargin(true);
tableToolbar1.setSpacing(true);
createToolbarButtons(tableToolbar1);
for (Iterator<?> iterator = tableToolbar1.getComponentIterator(); iterator.hasNext();) {
Component component = (Component) iterator.next();
tableToolbar1.setComponentAlignment(component, Alignment.MIDDLE_LEFT);
}
// add the caption first
if (getTableCaption() != null) {
final HorizontalLayout hl = new HorizontalLayout();
final Label cap = new Label(getTableCaption());
cap.setHeight("1.2em"); //$NON-NLS-1$
hl.setStyleName("title"); //$NON-NLS-1$
hl.addComponent(cap);
hl.setComponentAlignment(cap, Alignment.MIDDLE_LEFT);
tableToolbar1.addComponent(hl, 0);
tableToolbar1.setComponentAlignment(hl, Alignment.MIDDLE_LEFT);
}
return tableToolbar1;
}
/**
*
*/
protected void populateAndConfigureTable() {
// FieldTable always generates fields to ensure consistent formatting.
table = new FieldTable();
table.setWidth("100%"); //$NON-NLS-1$
table.setSelectable(true);
table.setImmediate(true);
table.setColumnCollapsingAllowed(true);
// load the data (this enables the table to know what fields are
// available).
loadData(); // table.getContainerDataSource() returns the datasource
if (table.getContainerDataSource().size() > 0) {
// enhance table
setTableFieldFactory();
addGeneratedColumns(); // add editing buttons in a generated cell.
addRowContextMenu();
// set visibility and ordering
setVisibleColumns();
setColumnHeaders();
// hide editing buttons if not editable
if (!table.isEditable()) {
table.removeGeneratedColumn("actions"); //$NON-NLS-1$
}
table.setPageLength(30);
table.setCacheRate(2.0);
} else {
table.setVisibleColumns(new Object[] {});
}
}
protected void addGeneratedColumns() {
}
/**
* Handles the creation of fields when the table is built in editable mode.
* By default, the same factory used by default for Form items is used.
*/
protected void setTableFieldFactory() {
table.setTableFieldFactory(new CommonFieldFactory((HbnSessionManager) app));
}
/**
* Add context menu to the table rows.
*/
protected void addRowContextMenu() {
// add context menus for rows
table.addActionHandler(new Handler() {
private static final long serialVersionUID = -6577539154616303085L;
Action add = new Action(Messages.getString("Common.addRow", app.getLocale())); //$NON-NLS-1$
Action remove = new Action(Messages.getString("Common.deleteThisRow", app.getLocale())); //$NON-NLS-1$
Action[] actions = new Action[] { add, remove };
@Override
public Action[] getActions(Object target, Object sender) {
return actions;
}
@Override
public void handleAction(Action action, Object sender, Object targetId) {
if (action == add) {
newItem();
} else if (action == remove) {
deleteItem(targetId);
}
}
});
}
/**
* @param targetId
*/
public void deleteItem(Object targetId) {
table.removeItem(targetId);
}
/**
* Adds new row to Table and selects new row. Table will delegate Item
* creation to its container.
*/
public Object newItem() {
Object newItemId = table.addItem();
// open in announcerLiftEditor window unless table is in content
// editable mode
if (!table.isEditable()) {
table.setValue(newItemId);
}
return newItemId;
}
/**
* @param tableToolbar1
*/
protected void createToolbarButtons(HorizontalLayout tableToolbar1) {
}
/**
* This method is used in response to a button click.
*/
public void toggleEditable() {
table.setEditable(!table.isEditable());
setButtonVisibility();
}
protected abstract void setButtonVisibility();
protected abstract void clearCache();
protected abstract void loadData();
public boolean isEditable() {
return table.isEditable();
}
/**
* @param tableCaption
* the tableCaption to set
*/
public void setTableCaption(String tableCaption) {
this.tableCaption = tableCaption;
}
/**
* @return the tableCaption
*/
public String getTableCaption() {
return tableCaption;
}
abstract protected String[] getColHeaders();
abstract protected String[] getColOrder();
/**
* Defines which fields from the container and the generated columns will
* actually be visible, and in which order they will be displayed.
*/
protected void setVisibleColumns() {
final String[] colOrder = getColOrder();
table.setVisibleColumns(colOrder);
}
/**
* Defines the readable headers for the table columns
*
* @return
*/
protected void setColumnHeaders() {
final String[] colHeaders = getColHeaders();
table.setColumnHeaders(colHeaders);
}
/**
* @param tableToolbar
* the tableToolbar to set
*/
public void setTableToolbar(Component tableToolbar) {
this.replaceComponent(this.tableToolbar, tableToolbar);
this.tableToolbar = tableToolbar;
}
/**
* @return the tableToolbar
*/
public Component getTableToolbar() {
return tableToolbar;
}
public void refresh() {
Component oldTable = table;
CategoryLookup.getSharedInstance().reload();
this.populateAndConfigureTable();
this.replaceComponent(oldTable, table);
this.positionTable();
}
/**
* Guess expansion ratios.
* Empirical; there is probably a better way.
*/
protected void setExpandRatios() {
Object[] visibleColumns = table.getVisibleColumns();
for (int i = 0; i < visibleColumns.length; i++) {
Object columnId = visibleColumns[i];
if (columnId.equals("lastName") ||columnId.equals("firstName")) {
table.setColumnExpandRatio(columnId, 1.0F);
} else {
table.setColumnExpandRatio(columnId, 0.0F);
}
}
}
protected void editCompetitionSession(Object itemId, Item item) {
if (itemId == null) {
CompetitionApplication.getCurrent().getMainWindow().showNotification(
Messages.getString("ResultList.sessionNotSelected", CompetitionApplication.getCurrentLocale()),
Notification.TYPE_ERROR_MESSAGE);
return;
}
SessionForm form = new SessionForm();
form.setItemDataSource(item);
form.setReadOnly(false);
CompetitionSession competitionSession = (CompetitionSession) ItemAdapter.getObject(item);
//logger.debug("retrieved session {} {}",System.identityHashCode(competitionSession), competitionSession.getReferee3());
Window editingWindow = new Window(competitionSession.getName());
form.setWindow(editingWindow);
form.setParentList(this);
editingWindow.getContent().addComponent(form);
app.getMainWindow().addWindow(editingWindow);
editingWindow.setWidth("40em");
editingWindow.center();
}
}
| 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.list;
import org.concordiainternational.competition.i18n.Messages;
import com.vaadin.Application;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
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.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
public abstract class GenericHbnList<T> extends GenericList<T> {
private static final long serialVersionUID = 8085082497600453476L;
public GenericHbnList(Application app, Class<T> parameterizedClass, String caption) {
super(app, parameterizedClass, caption);
}
/**
* Load container content to Table
*/
@Override
protected void loadData() {
// System.err.println("GenericHbnList: loadData()");
final HbnContainer<T> cont = new HbnContainer<T>(parameterizedClass, (HbnSessionManager) app);
table.setContainerDataSource(cont);
}
@SuppressWarnings("unchecked")
@Override
public void clearCache() {
// System.err.println("GenericHbnList: clearCache()");
((HbnContainer<T>) table.getContainerDataSource()).clearCache();
}
/**
* By default, add an action column with "delete" button.
*/
@Override
protected void addGeneratedColumns() {
// action buttons on each row
addDefaultActions();
}
/**
* Default actions: delete.
*/
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) {
deleteItem(itemId);
}
});
// actions.addComponent(del);
// return actions;
return del;
}
});
}
/**
* @param tableToolbar1
*/
@Override
protected void createToolbarButtons(HorizontalLayout tableToolbar1) {
toggleEditModeButton = new Button("", this, "toggleEditable"); //$NON-NLS-1$ //$NON-NLS-2$
tableToolbar1.addComponent(toggleEditModeButton);
addRowButton = new Button(Messages.getString("Common.addRow", app.getLocale()), this, "newItem"); //$NON-NLS-1$ //$NON-NLS-2$
tableToolbar1.addComponent(addRowButton);
setButtonVisibility();
setDefaultActions();
}
/**
* This method is used in response to a button click.
*/
@Override
public void toggleEditable() {
super.toggleEditable();
setDefaultActions();
}
/**
* Make sure that if the table is editable its actions are visible.
*/
protected void setDefaultActions() {
if (table != null) {
if (!table.isEditable()) {
table.removeGeneratedColumn("actions"); //$NON-NLS-1$
table.setSizeFull();
} else {
this.addDefaultActions();
}
}
}
@Override
protected void setButtonVisibility() {
if (table == null) {
addRowButton.setVisible(false);
toggleEditModeButton.setVisible(false);
return;
}
if (table.isEditable()) {
toggleEditModeButton.setCaption(Messages.getString("Common.done", app.getLocale())); //$NON-NLS-1$
toggleEditModeButton.setVisible(true);
addRowButton.setVisible(true);
} else {
toggleEditModeButton.setCaption(Messages.getString("Common.edit", app.getLocale())); //$NON-NLS-1$
toggleEditModeButton.setVisible(true);
addRowButton.setVisible(false);
}
}
@Override
protected String[] getColHeaders() {
return null;
}
@Override
protected String[] getColOrder() {
return null;
}
@Override
protected void positionTable() {
super.positionTable();
table.setSelectable(false);
}
}
| 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.list;
import java.io.Serializable;
import java.util.List;
import com.vaadin.Application;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.data.hbnutil.HbnContainer.HbnSessionManager;
import com.vaadin.data.util.BeanItemContainer;
/**
* Normally we would use an HbnContainer directly, but we need to sort on the
* lifting order, which we do not want written to the database. HbnContainer
* uses the database to sort, so we have to create our own container as a
* wrapper. The resulting BeanItemContainer is used to feed the table.
*
*
* @author jflamy
* @param <T>
*/
public abstract class GenericBeanList<T extends Serializable> extends GenericList<T> {
private static final long serialVersionUID = -5396475029309979597L;
protected List<T> allPojos;
public GenericBeanList(Application app, Class<T> parameterizedClass, String caption) {
super(app, parameterizedClass, caption);
}
/**
* Additional initializations, once super.populateAndConfigureTable() (and
* hence loadData()) has been done.
*/
@Override
protected void init() {
super.init();
}
/**
* Load container content to Table. We create a BeanItemContainer to gain
* sorting flexibility. Note: this routine is invoked as part of the super()
* chain in the constructor, and before our own init is called.
*/
@Override
protected void loadData() {
final HbnContainer<T> hbnCont = new HbnContainer<T>(parameterizedClass, (HbnSessionManager) app);
allPojos = hbnCont.getAllPojos();
final BeanItemContainer<T> cont = new BeanItemContainer<T>(parameterizedClass,allPojos);
table.setContainerDataSource(cont);
}
@Override
public void clearCache() {
// the following is brute force!
//System.err.println("GenericBeanList: clearCache()"); //$NON-NLS-1$
table = null;
populateAndConfigureTable();
}
}
| 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.List;
import java.util.Locale;
import org.concordiainternational.competition.data.Competition;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.publicAddress.PublicAddressForm;
import org.concordiainternational.competition.ui.AnnouncerView.Mode;
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.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.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
/**
* This class displays the lifting order for lifters for the announcer,
* timekeeper and marshal consoles.
*
* @author jflamy
*
*/
public class LiftList extends GenericBeanList<Lifter> implements
Property.ValueChangeListener, // change in table value = change in selected row
EditableList {
static final Logger logger = LoggerFactory.getLogger(LiftList.class);
private static final long serialVersionUID = 148461976217706535L;
private EditingView parentView;
transient private SessionData masterDataForCurrentPlatform = null; // do not serialize
private static String[] NATURAL_COL_ORDER = null;
private static String[] COL_HEADERS = null;
private Mode mode;
public LiftList(SessionData groupData, EditingView parentView, AnnouncerView.Mode mode) {
super(CompetitionApplication.getCurrent(), Lifter.class, buildCaption(mode, groupData)); //$NON-NLS-1$
logger.trace("new."); //$NON-NLS-1$
this.parentView = parentView;
this.mode = mode;
masterDataForCurrentPlatform = groupData;
init();
}
/**
* @param mode
* @return
*/
private static String buildCaption(AnnouncerView.Mode mode, SessionData groupData) {
CompetitionApplication current = CompetitionApplication.getCurrent();
final String role = Messages.getString(
"LiftList." + mode.toString(), current.getLocale()); //$NON-NLS-1$
if (Platform.getSize() == 1) {
return role;
} else {
final String currentPlatformName = " " + current.getPlatformName(); //$NON-NLS-1$
return role + currentPlatformName;
}
}
/**
* 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 masterDataForCurrentPlatform;
}
@Override
public void refresh() {
logger.debug("start refresh liftList**************{}", mode); //$NON-NLS-1$
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 liftList**************{}", mode); //$NON-NLS-1$
}
@Override
public void setGroupData(SessionData data) {
this.masterDataForCurrentPlatform = 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.
// clearSelection();
parentView.setStickyEditor(true); // since the user selected
// explicitly, ignore changes
// by others.
}
}
}
@Override
protected void addGeneratedColumns() {
// the following columns will be read-only.
final CommonColumnGenerator columnGenerator = new CommonColumnGenerator(app);
table.addGeneratedColumn("snatch1ActualLift", columnGenerator); //$NON-NLS-1$
table.addGeneratedColumn("snatch2ActualLift", columnGenerator); //$NON-NLS-1$
table.addGeneratedColumn("snatch3ActualLift", columnGenerator); //$NON-NLS-1$
table.addGeneratedColumn("cleanJerk1ActualLift", columnGenerator); //$NON-NLS-1$
table.addGeneratedColumn("cleanJerk2ActualLift", columnGenerator); //$NON-NLS-1$
table.addGeneratedColumn("cleanJerk3ActualLift", columnGenerator); //$NON-NLS-1$
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.
if (mode == AnnouncerView.Mode.ANNOUNCER) {
SessionSelect groupSelect = new SessionSelect((CompetitionApplication) app, app.getLocale(),parentView);
tableToolbar1.addComponent(groupSelect);
final Button refreshButton = new Button(Messages.getString("ResultList.Refresh", app.getLocale())); //$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$
masterDataForCurrentPlatform.refresh(true);
}
};
refreshButton.addListener(refreshClickListener);
tableToolbar1.addComponent(refreshButton);
}
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(LiftList.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.category", locale), //$NON-NLS-1$
Messages.getString("Lifter.bodyWeight", locale), //$NON-NLS-1$
Messages.getString("Lifter.club", locale), //$NON-NLS-1$
Messages.getString("Lifter.nextRequestedWeight", 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$
};
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$
(Competition.isMasters() ? "mastersLongCategory" //$NON-NLS-1$
: "category"), //$NON-NLS-1$
"bodyWeight", //$NON-NLS-1$
"club", //$NON-NLS-1$
"nextAttemptRequestedWeight", //$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$
};
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() {
logger.debug("loadData for {}, size={}", mode, masterDataForCurrentPlatform.lifters.size()); //$NON-NLS-1$
logger.debug("masterDataForCurrentPlatform={}", masterDataForCurrentPlatform); //$NON-NLS-1$
List<Lifter> lifters = masterDataForCurrentPlatform.getAttemptOrder();
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.setColumnWidth("lastName",100);
table.setColumnWidth("firstName",100);
table.setColumnExpandRatio("lastName",100F);
table.setColumnExpandRatio("firstName",100F);
table.setColumnWidth("birthDate",30);
table.setColumnWidth("category",30);
table.setColumnWidth("bodyWeight",45);
table.setColumnWidth("nextAttemptRequestedWeight",30);
table.setColumnWidth("lotNumber",30);
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 sortTableInLiftingOrder() {
table.sort(new String[] { "liftOrderRank" }, new boolean[] { true }); //$NON-NLS-1$
}
/**
* Sorts the lifters in the correct order in response to a change in the
* masterDataForCurrentPlatform. Informs listeners that the order has been updated.
*/
void updateTable() {
// update our own user interface
this.sortTableInLiftingOrder(); // 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.components;
import org.concordiainternational.competition.decision.Decision;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
public class DecisionLightsWindow extends HorizontalLayout implements DecisionEventListener {
private static final long serialVersionUID = 1L;
Label[] decisionLights = new Label[3];
CompetitionApplication app = CompetitionApplication.getCurrent();
private Logger logger = LoggerFactory.getLogger(DecisionLightsWindow.class);
private boolean immediateMode = false;
private boolean publicFacing;
private boolean shown = false;
public DecisionLightsWindow(boolean immediateMode, boolean publicFacing) {
this.app = CompetitionApplication.getCurrent();
this.publicFacing = publicFacing;
this.immediateMode = immediateMode;
createLights();
this.setMargin(true);
this.setSpacing(true);
resetLights();
}
/**
* Create the red/white display rectangles for decisions.
*/
private void createLights() {
logger.debug("createLights");
this.setSizeFull();
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i] = new Label();
decisionLights[i].setSizeFull();
decisionLights[i].setStyleName("decisionLight");
this.addComponent(decisionLights[i]);
this.setComponentAlignment(decisionLights[i], Alignment.MIDDLE_CENTER);
this.setExpandRatio(decisionLights[i], 100.0F / decisionLights.length);
}
}
@Override
public void updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
Decision[] decisions = updateEvent.getDecisions();
switch (updateEvent.getType()) {
case DOWN:
logger.debug("received DOWN event");
doDown();
if (immediateMode) {
showLights(decisions);
// decisionLights[1].addStyleName("down");
} else {
// decisionLights[1].setStyleName("decisionLight");
// decisionLights[1].addStyleName("undecided");
}
for (int i = 0; i < decisions.length; i++) {
if (decisions[i].accepted == null) {
// do nothing; maybe show in yellow in Jury Mode ?
}
}
break;
case WAITING:
logger.debug("received WAITING event");
for (int i = 0; i < decisions.length; i++) {
if (decisions[i].accepted == null) {
// do nothing; maybe show in yellow in Jury Mode ?
}
}
break;
case UPDATE:
logger.debug("received UPDATE event");
DecisionLightsWindow.this.removeStyleName("down");
if (immediateMode || shown) {
logger.debug("showing immediateMode={} shown={}",immediateMode, shown);
showLights(decisions);
} else {
logger.debug("not showing {} {}",immediateMode, shown);
}
break;
case SHOW:
logger.debug("received SHOW event, removing down");
DecisionLightsWindow.this.removeStyleName("down");
showLights(decisions);
break;
case BLOCK:
logger.debug("received BLOCK event, removing down");
DecisionLightsWindow.this.removeStyleName("down");
showLights(decisions);
break;
case RESET:
logger.debug("received RESET event");
DecisionLightsWindow.this.removeStyleName("down");
resetLights();
break;
default:
logger.debug("received default");
break;
}
}
app.push();
}
}).start();
}
/**
* show down signal in window.
*/
public void doDown() {
this.addStyleName("down");
//decisionLights[1].addStyleName("down");
}
/**
* @param decisions
*/
private void showLights(Decision[] decisions) {
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i].setStyleName("decisionLight");
Boolean accepted = null;
if (publicFacing) {
accepted = decisions[i].accepted;
} else {
// display in reverse order relative to what public sees
accepted = decisions[decisionLights.length-1-i].accepted;
}
if (decisions[i] != null && accepted != null) {
decisionLights[i].addStyleName(accepted ? "lift" : "nolift");
} else {
decisionLights[i].addStyleName("undecided");
}
}
shown = true;
}
private void resetLights() {
synchronized(app) {
for (int i = 0; i < decisionLights.length; i++) {
decisionLights[i].setStyleName("decisionLight");
decisionLights[i].addStyleName("undecided");
decisionLights[i].setContentMode(Label.CONTENT_XHTML);
decisionLights[i].setValue(" ");
}
}
shown = false;
app.push();
}
public void refresh() {
}
/**
* @param refereeIndex2
* @return
*/
@SuppressWarnings("unused")
private String refereeLabel(int refereeIndex2) {
return Messages.getString("ORefereeConsole.Referee", CompetitionApplication.getCurrentLocale()) + " "
+ (refereeIndex2 + 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.components;
import java.io.Serializable;
import java.util.Set;
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 com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.ui.ListSelect;
@SuppressWarnings("unchecked")
public class PlatformSelect extends ListSelect implements Serializable {
private static final long serialVersionUID = -5471881649385421098L;
HbnContainer<Platform> dataSource;
CompetitionApplication app;
/**
* @param competitionApplication
* @param locale
* @return
*/
public PlatformSelect() {
final PlatformSelect platformSelect = this;
app = CompetitionApplication.getCurrent();
dataSource = new HbnContainer<Platform>(Platform.class, app);
platformSelect.setContainerDataSource(dataSource);
platformSelect.setItemCaptionPropertyId("name"); //$NON-NLS-1$
platformSelect.setImmediate(true);
platformSelect.setNullSelectionAllowed(true);
platformSelect.setNullSelectionItemId(null);
platformSelect.setRows(1);
}
@Override
public String toString() {
Set<Long> PlatformIds = (Set<Long>) getValue();
if (PlatformIds == 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 curPlatformId : PlatformIds) {
// Item s = (categories.getItem(curPlatformId));
Platform curPlatform = (Platform) ItemAdapter.getObject(dataSource.getItem(curPlatformId));
sb.append(curPlatform.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
}
}
}
| 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.components;
import java.io.File;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Locale;
import javax.servlet.ServletContext;
import org.concordiainternational.competition.data.Platform;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.LoadWindow;
import org.concordiainternational.competition.ui.SessionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
public class Menu extends MenuBar implements Serializable {
private static final long serialVersionUID = -3809346951739483448L;
protected static final Logger logger = LoggerFactory.getLogger(Menu.class);
private LoadWindow loadComputerWindow;
public Menu() {
final CompetitionApplication competitionApplication = CompetitionApplication.getCurrent();
final Locale locale = competitionApplication.getLocale();
MenuBar menu = this;
menu.setWidth("100%"); //$NON-NLS-1$
MenuItem console = createConsoleMenu(menu, competitionApplication, locale);
createAnnouncerMenuItem(console, locale);
createChangesMenuItem(console, locale);
createTimeKeeperMenuItem(console, locale);
MenuItem projectors = createProjectorsMenuItem(menu, competitionApplication, locale);
createDisplayMenuItem(projectors, competitionApplication, locale, "dlp");
createDisplayMenuItem(projectors, competitionApplication, locale, "lcd");
createDisplayMenuItem(projectors, competitionApplication, locale, "pale");
//createSimpleDisplayMenuItem(projectors, competitionApplication, locale);
projectors.addSeparator();
createPublicAttemptBoardMenuItem(projectors, competitionApplication, locale);
createLifterAttemptBoardMenuItem(projectors, competitionApplication, locale);
projectors.addSeparator();
createCountdownDisplayMenuItem(projectors, competitionApplication, locale);
projectors.addSeparator();
//createLiftOrderMenuItem(projectors, competitionApplication, locale);
createSummaryLiftOrderMenuItem(projectors, competitionApplication, locale);
createLoadComputerMenuItem(menu, competitionApplication, locale);
MenuItem decisions = createDecisionMenuItem(menu, competitionApplication, locale);
createRefereeMenuItem(decisions, competitionApplication, locale, 0);
createRefereeMenuItem(decisions, competitionApplication, locale, 1);
createRefereeMenuItem(decisions, competitionApplication, locale, 2);
decisions.addSeparator();
createJuryLightsMenuItem(decisions, competitionApplication, locale);
decisions.addSeparator();
createRefereeTestingMenuItem(decisions, competitionApplication, locale);
createResultsMenuItem(menu, competitionApplication, locale);
createWeighInsMenuItem(menu, competitionApplication, locale);
MenuItem administration = createAdminMenuItem(menu, competitionApplication, locale);
createCompetitionMenuItem(administration, competitionApplication, locale);
createPlatformsMenuItem(administration, competitionApplication, locale);
createCategoriesMenuItem(administration, competitionApplication, locale);
createGroupsMenuItem(administration, competitionApplication, locale);
administration.addSeparator();
createUploadMenuItem(administration, competitionApplication, locale);
createLiftersMenuItem(administration, competitionApplication, locale);
administration.addSeparator();
createRestartMenuItem(administration, competitionApplication, locale);
createAboutMenuItem(menu, competitionApplication, locale);
if (Platform.getSize() > 1) {
MenuItem platforms = createPlatformsMenuItem(menu, competitionApplication, locale);
createPlatformSelectionMenuItems(platforms, competitionApplication, locale);
}
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createConsoleMenu(MenuBar menu, final CompetitionApplication competitionApplication, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Console", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
null);
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createAnnouncerMenuItem(MenuItem menu, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Announcer", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = -547788870764317931L;
@Override
public void menuSelected(MenuItem selectedItem) {
CompetitionApplication.getCurrent().doDisplay(CompetitionApplicationComponents.ANNOUNCER_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createChangesMenuItem(MenuItem menu, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Changes", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = -547788870764317931L;
@Override
public void menuSelected(MenuItem selectedItem) {
CompetitionApplication.getCurrent().doDisplay(CompetitionApplicationComponents.CHANGES_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createTimeKeeperMenuItem(MenuItem menu, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.TimeKeeper", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = -547788870764317931L;
@Override
public void menuSelected(MenuItem selectedItem) {
CompetitionApplication.getCurrent().doDisplay(CompetitionApplicationComponents.TIMEKEEPER_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createResultsMenuItem(MenuBar menu, final CompetitionApplication competitionApplication, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Results", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.RESULT_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createLoadComputerMenuItem(MenuBar menu, final CompetitionApplication competitionApplication,
final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Load", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
if (getLoadComputerWindow() == null) {
displayLoadComputerWindow();
} else {
closeLoadComputerWindow();
}
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createWeighInsMenuItem(MenuBar menu, final CompetitionApplication competitionApplication, final Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.WeighIn", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/users.png"),
new Command() {
private static final long serialVersionUID = 3563330867710192233L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.WEIGH_IN_LIST);
}
});
}
private MenuItem createProjectorsMenuItem(MenuBar menu, CompetitionApplication competitionApplication, Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Projectors", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
null);
}
/**
* @param competitionApplication
* @param locale
* @return
*/
private MenuItem createDisplayMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale, final String stylesheet) {
return projectors.addItem(
Messages.getString("CompetitionApplication.Display",locale)//$NON-NLS-1$
+ " - "
+ Messages.getString("CompetitionApplication.Display."+stylesheet,locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -4179990860181438187L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.displayProjector(CompetitionApplicationComponents.RESULT_BOARD, stylesheet);
}
});
}
/**
* @param competitionApplication
* @param locale
* @return
*/
@SuppressWarnings("unused")
private MenuItem createSimpleDisplayMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale) {
return projectors.addItem(Messages.getString("CompetitionApplication.SimpleDisplay", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -4179990860181438187L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.SIMPLE_RESULT_BOARD);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createSummaryLiftOrderMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale) {
return projectors.addItem(Messages.getString("CompetitionApplication.SummaryLiftOrder", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = 5658882232799685230L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.SUMMARY_LIFT_ORDER_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createPublicAttemptBoardMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale) {
return projectors.addItem(Messages.getString("CompetitionApplication.PublicAttemptBoard", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = 5658882232799685230L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.PUBLIC_ATTEMPT_BOARD_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createLifterAttemptBoardMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale) {
return projectors.addItem(Messages.getString("CompetitionApplication.LifterAttemptBoard", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = 5658882232799685230L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.LIFTER_ATTEMPT_BOARD_VIEW);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
@SuppressWarnings("unused")
private MenuItem createLiftOrderMenuItem(MenuItem projectors, final CompetitionApplication competitionApplication,
final Locale locale) {
return projectors.addItem(Messages.getString("CompetitionApplication.LiftOrder", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = 5658882232799685230L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.LIFT_ORDER_VIEW);
}
});
}
private MenuItem createAdminMenuItem(MenuBar menu, CompetitionApplication competitionApplication, Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Administration", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
null);
}
private MenuItem createPlatformsMenuItem(MenuBar menu, CompetitionApplication competitionApplication, Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Platforms", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
null);
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createPlatformsMenuItem(MenuItem administration, final CompetitionApplication competitionApplication,
final Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Platforms", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -3184587992763328917L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.PLATFORM_LIST);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createCompetitionMenuItem(MenuItem administration, final CompetitionApplication competitionApplication,
final Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Competition", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -3184587992763328917L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.COMPETITION_EDITOR);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createCategoriesMenuItem(MenuItem administration, final CompetitionApplication competitionApplication,
final Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Categories", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -6471211259031643832L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.CATEGORY_LIST);
}
});
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createGroupsMenuItem(MenuItem administration, final CompetitionApplication competitionApplication,
final Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Groups", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/folder-add.png"),
new Command() {
private static final long serialVersionUID = -6740574252795556971L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.GROUP_LIST);
}
});
}
private MenuItem createLiftersMenuItem(MenuItem administration,
final CompetitionApplication competitionApplication, Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Lifters", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/users.png"),
new Command() {
private static final long serialVersionUID = 3563330867710192233L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.REGISTRATION_LIST);
}
});
}
private MenuItem createRestartMenuItem(MenuItem administration,
final CompetitionApplication competitionApplication, Locale locale) {
return administration.addItem(Messages.getString("Restart.Restart", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/users.png"),
new Command() {
private static final long serialVersionUID = 3563330867710192233L;
@Override
public void menuSelected(MenuItem selectedItem) {
displayRestartConfirmation();
}
});
}
protected void restart() {
ServletContext sCtx = CompetitionApplication.getCurrent().getServletContext();
String configFilePath = sCtx.getRealPath("/WEB-INF/web.xml"); //$NON-NLS-1$
File configFile = new File(configFilePath);
logger.info("restarting by touching {}", configFile); //$NON-NLS-1$
configFile.setLastModified(System.currentTimeMillis());
}
private MenuItem createUploadMenuItem(MenuItem administration, final CompetitionApplication competitionApplication,
Locale locale) {
return administration.addItem(Messages.getString("CompetitionApplication.Upload", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/users.png"),
new Command() {
private static final long serialVersionUID = 3563330867710192233L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.UPLOAD_VIEW);
}
});
}
private void createPlatformSelectionMenuItems(MenuItem platforms,
final CompetitionApplication competitionApplication, Locale locale) {
for (final Platform platform : Platform.getAll()) {
final String name = (platform.getName() == null ? "?" : platform.getName()); //$NON-NLS-1$
platforms.addItem(name, null, // new
// ThemeResource("icons/32/users.png"),
new Command() {
private static final long serialVersionUID = 3563330867710192233L;
@Override
public void menuSelected(MenuItem selectedItem) {
Menu.this.setComponentError(null); // erase error
// marker;
competitionApplication.setPlatformByName(name);
SessionData masterData = competitionApplication.getMasterData(name);
logger.debug("new platform={}, new group = {}", name, masterData.getCurrentSession()); //$NON-NLS-1$
competitionApplication.setCurrentCompetitionSession(masterData.getCurrentSession());
}
});
}
}
private MenuItem createDecisionMenuItem(MenuBar menu, final CompetitionApplication competitionApplication,
Locale locale) {
return menu.addItem(Messages.getString("CompetitionApplication.Refereeing", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
null);
}
private MenuItem createRefereeTestingMenuItem(MenuItem item, final CompetitionApplication competitionApplication,
Locale locale) {
return item.addItem(Messages.getString("CompetitionApplication.DecisionLights", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.REFEREE_TESTING);
}
});
}
private MenuItem createJuryLightsMenuItem(MenuItem item, final CompetitionApplication competitionApplication,
Locale locale) {
return item.addItem(Messages.getString("CompetitionApplication.JuryLights", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.JURY_LIGHTS);
}
});
}
private MenuItem createCountdownDisplayMenuItem(MenuItem item, final CompetitionApplication competitionApplication,
Locale locale) {
return item.addItem(Messages.getString("CompetitionApplication.CountdownDisplay", locale), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.doDisplay(CompetitionApplicationComponents.COUNTDOWN_DISPLAY);
}
});
}
private MenuItem createRefereeMenuItem(MenuItem item, final CompetitionApplication competitionApplication,
Locale locale, final int refereeIndex) {
return item.addItem(Messages.getString("CompetitionApplication.Referee", locale) + " " + (refereeIndex + 1), //$NON-NLS-1$
null, // new ThemeResource("icons/32/document.png"),
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
competitionApplication.displayRefereeConsole(refereeIndex);
}
});
}
public void displayRestartConfirmation() {
// Create the window...
final Window subwindow = new Window(Messages.getString(
"Restart.ConfirmationDialogTitle", getApplication().getLocale())); //$NON-NLS-1$
// ...and make it modal
subwindow.setModal(true);
subwindow.setWidth("10cm"); //$NON-NLS-1$
// Configure the windws layout; by default a VerticalLayout
VerticalLayout layout = (VerticalLayout) subwindow.getContent();
layout.setMargin(true);
layout.setSpacing(true);
// Add some content; a label and a close-button
final Label message = new Label(
Messages.getString("Restart.Confirmation", getApplication().getLocale()), Label.CONTENT_XHTML); //$NON-NLS-1$
subwindow.addComponent(message);
final Button close = new Button(
Messages.getString("Restart.Cancel", getApplication().getLocale()), new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
// inline click-listener
@Override
public void buttonClick(ClickEvent event) {
// close the window by removing it from the main window
getApplication().getMainWindow().removeWindow(subwindow);
}
});
final Button ok = new Button(Messages.getString("Restart.Restart", getApplication().getLocale()));
ok.addListener(new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
// inline click-listener
@Override
public void buttonClick(ClickEvent event) {
// close the window by removing it from the main window
restart();
message.setValue(Messages.getString("Restart.InProgress", getApplication().getLocale()));//$NON-NLS-1$
// getApplication().getMainWindow().removeWindow(subwindow);
// close.setVisible(false);
ok.setVisible(false);
close.setCaption(Messages.getString("Common.done", getApplication().getLocale()));
}
});
// The components added to the window are actually added to the window's
// layout; you can use either. Alignments are set using the layout
HorizontalLayout buttons = new HorizontalLayout();
buttons.addComponent(ok);
buttons.addComponent(close);
buttons.setSpacing(true);
layout.addComponent(buttons);
layout.setComponentAlignment(buttons, Alignment.BOTTOM_CENTER);
getApplication().getMainWindow().addWindow(subwindow);
}
public void displayLoadComputerWindow() {
if (loadComputerWindow != null) {
loadComputerWindow.setVisible(true);
} else {
loadComputerWindow = new LoadWindow(this);
getApplication().getMainWindow().addWindow(loadComputerWindow);
}
}
public void closeLoadComputerWindow() {
LoadWindow loadComputerWindow2 = getLoadComputerWindow();
getApplication().getMainWindow().removeWindow(loadComputerWindow2);
loadComputerWindow2 = getLoadComputerWindow();
if (loadComputerWindow2 != null) {
loadComputerWindow2.close();
}
setLoadComputerWindow(null);
}
/**
* @param loadComputerWindow
* the loadComputerWindow to set
*/
public void setLoadComputerWindow(LoadWindow loadComputerWindow) {
this.loadComputerWindow = loadComputerWindow;
}
/**
* @return the loadComputerWindow
*/
public LoadWindow getLoadComputerWindow() {
return loadComputerWindow;
}
/**
* @param competitionApplication
* @param locale
*/
private MenuItem createAboutMenuItem(MenuBar menu, final CompetitionApplication competitionApplication,
final Locale locale) {
return menu.addItem(Messages.getString("About.menu", CompetitionApplication.getCurrentLocale()), //$NON-NLS-1$
null,
new Command() {
private static final long serialVersionUID = 5577281157225515360L;
@Override
public void menuSelected(MenuItem selectedItem) {
if (getLoadComputerWindow() == null) {
displayAboutWindow();
}
}
private void displayAboutWindow() {
Window window = new Window();
window.setIcon(new ThemeResource("icons/16/appIcon.png"));
ServletContext servletContext = CompetitionApplication.getCurrent().getServletContext();
String name = servletContext.getInitParameter("appName");
String version = servletContext.getInitParameter("appVersion");
String url = servletContext.getInitParameter("appUrl");
window.setCaption(" "+name);
String pattern = Messages.getString("About.message", CompetitionApplication.getCurrentLocale());
String message = MessageFormat.format(pattern, version, "Jean-François Lamy", url, url, "lamyjeanfrancois@gmail.com");
window.addComponent(new Label(message, Label.CONTENT_XHTML));
getApplication().getMainWindow().addWindow(window);
window.center();
}
});
}
}
| 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.components;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
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.RuleViolationException;
import org.concordiainternational.competition.decision.IDecisionController;
import org.concordiainternational.competition.decision.DecisionEvent;
import org.concordiainternational.competition.decision.DecisionEventListener;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent;
import org.concordiainternational.competition.publicAddress.PublicAddressMessageEvent.MessageDisplayListener;
import org.concordiainternational.competition.publicAddress.PublicAddressOverlay;
import org.concordiainternational.competition.timer.CountdownTimer;
import org.concordiainternational.competition.timer.CountdownTimerListener;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.CompetitionApplicationComponents;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.SessionData.UpdateEvent;
import org.concordiainternational.competition.ui.SessionData.UpdateEventListener;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
import org.concordiainternational.competition.ui.UserActions;
import org.concordiainternational.competition.ui.generators.TimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Embedded;
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 ResultFrame extends VerticalLayout implements
ApplicationView,
CountdownTimerListener,
MessageDisplayListener,
Window.CloseListener,
URIHandler,
DecisionEventListener
{
private static final String ATTEMPT_WIDTH = "6em";
public final static Logger logger = LoggerFactory.getLogger(ResultFrame.class);
private static final long serialVersionUID = 1437157542240297372L;
private Embedded iframe;
public String urlString;
private String platformName;
private SessionData masterData;
private CustomLayout top;
private CompetitionApplication app;
private Label name = new Label("<br>", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label attempt = new Label("", Label.CONTENT_XHTML); //$NON-NLS-1$
private Label timeDisplay = new Label();
private Label weight = new Label();
private String appUrlString;
private UpdateEventListener updateListener;
private DecisionLightsWindow decisionLights;
protected boolean waitingForDecisionLightsReset;
public ResultFrame(boolean initFromFragment, String viewName, String urlString) throws MalformedURLException {
if (initFromFragment) {
setParametersFromFragment();
} else {
this.viewName = viewName;
}
this.app = CompetitionApplication.getCurrent();
boolean prevDisabledPush = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
if (platformName == null) {
// get the default platform name
platformName = CompetitionApplicationComponents.initPlatformName();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
this.urlString = urlString;
getAppUrlString();
create(app);
masterData = app.getMasterData(platformName);
// we cannot call push() at this point
synchronized (app) {
boolean prevDisabled = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
decisionLights = new DecisionLightsWindow(false, true);
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);
registerHandlers(viewName);
} finally {
app.setPusherDisabled(prevDisabledPush);
}
}
/**
* Compute where we think the jsp file ought to be.
*/
private void getAppUrlString() {
appUrlString = app.getURL().toExternalForm();
int lastSlash = appUrlString.lastIndexOf("/");
if (lastSlash == appUrlString.length() - 1) {
// go back one more slash, the string ended with /
lastSlash = appUrlString.lastIndexOf("/", lastSlash - 1);
}
appUrlString = appUrlString.substring(0, lastSlash + 1);
// System.err.println("appUrlString with slash="+appUrlString);
}
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 {}",
ResultFrame.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) throws MalformedURLException {
this.setSizeFull();
top = new CustomLayout("projectorTop"); //$NON-NLS-1$
top.setWidth("100%"); //$NON-NLS-1$
this.addComponent(top);
iframe = new Embedded(); //$NON-NLS-1$
iframe.setType(Embedded.TYPE_BROWSER);
iframe.setSizeFull();
this.addComponent(iframe);
this.setExpandRatio(top, 0);
this.setExpandRatio(iframe, 100);
}
/**
* @param platformName1
* @param masterData1
* @throws RuntimeException
*/
private void display(final String platformName1, final SessionData masterData1) throws RuntimeException {
synchronized (app) {
URL url = computeUrl(platformName1);
logger.debug("display {}",url);
iframe.setSource(new ExternalResource(url));
final Lifter currentLifter = masterData1.getCurrentLifter();
if (currentLifter != null) {
boolean done = fillLifterInfo(currentLifter);
updateTime(masterData1);
top.addComponent(timeDisplay, "timeDisplay"); //$NON-NLS-1$
timeDisplay.setVisible(!done);
} else {
logger.debug("lifter null");
name.setValue(getWaitingMessage()); //$NON-NLS-1$
top.addComponent(name, "name"); //$NON-NLS-1$
displayDecision(true);
attempt.setValue(""); //$NON-NLS-1$
top.addComponent(attempt, "attempt"); //$NON-NLS-1$
attempt.setWidth(ATTEMPT_WIDTH); //$NON-NLS-1$
timeDisplay.setValue(""); //$NON-NLS-1$
timeDisplay.setWidth("4em");
top.addComponent(timeDisplay, "timeDisplay"); //$NON-NLS-1$
weight.setValue(""); //$NON-NLS-1$
weight.setWidth("4em"); //$NON-NLS-1$
top.addComponent(weight, "weight"); //$NON-NLS-1$
}
}
logger.debug("prior to display push disabled={}",app.getPusherDisabled());
app.push();
}
/**
* @param platformName1
* @return
* @throws RuntimeException
*/
private URL computeUrl(final String platformName1) throws RuntimeException {
URL url;
String encodedPlatformName;
try {
encodedPlatformName = URLEncoder.encode(platformName1, "UTF-8");
// System.err.println(encodedPlatformName);
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
String styleSheet = getStylesheet();
if (styleSheet == null || styleSheet.isEmpty()) {
styleSheet = "";
} else {
styleSheet = "&style=" + getStylesheet() + ".css";
}
final String spec = appUrlString + urlString + encodedPlatformName + styleSheet +"&time=" + System.currentTimeMillis(); //$NON-NLS-1$
try {
url = new URL(spec);
logger.debug("url={}",url.toExternalForm());
} catch (MalformedURLException e) {
throw new RuntimeException(e); // can't happen.
}
return url;
}
/**
* @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);
displayDecision(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 name and affiliation
if (!done) {
final String lastName = lifter.getLastName();
final String firstName = lifter.getFirstName();
final String club = lifter.getClub();
name.setValue(lastName.toUpperCase() + " " + firstName + " " + club); //$NON-NLS-1$ //$NON-NLS-2$
top.addComponent(name, "name"); //$NON-NLS-1$
} else {
name.setValue(MessageFormat.format(
Messages.getString("ResultFrame.Done", locale), masterData.getCurrentSession().getName())); //$NON-NLS-1$
top.addComponent(name, "name"); //$NON-NLS-1$
}
}
private void displayDecision(boolean done) {
decisionLights.setSizeFull();
decisionLights.setHeight("2ex");
decisionLights.setMargin(false);
top.addComponent(decisionLights, "decisionLights"); //$NON-NLS-1$
decisionLights.setVisible(false);
}
/**
* @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 attempt number
if (!done) {
//appendDiv(sb, lifter.getNextAttemptRequestedWeight()+Messages.getString("Common.kg",locale)); //$NON-NLS-1$
String tryInfo = MessageFormat.format(Messages.getString("ResultFrame.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$
attempt.setValue(tryInfo);
} else {
attempt.setValue("");
}
attempt.setWidth(ATTEMPT_WIDTH);
top.addComponent(attempt, "attempt"); //$NON-NLS-1$
}
/**
* @param lifter
* @param sb
* @param locale
* @param done
* @return
*/
private void displayRequestedWeight(Lifter lifter, final Locale locale, boolean done) {
// display requested weight
if (!done) {
weight.setValue(lifter.getNextAttemptRequestedWeight() + Messages.getString("Common.kg", locale)); //$NON-NLS-1$
} else {
weight.setValue(""); //$NON-NLS-1$
}
top.addComponent(weight, "weight"); //$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();
timeDisplay.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
timer.addListener(this);
}
@Override
public void finalWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void forceTimeRemaining(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
timeDisplay.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
}
@Override
public void initialWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void noTimeLeft(int timeRemaining) {
normalTick(timeRemaining);
}
int previousTimeRemaining = 0;
private String viewName;
private PublicAddressOverlay overlayContent;
private Window overlay;
protected boolean shown;
private String stylesheetName;
@Override
public void normalTick(int timeRemaining) {
if (name == null) return;
if (TimeFormatter.getSeconds(previousTimeRemaining) == TimeFormatter.getSeconds(timeRemaining)) {
previousTimeRemaining = timeRemaining;
return;
} else {
previousTimeRemaining = timeRemaining;
}
synchronized (app) {
timeDisplay.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
}
app.push();
}
@Override
public void pause(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
@Override
public void start(int timeRemaining) {
}
@Override
public void stop(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+platformName+(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) {
stylesheetName = params[2];
logger.debug("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 (viewName.contains("resultBoard")) {
if (event.setHide()) {
removeMessage();
} else if (overlay == null) {
displayMessage(event.getTitle(),event.getMessage(),event.getRemainingMilliseconds());
} else {
// nothing to do: overlayContent listens to the events on its own
}
}
}
app.push();
}
/**
* Remove the currently displayed message, if any.
*/
private void removeMessage() {
if (overlayContent != null) masterData.removeBlackBoardListener(overlayContent);
overlayContent = null;
if (overlay != null) app.getMainWindow().removeWindow(overlay);
overlay = null;
}
/**
* 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 {} {}",title,message);
if (overlayContent == null) {
overlayContent = new PublicAddressOverlay(title,message,remainingMilliseconds);
// overlayContent listens to message updates and timer updates
masterData.addBlackBoardListener(overlayContent);
}
synchronized (app) {
// create window
if (overlay == null) {
logger.debug("creating window");
Window mainWindow = app.getMainWindow();;
overlay = new Window(platformName);
overlay.addStyleName("decisionLightsWindow");
overlay.setSizeFull();
mainWindow.addWindow(overlay);
overlay.center();
overlay.setContent(overlayContent);
overlay.setVisible(true);
}
}
app.push();
}
/**
* Register listeners for the various model events.
* @param viewName1
*/
private void registerHandlers(String viewName1) {
// listen to changes in the competition data
logger.debug("listening to session data updates.");
updateListener = registerAsListener(platformName, masterData);
// listen to public address events
if (viewName1.contains("resultBoard")) {
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);
}
/**
* Undo what registerListeners did.
*/
private void unRegisterListeners() {
// 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();
if (viewName.contains("resultBoard")) {
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);
}
/* Unregister listeners when window is closed.
* @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window.CloseEvent)
*/
@Override
public void windowClose(CloseEvent e) {
unRegisterListeners();
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
logger.trace("re-registering handlers for {} {}",this,relativeUri);
registerHandlers(viewName);
return null;
}
/**
* Process a decision regarding the current lifter.
* Make sure that the name 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;
decisionLights.setVisible(true);
break;
case RESET:
// we are done
waitingForDecisionLightsReset = false;
decisionLights.setVisible(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) {
decisionLights.setVisible(true);
}
break;
case BLOCK:
waitingForDecisionLightsReset = true;
decisionLights.setVisible(true);
break;
}
}
}
}).start();
}
public void setStylesheet(String stylesheetName) {
this.stylesheetName = stylesheetName;
}
private String getStylesheet() {
return stylesheetName;
}
@Override
public void registerAsListener() {
// TODO Auto-generated method stub
}
@Override
public void unregisterAsListener() {
// TODO Auto-generated method stub
}
}
| 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.components;
import java.io.Serializable;
import java.util.Locale;
import org.concordiainternational.competition.data.CompetitionSession;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.Bookmarkable;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.ItemAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Select;
public class SessionSelect extends HorizontalLayout implements Serializable {
private static final long serialVersionUID = -5471881649385421098L;
private static final Logger logger = LoggerFactory.getLogger(SessionSelect.class);
CompetitionSession value = null;
Item selectedItem = null;
Serializable selectedId = null;
private Select sessionSelect;
private ValueChangeListener listener;
/**
* @param competitionApplication
* @param locale
* @return
*/
public SessionSelect(final CompetitionApplication competitionApplication, final Locale locale, final Bookmarkable view) {
final Label groupLabel = new Label(Messages.getString("CompetitionApplication.CurrentGroup", locale)); //$NON-NLS-1$
groupLabel.setSizeUndefined();
sessionSelect = new Select();
loadData(competitionApplication, sessionSelect);
sessionSelect.setImmediate(true);
sessionSelect.setNullSelectionAllowed(true);
sessionSelect.setNullSelectionItemId(null);
final CompetitionSession currentGroup = competitionApplication.getCurrentCompetitionSession();
logger.trace("constructor currentGroup: {}",(currentGroup != null ? currentGroup.getName() : null));
selectedId = currentGroup != null ? currentGroup.getId() : null;
if (selectedId != null) {
selectedItem = sessionSelect.getContainerDataSource().getItem(selectedId);
value = (CompetitionSession) ItemAdapter.getObject(selectedItem);
} else {
selectedItem = null;
value = null;
}
listener = new ValueChangeListener() {
private static final long serialVersionUID = -4650521592205383913L;
@Override
public void valueChange(ValueChangeEvent event) {
final Serializable selectedValue = (Serializable) event.getProperty().getValue();
if (selectedValue != null) {
selectedId = selectedValue;
selectedItem = sessionSelect.getContainerDataSource().getItem(selectedValue);
value = (CompetitionSession) ItemAdapter.getObject(selectedItem);
} else {
selectedId = null;
selectedItem = null;
value = null;
}
if (value != null) logger.trace("listener selected group : {}",value.getName());
CompetitionApplication.getCurrent().setCurrentCompetitionSession(value);
CompetitionApplication.getCurrent().getUriFragmentUtility().setFragment(view.getFragment(), false);
}
};
sessionSelect.addListener(listener);
sessionSelect.select(selectedId);
this.addComponent(groupLabel);
this.setComponentAlignment(groupLabel, Alignment.MIDDLE_LEFT);
this.addComponent(sessionSelect);
this.setComponentAlignment(groupLabel, Alignment.MIDDLE_LEFT);
this.setSpacing(true);
}
/**
* Force a reload of the names in the dropdown.
* @param competitionApplication
* @param sessionSelect1
* @return
*/
private HbnContainer<CompetitionSession> loadData(
final CompetitionApplication competitionApplication,
final Select sessionSelect1) {
final HbnContainer<CompetitionSession> sessionDataSource = new HbnContainer<CompetitionSession>(CompetitionSession.class, competitionApplication);
sessionSelect1.setContainerDataSource(sessionDataSource);
sessionSelect1.setItemCaptionPropertyId("name"); //$NON-NLS-1$
return sessionDataSource;
}
public void refresh() {
sessionSelect.removeListener(listener);
loadData(CompetitionApplication.getCurrent(), sessionSelect);
sessionSelect.setValue(selectedId);
logger.info("selected {}",selectedId);
sessionSelect.addListener(listener);
CompetitionApplication.getCurrent().push();
}
public Item getSelectedItem() {
return selectedItem;
}
public CompetitionSession getValue() {
return value;
}
public Serializable getSelectedId() {
return selectedId;
}
}
| 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.components;
import java.io.Serializable;
import java.util.Set;
import org.concordiainternational.competition.data.Category;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.utils.ItemAdapter;
import com.vaadin.data.hbnutil.HbnContainer;
import com.vaadin.ui.ListSelect;
@SuppressWarnings("unchecked")
public class CategorySelect extends ListSelect implements Serializable {
private static final long serialVersionUID = -5471881649385421098L;
HbnContainer<Category> dataSource;
CompetitionApplication app;
/**
* @param competitionApplication
* @param locale
* @return
*/
public CategorySelect() {
final ListSelect categorySelect = this;
app = CompetitionApplication.getCurrent();
dataSource = new HbnContainer<Category>(Category.class, app);
categorySelect.setContainerDataSource(dataSource);
categorySelect.setItemCaptionPropertyId("name"); //$NON-NLS-1$
categorySelect.setImmediate(true);
categorySelect.setNullSelectionAllowed(true);
categorySelect.setNullSelectionItemId(null);
categorySelect.setRows(6);
}
@Override
public String toString() {
Set<Long> categoryIds = (Set<Long>) getValue();
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(dataSource.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
}
}
}
| 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.components;
import java.util.ArrayList;
import java.util.Iterator;
import com.vaadin.data.Buffered;
import com.vaadin.data.Validator;
import com.vaadin.terminal.CompositeErrorMessage;
import com.vaadin.terminal.ErrorMessage;
import com.vaadin.ui.TextField;
public class CustomTextField extends TextField {
private static final long serialVersionUID = 7340431723259557435L;
/**
* Error messages shown by the fields are composites of the error message
* thrown by the superclasses (that is the component error message),
* validation errors and buffered source errors.
*
* @see com.vaadin.ui.AbstractComponent#getErrorMessage()
*/
@Override
public ErrorMessage getErrorMessage() {
/*
* Check validation errors only if automatic validation is enabled.
* Empty, required fields will generate a validation error containing
* the requiredError string. For these fields the exclamation mark will
* be hidden but the error must still be sent to the client.
*/
ErrorMessage validationError = null;
if (isValidationVisible()) {
try {
validate();
} catch (Validator.InvalidValueException e) {
if (!e.isInvisible()) {
validationError = e;
}
}
}
// Check if there are any systems errors
final ErrorMessage superError = super.getErrorMessage();
// Return if there are no errors at all
if (superError == null && validationError == null) {
return null;
}
ErrorMessage error;
// get rid of the private exception from AbstractField that is
// systematically
// included (private Buffered.SourceException
// currentBufferedSourceException)
if (superError instanceof CompositeErrorMessage) {
ArrayList<ErrorMessage> newErrors = new ArrayList<ErrorMessage>();
final CompositeErrorMessage compositeError = (CompositeErrorMessage) superError;
ErrorMessage em = null;
for (Iterator<?> iterator = compositeError.iterator(); iterator.hasNext();) {
em = (ErrorMessage) iterator.next();
if (!(em instanceof Buffered.SourceException)) {
newErrors.add(em);
}
}
// our version of terminalError has already added a UserError in
// this case
// so there is always at least an error.
if (newErrors.size() >= 1) {
error = new CompositeErrorMessage(newErrors);
} else {
if (superError instanceof Throwable) ((Throwable) superError).printStackTrace();
error = superError;
}
} else {
error = new CompositeErrorMessage(new ErrorMessage[] { superError, validationError });
}
setComponentError(null);
return error;
}
}
| 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.components;
import java.util.Locale;
import org.concordiainternational.competition.data.Lifter;
import org.concordiainternational.competition.i18n.Messages;
import org.concordiainternational.competition.ui.AnnouncerView;
import org.concordiainternational.competition.ui.AnnouncerView.Mode;
import org.concordiainternational.competition.ui.CompetitionApplication;
import org.concordiainternational.competition.ui.LifterInfo;
import org.concordiainternational.competition.ui.SessionData;
import org.concordiainternational.competition.ui.TimeStoppedNotificationReason;
import org.concordiainternational.competition.webapp.WebApplicationConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vaadin.event.Action;
import com.vaadin.event.ShortcutAction;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Window;
public class TimerControls extends GridLayout {
private static final String ANNOUNCER_BUTTON_WIDTH = "9em";
private static final String ANNOUNCER_SMALL_BUTTON_WIDTH = "4em";
private static final long serialVersionUID = 4075226732120553473L;
static final Logger logger = LoggerFactory.getLogger(TimerControls.class);
static final Logger timingLogger = LoggerFactory
.getLogger("org.concordiainternational.competition.timer.TimingLogger"); //$NON-NLS-1$
/**
* a click that take place less than MIN_CLICK_DELAY milliseconds after an
* initial click on the Ok or Failed button is ignored. This usually means
* that the user double clicked by mistake, or pressed a second time becaus
* he was unsure that recalculation had taken place and we definitely don't
* want to register two successful or failed lifts.
*/
protected static final long MIN_CLICK_DELAY = 1000;
final public Button announce = new Button();
final public Button changeWeight = new Button();
//final public Button stopStart = new Button();
final public Button start = new Button();
final public Button stop = new Button();
final public Button oneMinute = new Button();
final public Button twoMinutes = new Button();
final public Button okLift = new Button();
final public Button failedLift = new Button();
final public Button stopTimeBottom = new Button();
private Mode mode;
private LifterInfo lifterInfo;
private boolean timerVisible = false;
private boolean timerShortcutsEnabled = false;
private ShortcutActionListener startAction;
private ShortcutActionListener stopAction;
private ShortcutActionListener oneMinuteAction;
private ShortcutActionListener twoMinutesAction;
public TimerControls(final Lifter lifter, final SessionData groupData, boolean top, AnnouncerView.Mode mode,
LifterInfo lifterInfo, boolean timerVisible, CompetitionApplication app) {
super(4, 3);
this.mode = mode;
this.lifterInfo = lifterInfo;
this.timerVisible = timerVisible;
this.setMargin(false);
this.setSpacing(false);
Locale locale = app.getLocale();
if (top) {
top(lifter, groupData, locale);
} else {
bottom(lifter, groupData, locale);
}
this.setSpacing(true);
}
/**
* @param lifter
* @param groupData
* @param locale
* @throws OverlapsException
* @throws OutOfBoundsException
*/
private void top(final Lifter lifter, final SessionData groupData, Locale locale) throws OverlapsException,
OutOfBoundsException {
if (mode == AnnouncerView.Mode.ANNOUNCER) {
configureAnnounceButton(lifter, groupData, locale);
configureWeightChangeButton(lifter, groupData, locale);
//configureStopStart(lifter, groupData, locale);
configureStart(lifter, groupData, locale);
configureStop(lifter, groupData, locale);
configureOneMinute(lifter, groupData, locale);
configureTwoMinutes(lifter, groupData, locale);
configureOkLift(lifter, groupData, locale);
configureFailedLift(lifter, groupData, locale);
registerListeners(lifter,groupData);
this.addComponent(announce, 0, 0, 1, 0);
this.addComponent(changeWeight, 2, 0, 3, 0);
//this.addComponent(stopStart, 0, 1, 1, 1);
this.addComponent(start, 0, 1, 0, 1);
this.addComponent(stop, 1, 1, 1, 1);
this.addComponent(oneMinute, 2, 1, 2, 1);
this.addComponent(twoMinutes, 3, 1, 3, 1);
this.addComponent(okLift, 0, 2, 1, 2);
this.addComponent(failedLift, 2, 2, 3, 2);
okLift.addStyleName("okLift"); //$NON-NLS-1$
failedLift.addStyleName("failedLift"); //$NON-NLS-1$
final boolean announced = !groupData.getNeedToAnnounce();
if (!WebApplicationConfiguration.NECShowsLifterImmediately) {
announce.setEnabled(true); // allow announcer to call lifter at
// will
changeWeight.setEnabled(true); // always allow changes
enableStopStart(true);
//stopStart.setEnabled(announced);
} else {
announce.setEnabled(!announced && groupData.getAnnouncerEnabled()); // if lifter has been
// announced, disable this
// button
changeWeight.setEnabled(true); // always allow changes
enableStopStart(groupData.getTimer().isRunning());
//stopStart.setEnabled(announced);
}
// okLift.setEnabled(false);
// failedLift.setEnabled(false);
if (timerVisible) {
showTimerControls(groupData.getTimer().isRunning());
} else {
hideTimerControls();
}
} else if (mode == AnnouncerView.Mode.MARSHALL) {
configureWeightChangeButton(lifter, groupData, locale);
this.addComponent(changeWeight, 0, 0, 1, 0);
// changeWeight.setEnabled(false);
} else if (mode == AnnouncerView.Mode.TIMEKEEPER) {
//configureStopStart(lifter, groupData, locale);
configureStart(lifter, groupData, locale);
configureStop(lifter, groupData, locale);
configureOneMinute(lifter, groupData, locale);
configureTwoMinutes(lifter, groupData, locale);
this.addComponent(start, 0, 1, 0, 1);
this.addComponent(stop, 1, 1, 1, 1);
this.addComponent(oneMinute, 2, 1, 2, 1);
this.addComponent(twoMinutes, 3, 1, 3, 1);
enableStopStart(groupData.getTimer().isRunning());
registerListeners(lifter,groupData);
setTimerShortcutsEnabled(true);
}
}
public void enableStopStart(boolean running) {
final boolean isTimeKeeper = mode == Mode.TIMEKEEPER;
if (!running) {
stop.setEnabled(false);
stop.removeStyleName("primary");
if (isTimeKeeper) {
stop.removeClickShortcut();
}
start.setEnabled(true);
if (isTimeKeeper) {
start.setClickShortcut(KeyCode.ENTER);
} else {
start.focus();
}
start.addStyleName("primary");
} else {
start.setEnabled(false);
start.removeStyleName("primary");
if (isTimeKeeper) {
start.removeClickShortcut();
}
stop.setEnabled(true);
if (isTimeKeeper) {
stop.setClickShortcut(KeyCode.ENTER);
} else {
stop.focus();
}
stop.addStyleName("primary");
}
}
/**
* @param groupData
* @param locale
*/
private void bottom(Lifter lifter, final SessionData groupData, Locale locale) {
addStopTimeBottomListener(lifter, groupData, locale);
// if the timer is running, we allow scorekeeper to stop it.
// otherwise, button will get enabled by the timer when it is started
final boolean enabled = groupData.getTimer().isRunning();
logger.debug("timer is running = {}", enabled); //$NON-NLS-1$
// stopTimeBottom.setEnabled(enabled);
this.addComponent(stopTimeBottom);
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureFailedLift(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener failedLiftListener = new Button.ClickListener() {
private static final long serialVersionUID = 5693610077500773431L;
@Override
public void buttonClick(ClickEvent event) {
failedLiftDoIt(lifter, groupData);
}
};
failedLift.addListener(failedLiftListener);
failedLift.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
failedLift.setCaption(Messages.getString("LifterInfo.Failed", locale)); //$NON-NLS-1$
failedLift.setEnabled(groupData.getAnnouncerEnabled());
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureOkLift(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener okLiftListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -2582860566509880474L;
@Override
public void buttonClick(ClickEvent event) {
okLiftDoIt(lifter, groupData);
}
};
okLift.addListener(okLiftListener);
okLift.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
okLift.setCaption(Messages.getString("LifterInfo.Successful", locale)); //$NON-NLS-1$
okLift.setEnabled(groupData.getAnnouncerEnabled());
}
// /**
// * @param lifter
// * @param groupData
// * @param locale
// */
// private void configureStopStart(final Lifter lifter, final SessionData groupData, Locale locale) {
// final Button.ClickListener stopStartListener = new Button.ClickListener() { //$NON-NLS-1$
// private static final long serialVersionUID = -2582860566509880474L;
//
// @Override
// public void buttonClick(ClickEvent event) {
// logger.debug("stop/start clicked");
// final CountdownTimer timer = groupData.getTimer();
// groupData.manageTimerOwner(lifter, groupData, timer);
//
// final boolean running = timer.isRunning();
// timingLogger.debug("stop/start timer.isRunning()={}", running); //$NON-NLS-1$
// if (running) {
// lifterInfo.setBlocked(true);
// timer.pause(TimeStoppedNotificationReason.STOP_START_BUTTON); // pause() does not clear the associated
// // lifter
// } else {
// lifterInfo.setBlocked(false); // !!!!
// timer.restart();
// groupData.setLifterAsHavingStarted(lifter);
// groupData.getRefereeDecisionController().setBlocked(false);
// }
// // announce.setEnabled(false);
// // changeWeight.setEnabled(false);
// }
// };
//// stopStart.addListener(stopStartListener);
//// stopStart.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
//// stopStart.setCaption(Messages.getString("LifterInfo.StopStartTime", locale)); //$NON-NLS-1$
// }
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureStart(final Lifter lifter, final SessionData groupData, Locale locale) {
@SuppressWarnings("serial")
final Button.ClickListener startListener = new Button.ClickListener() { //$NON-NLS-1$
@Override
public void buttonClick(ClickEvent event) {
startDoIt(lifter, groupData);
}
};
start.addListener(startListener);
//start.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
start.setIcon(new ThemeResource("icons/16/playTriangle.png"));
//start.setCaption(Messages.getString("LifterInfo.StartTime", locale)); //$NON-NLS-1$
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureStop(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener stopListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -2582860566509880474L;
@Override
public void buttonClick(ClickEvent event) {
stopDoIt(lifter, groupData);
}
};
stop.addListener(stopListener);
//stop.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
stop.setIcon(new ThemeResource("icons/16/pause.png"));
//stop.setCaption(Messages.getString("LifterInfo.StopTime", locale)); //$NON-NLS-1$
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureOneMinute(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener oneMinuteListener = new Button.ClickListener() {
private static final long serialVersionUID = 5693610077500773431L;
@Override
public void buttonClick(ClickEvent event) {
oneMinuteDoIt(lifter, groupData);
}
};
oneMinute.addListener(oneMinuteListener);
oneMinute.setWidth(ANNOUNCER_SMALL_BUTTON_WIDTH);
oneMinute.setCaption(Messages.getString("LifterInfo.OneMinute", locale)); //$NON-NLS-1$
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureTwoMinutes(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener twoMinutesListener = new Button.ClickListener() {
private static final long serialVersionUID = 5693610077500773431L;
@Override
public void buttonClick(ClickEvent event) {
twoMinutesDoIt(lifter, groupData);
}
};
twoMinutes.addListener(twoMinutesListener);
twoMinutes.setWidth(ANNOUNCER_SMALL_BUTTON_WIDTH);
twoMinutes.setCaption(Messages.getString("LifterInfo.TwoMinutes", locale)); //$NON-NLS-1$
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureWeightChangeButton(final Lifter lifter, final SessionData groupData, Locale locale) {
final Button.ClickListener changeWeightListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -2582860566509880474L;
@Override
public void buttonClick(ClickEvent event) {
timingLogger.debug("weightChangeButton clicked"); //$NON-NLS-1$
logger.info("WEIGHT CHANGE button clicked");
groupData.getTimer().pause(TimeStoppedNotificationReason.CURRENT_LIFTER_CHANGE);
if (mode == Mode.ANNOUNCER || mode == Mode.MARSHALL) {
// if
// (!WebApplicationConfiguration.NECShowsLifterImmediately)
// {
// groupData.displayWeight(lifter);
// } else {
// groupData.displayLifterInfo(lifter);
// }
AnnouncerView announcerView = (AnnouncerView) CompetitionApplication.getCurrent().components.currentView;
announcerView.setStickyEditor(false, false);
announcerView.editFirstLifterInfo(groupData, WebApplicationConfiguration.DEFAULT_STICKINESS);
changeWeight.setEnabled(true);
if (mode == Mode.ANNOUNCER) {
announce.setEnabled(true);
announcerView.selectFirstLifter();
}
}
// okLift.setEnabled(false);
// failedLift.setEnabled(false);
// stopStart.setEnabled(false);
}
};
changeWeight.addListener(changeWeightListener);
changeWeight.setWidth(ANNOUNCER_BUTTON_WIDTH);
changeWeight.setCaption(Messages.getString("LifterInfo.WeightChange", locale)); //$NON-NLS-1$
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void configureAnnounceButton(final Lifter lifter, final SessionData groupData, final Locale locale) {
final Button.ClickListener announceListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -2582860566509880474L;
@Override
public void buttonClick(ClickEvent event) {
timingLogger.debug("announce"); //$NON-NLS-1$
checkDecisionHasBeenDisplayed(groupData, locale);
groupData.callLifter(lifter); // will call start which will cause the timer buttons to do their thing.
enableStopStart(groupData.getTimer().isRunning());
announce.setEnabled(false);
changeWeight.setEnabled(true);
groupData.getRefereeDecisionController().setBlocked(false);
// okLift.setEnabled(true);
// failedLift.setEnabled(true);
}
};
announce.addListener(announceListener);
announce.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
announce.setCaption(Messages.getString("LifterInfo.Announce", locale)); //$NON-NLS-1$
announce.setEnabled(groupData.getAnnouncerEnabled());
}
protected void checkDecisionHasBeenDisplayed(SessionData groupData, Locale locale) {
if (!groupData.getAnnouncerEnabled()) {
throw new RuntimeException(Messages.getString("LifterInfo.Busy", locale)); //$NON-NLS-1$
}
}
/**
* @param lifter
* @param groupData
* @param locale
*/
private void addStopTimeBottomListener(final Lifter lifter, final SessionData groupData, Locale locale) {
// we need a way to stop the timer if the current lifter requests a
// change.
final Button.ClickListener stopTimeBottomListener = new Button.ClickListener() { //$NON-NLS-1$
private static final long serialVersionUID = -2582860566509880474L;
@Override
public void buttonClick(ClickEvent event) {
timingLogger.debug("stopTimeBottom"); //$NON-NLS-1$
groupData.getTimer().pause(TimeStoppedNotificationReason.CURRENT_LIFTER_CHANGE);
}
};
stopTimeBottom.addListener(stopTimeBottomListener);
stopTimeBottom.setWidth(ANNOUNCER_BUTTON_WIDTH); //$NON-NLS-1$
stopTimeBottom.setCaption(Messages.getString("LifterInfo.WeightChange", locale)); //$NON-NLS-1$
}
public void showTimerControls(boolean running) {
//stopStart.setVisible(true);
stop.setVisible(true);
start.setVisible(true);
enableStopStart(running);
oneMinute.setVisible(true);
twoMinutes.setVisible(true);
setTimerShortcutsEnabled(true);
}
public void setTimerShortcutsEnabled(boolean b) {
this.timerShortcutsEnabled = b;
}
public void hideTimerControls() {
start.setVisible(false);
stop.setVisible(false);
oneMinute.setVisible(false);
twoMinutes.setVisible(false);
setTimerShortcutsEnabled(false);
}
public void showLiftControls() {
logger.trace("showing announcer decision buttons");
announce.setEnabled(true);
okLift.setEnabled(true);
failedLift.setEnabled(true);
}
public void hideLiftControls() {
logger.trace("hiding announcer decision buttons");
announce.setEnabled(false);
okLift.setEnabled(false);
failedLift.setEnabled(false);
}
private void okLiftDoIt(final Lifter lifter, final SessionData groupData) {
final long currentTimeMillis = System.currentTimeMillis();
// ignore two clicks on the same button in quick succession
if ((currentTimeMillis - lifterInfo.getLastOkButtonClick()) > MIN_CLICK_DELAY) {
logger.debug("Ok: délai acceptable: {}-{}={}",
new Object[] { currentTimeMillis, lifterInfo.getLastOkButtonClick(),
(currentTimeMillis - lifterInfo.getLastOkButtonClick()) });
lifterInfo.setLastOkButtonClick(currentTimeMillis);
logger.debug("Ok: dernier click accepté: {} {}", (lifterInfo.getLastOkButtonClick()), lifterInfo);
timingLogger.debug("okLift"); //$NON-NLS-1$
// call group data first because this resets the timers
logger.info("successful lift for {} {}", lifter.getLastName(), lifter.getFirstName()); //$NON-NLS-1$
lifterInfo.setBlocked(true);
groupData.okLiftUpdateModel();
} else {
logger.debug("Ok: délai Inacceptable: {}", currentTimeMillis - lifterInfo.getLastOkButtonClick());
}
}
private void failedLiftDoIt(final Lifter lifter, final SessionData groupData) {
final long currentTimeMillis = System.currentTimeMillis();
// ignore two clicks on the same button in quick succession
if (currentTimeMillis - lifterInfo.getLastFailedButtonClick() > MIN_CLICK_DELAY) {
logger.debug("Failed: délai acceptable: {}", currentTimeMillis
- lifterInfo.getLastFailedButtonClick());
lifterInfo.setLastFailedButtonClick(currentTimeMillis);
timingLogger.debug("failedLift"); //$NON-NLS-1$
// call group data first because this resets the timers
logger.info("failed lift for {} {}", lifter.getLastName(), lifter.getFirstName()); //$NON-NLS-1$
lifterInfo.setBlocked(true);
groupData.failedListUpdateModel();
} else {
logger.debug("Failed: délai Inacceptable: {}", currentTimeMillis
- lifterInfo.getLastFailedButtonClick());
}
}
public void startDoIt(final Lifter lifter, final SessionData groupData) {
logger.info("start clicked");
groupData.setTimeKeepingInUse(true);
if (groupData.getTimer().isRunning()) {
// do nothing
timingLogger.debug("start timer.isRunning()={}", true); //$NON-NLS-1$
} else {
lifterInfo.setBlocked(false); // !!!!
enableStopStart(true);
timingLogger.debug("start timer.isRunning()={}", false); //$NON-NLS-1$
groupData.startUpdateModel();
}
}
private void stopDoIt(final Lifter lifter, final SessionData groupData) {
logger.info("stop clicked");
groupData.setTimeKeepingInUse(true);
if (groupData.getTimer().isRunning()) {
timingLogger.debug("stop timer.isRunning()={}", true); //$NON-NLS-1$
lifterInfo.setBlocked(true);
groupData.stopUpdateModel();
enableStopStart(false);
} else {
timingLogger.debug("stop timer.isRunning()={}", false); //$NON-NLS-1$
// do nothing.
}
}
private void oneMinuteDoIt(final Lifter lifter, final SessionData groupData) {
timingLogger.debug("oneMinute"); //$NON-NLS-1$
// call group data first because this resets the timers
logger.info("resetting to one minute for {}", lifter); //$NON-NLS-1$
groupData.oneMinuteUpdateModel();
enableStopStart(false);
}
private void twoMinutesDoIt(final Lifter lifter, final SessionData groupData) {
timingLogger.debug("twoMinutes"); //$NON-NLS-1$
// call group data first because this resets the timers
logger.info("resetting to two minutes for {}", lifter); //$NON-NLS-1$
groupData.twoMinuteUpdateModel();
enableStopStart(false);
}
@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 initActions(Action.Notifier actionNotifier, final Lifter lifter, final SessionData groupData) {
startAction = new ShortcutActionListener("start", ShortcutAction.KeyCode.G){
@Override
public void handleAction(Object sender, Object target) {
if (!timerShortcutsEnabled) return;
TimerControls.this.startDoIt(lifter,groupData);
}
};
stopAction = new ShortcutActionListener("stop",ShortcutAction.KeyCode.P){
@Override
public void handleAction(Object sender, Object target) {
if (!timerShortcutsEnabled) return;
TimerControls.this.stopDoIt(lifter,groupData);
}
};
oneMinuteAction = new ShortcutActionListener("1 minute",ShortcutAction.KeyCode.O){
@Override
public void handleAction(Object sender, Object target) {
if (!timerShortcutsEnabled) return;
TimerControls.this.oneMinuteDoIt(lifter,groupData);
}
};
twoMinutesAction = new ShortcutActionListener("2 minutes",ShortcutAction.KeyCode.T){
@Override
public void handleAction(Object sender, Object target) {
if (!timerShortcutsEnabled) return;
TimerControls.this.twoMinutesDoIt(lifter,groupData);
}
};
actionNotifier.addAction(startAction);
actionNotifier.addAction(stopAction);
actionNotifier.addAction(oneMinuteAction);
actionNotifier.addAction(twoMinutesAction);
}
public void unregisterListeners() {
Window mainWindow = CompetitionApplication.getCurrent().getMainWindow();
mainWindow.removeAction(startAction);
mainWindow.removeAction(stopAction);
mainWindow.removeAction(oneMinuteAction);
mainWindow.removeAction(twoMinutesAction);
}
public void registerListeners(Lifter lifter, SessionData groupData) {
Window mainWindow = CompetitionApplication.getCurrent().getMainWindow();
initActions(mainWindow, lifter, groupData);
}
}
| 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.components;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.vaadin.ui.DateField;
@SuppressWarnings("serial")
public class ISO8601DateField extends DateField {
private static final String YEAR_FORMAT = "yyyy";
private static final String MONTH_FORMAT = "yyyy-MM";
private static final String DAY_FORMAT = "yyyy-MM-dd";
private static final String HOUR_FORMAT = "yyyy-MM-dd HH";
private static final String MIN_FORMAT = "yyyy-MM-dd HH:mm";
private static final String SEC_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String MSEC_FORMAT = "yyyy-MM-dd HH:mm:ss,SSS";
private SimpleDateFormat formatter = new SimpleDateFormat(MIN_FORMAT);
@Override
public String toString() {
Date date = (Date)this.getValue();
if (date == null) {
return "";
}
return formatter.format(date);
}
@Override
public String getDateFormat() {
switch (getResolution()) {
case RESOLUTION_MSEC:
return MSEC_FORMAT;
case RESOLUTION_SEC:
return SEC_FORMAT;
case RESOLUTION_MIN:
return MIN_FORMAT;
case RESOLUTION_HOUR:
return HOUR_FORMAT;
case RESOLUTION_DAY:
return DAY_FORMAT;
case RESOLUTION_MONTH:
return MONTH_FORMAT;
case RESOLUTION_YEAR:
return YEAR_FORMAT;
default:
return MIN_FORMAT;
}
}
@Override
public void setResolution(int resolution) {
super.setResolution(resolution);
setDateFormat(this.getDateFormat());
formatter = new SimpleDateFormat(this.getDateFormat());
}
}
| 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.components;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Window.CloseListener;
/**
* In this application the views need to refresh themselves when the user
* switches groups, or when they receive events.
*
*/
public interface ApplicationView extends ComponentContainer, CloseListener, URIHandler {
public void refresh();
/**
* @return true if the menu bar is needed
*/
public boolean needsMenu();
/**
*/
public void setParametersFromFragment();
/**
*/
public String getFragment();
public void registerAsListener();
public void 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.MalformedURLException;
import java.net.URL;
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.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.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;
public class CountdownDisplay extends VerticalLayout implements
ApplicationView,
CountdownTimerListener,
DecisionEventListener,
CloseListener,
URIHandler
{
public final static Logger logger = LoggerFactory.getLogger(CountdownDisplay.class);
private static final long serialVersionUID = 1437157542240297372L;
private String platformName;
private SessionData masterData;
private CompetitionApplication app;
private Label timeDisplay = new Label();
private int lastTimeRemaining;
private String viewName;
private Window popUp = null;
private DecisionLightsWindow decisionLights;
private UpdateEventListener updateEventListener;
protected boolean shown;
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 CountdownDisplay(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();
} else if (app.getPlatform() == null) {
app.setPlatformByName(platformName);
}
synchronized (app) {
boolean prevDisabled = app.getPusherDisabled();
try {
app.setPusherDisabled(true);
create(app, platformName);
masterData = app.getMasterData(platformName);
app.getMainWindow().addURIHandler(this);
registerAsListener();
display(platformName, masterData);
} finally {
app.setPusherDisabled(prevDisabled);
}
}
}
private void registerAsGroupDataListener(final String platformName1, final SessionData masterData1) {
// locate the current group data for the platformName
if (masterData1 != null) {
logger.debug("{} listening to: {}", platformName1, masterData1); //$NON-NLS-1$
//masterData.addListener(SessionData.UpdateEvent.class, this, "update"); //$NON-NLS-1$
updateEventListener = new SessionData.UpdateEventListener() {
@Override
public void updateEvent(UpdateEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
display(platformName1, masterData1);
}
}).start();
}
};
masterData1.addListener(updateEventListener); //$NON-NLS-1$
} else {
logger.debug("{} NOT listening to: = {}", platformName1, masterData1); //$NON-NLS-1$
}
}
/**
* @param app1
* @param platformName1
* @throws MalformedURLException
*/
private void create(UserActions app1, String platformName1) {
this.setSizeFull();
this.addStyleName("largeCountdownBackground");
timeDisplay = createTimeDisplay();
this.addComponent(timeDisplay);
this.setComponentAlignment(timeDisplay, Alignment.MIDDLE_CENTER);
this.setExpandRatio(timeDisplay, 100);
}
/**
*
*/
private Label createTimeDisplay() {
Label timeDisplay1 = new Label();
timeDisplay1.setSizeUndefined();
timeDisplay1.setHeight("600px");
timeDisplay1.addStyleName("largeCountdown");
return timeDisplay1;
}
/**
* @param platformName1
* @param masterData1
* @throws RuntimeException
*/
private void display(final String platformName1, final SessionData masterData1) throws RuntimeException {
synchronized (app) {
final Lifter currentLifter = masterData1.getCurrentLifter();
if (currentLifter != null) {
boolean done = fillLifterInfo(currentLifter);
updateTime(masterData1);
timeDisplay.setVisible(!done);
} else {
timeDisplay.setValue(""); //$NON-NLS-1$
}
}
app.push();
}
@Override
public void refresh() {
display(platformName, masterData);
}
public boolean fillLifterInfo(Lifter lifter) {
final int currentTry = 1 + (lifter.getAttemptsDone() >= 3 ? lifter.getCleanJerkAttemptsDone() : lifter
.getSnatchAttemptsDone());
boolean done = currentTry > 3;
return done;
}
/**
* @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();
pushTime(timeRemaining);
}
@Override
public void finalWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void forceTimeRemaining(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
pushTime(timeRemaining);
}
@Override
public void initialWarning(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void noTimeLeft(int timeRemaining) {
normalTick(timeRemaining);
}
@Override
public void normalTick(int timeRemaining) {
pushTime(timeRemaining);
}
/**
* @param timeRemaining
*/
private void pushTime(int timeRemaining) {
if (timeDisplay == null) return;
// do not update if no visible change
if (TimeFormatter.getSeconds(timeRemaining) == TimeFormatter.getSeconds(lastTimeRemaining)) {
lastTimeRemaining = timeRemaining;
return;
} else {
lastTimeRemaining = timeRemaining;
}
synchronized (app) {
timeDisplay.setValue(TimeFormatter.formatAsSeconds(timeRemaining));
}
app.push();
}
@Override
public void pause(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
@Override
public void start(int timeRemaining) {
}
@Override
public void stop(int timeRemaining, CompetitionApplication originatingApp, TimeStoppedNotificationReason reason) {
}
/* (non-Javadoc)
* @see org.concordiainternational.competition.ui.components.ApplicationView#needsMenu()
*/
@Override
public boolean needsMenu() {
return false;
}
/**
* @return
*/
@Override
public String getFragment() {
return viewName+"/"+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 updateEvent(final DecisionEvent updateEvent) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (app) {
switch (updateEvent.getType()) {
case DOWN:
logger.info("received DOWN event");
showLights(updateEvent);
break;
case SHOW:
// if window is not up, show it.
shown = true;
logger.info("received SHOW event {}",shown);
showLights(updateEvent);
break;
case RESET:
// we are done
logger.info("received RESET event (hiding decision lights)");
hideLights(updateEvent);
shown = false;
break;
case WAITING:
logger.info("ignoring WAITING event");
break;
case UPDATE:
logger.debug("received UPDATE event {}",shown);
// we need to show that referees have changed their mind.
if (shown) {
showLights(updateEvent);
}
break;
case BLOCK:
logger.debug("received BLOCK event {}",shown);
showLights(updateEvent);
break;
}
}
app.push();
}
}).start();
}
/**
* Make sure decision lights are shown, and relay the event to the display component.
* @param updateEvent
*/
private void showLights(DecisionEvent updateEvent) {
// create window
if (popUp == null) {
logger.debug("creating window");
Window mainWindow = app.getMainWindow();
decisionLights = new DecisionLightsWindow(false, false);
popUp = new Window(platformName);
popUp.addStyleName("decisionLightsWindow");
popUp.setSizeFull();
mainWindow.addWindow(popUp);
popUp.setContent(decisionLights);
}
popUp.setVisible(true);
// relay the event
logger.debug("relaying");
decisionLights.updateEvent(updateEvent);
}
/**
* Hide the decision lights.
* @param updateEvent
*/
private void hideLights(DecisionEvent updateEvent) {
// relay the event (just in case)
if (decisionLights != null) {
decisionLights.updateEvent(updateEvent);
}
// close window
if (popUp != null) {
popUp.setVisible(false);
}
}
/**
* Resister to all necessary listening events
*/
@Override
public void registerAsListener() {
Window mainWindow = app.getMainWindow();
mainWindow.addListener((CloseListener)this);
registerAsGroupDataListener(platformName, masterData);
masterData.getRefereeDecisionController().addListener(this);
final CountdownTimer timer = masterData.getTimer();
timer.setCountdownDisplay(this);
addActions(mainWindow);
logger.warn("added action handler");
}
/**
* Undo what registerAsListener did.
*/
@Override
public void unregisterAsListener() {
Window mainWindow = app.getMainWindow();
mainWindow.removeListener((CloseListener)this);
masterData.removeListener(updateEventListener);
masterData.getRefereeDecisionController().removeListener(this);
final CountdownTimer timer = masterData.getTimer();
timer.setCountdownDisplay(null);
removeActions(mainWindow);
}
@Override
public DownloadStream handleURI(URL context, String relativeUri) {
registerAsListener();
return null;
}
@Override
public void windowClose(CloseEvent e) {
unregisterAsListener();
}
public DecisionLightsWindow getDecisionLights() {
return decisionLights;
}
public void setDecisionLights(DecisionLightsWindow decisionLights) {
this.decisionLights = decisionLights;
}
@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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.