Merge remote-tracking branch 'origin/master'

This commit is contained in:
Axel Uhl
2013-03-01 01:15:49 -08:00
13 changed files with 783 additions and 1204 deletions
@@ -4,11 +4,11 @@
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>XcelsiusApp</servlet-name>
<servlet-class>com.sap.sailing.xcelsiusadapter.XcelsiusApp</servlet-class>
<servlet-name>XcelsiusServlet</servlet-name>
<servlet-class>com.sap.sailing.xcelsiusadapter.XcelsiusServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XcelsiusApp</servlet-name>
<servlet-name>XcelsiusServlet</servlet-name>
<url-pattern>/xcelsius</url-pattern>
</servlet-mapping>
</web-app>
@@ -26,10 +26,10 @@ import com.sap.sailing.domain.tracking.TrackedLegOfCompetitor;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.server.RacingEventService;
public class GPSPerRace extends Action {
public class GPSPerRaceAction extends HttpAction {
private final Set<String> competitorNameSet;
public GPSPerRace(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public GPSPerRaceAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
String[] competitors = req.getParameterValues("competitor");
if (competitors == null) {
@@ -7,7 +7,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -31,12 +30,14 @@ import com.sap.sailing.domain.base.Regatta;
import com.sap.sailing.domain.base.RaceDefinition;
import com.sap.sailing.domain.base.impl.MillisecondsTimePoint;
import com.sap.sailing.domain.common.TimePoint;
import com.sap.sailing.domain.leaderboard.Leaderboard;
import com.sap.sailing.domain.leaderboard.RegattaLeaderboard;
import com.sap.sailing.domain.tracking.DynamicTrackedRegatta;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.server.RacingEventService;
import com.sap.sailing.util.InvalidDateException;
public class Action {
public abstract class HttpAction {
private HttpServletRequest req;
private HttpServletResponse res;
@@ -49,7 +50,7 @@ public class Action {
private int rowCount;
private Element currentRow;
public Action(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public HttpAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
this.req = req;
this.res = res;
this.service = service;
@@ -88,6 +89,23 @@ public class Action {
}
return regatta;
}
public RegattaLeaderboard getRegattaLeaderboard() throws IOException {
/*
* Leaderboard name is always equal Regatta name
*/
final String leaderboardName = getAttribute("regatta");
if (leaderboardName == null) {
say("Use the regatta= parameter to specify the regatta");
return null;
}
final Leaderboard leaderboard = getService().getLeaderboardByName(leaderboardName);
if (leaderboard == null || !(leaderboard instanceof RegattaLeaderboard)) {
say("Regatta " + leaderboardName + " not found.");
return null;
}
return (RegattaLeaderboard)leaderboard;
}
public Regatta getEvent(String name) {
for (final Regatta regatta : this.service.getAllRegattas()) {
@@ -100,9 +118,6 @@ public class Action {
}
public RaceDefinition getRace(Regatta regatta) throws IOException {
/*
* Get the race
*/
final String raceName = getAttribute("race");
if (raceName == null) {
@@ -111,9 +126,6 @@ public class Action {
return null;
}
/*
* RACE
*/
final RaceDefinition race = getRace(regatta, raceName);
if (race == null) {
@@ -163,13 +175,21 @@ public class Action {
if (start == null) {
return null;
}
final long mTime = start.asMillis() + (StringUtility.StringToInteger(time, 0) * 1000 * 60);
final long mTime = start.asMillis() + (stringToInteger(time, 0) * 1000 * 60);
final TimePoint bTimePoint = new MillisecondsTimePoint(mTime);
return bTimePoint;
}
return null;
}
private int stringToInteger(String strString, int intDefault) {
try {
return Integer.parseInt(strString);
} catch (NumberFormatException e) {
return intDefault;
}
}
public Document getTable(String variable) {
this.table = new Document();
final Element data = new Element("data");
@@ -196,7 +216,7 @@ public class Action {
this.currentRow.addContent(col);
}
}
public void addNamedColumn(String content, String columnName) {
if (maxRows == -1 || rowCount <= maxRows) {
final Element col = new Element(columnName);
@@ -217,77 +237,69 @@ public class Action {
}
public void say(Document doc) throws IOException {
this.res.setCharacterEncoding("UTF-8");
this.res.setCharacterEncoding("UTF-8");
this.res.getWriter().print(getXMLAsString(doc));
}
public void say(String msg) throws IOException {
say(msg, this.res);
}
public void sendDocument(Document doc, String fileName){
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Result outputTarget = new StreamResult(outputStream);
DOMOutputter outputter = new DOMOutputter() ;
org.w3c.dom.Document w3cDoc = outputter.output(doc);
Source xmlSource = new DOMSource(w3cDoc);
stream = res.getOutputStream();
res.setContentType("text/xml");
res.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
buf = new BufferedInputStream(is);
int readBytes = 0;
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch(TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (JDOMException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (buf != null)
try {
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
}
public void sendDocument(Document doc, String fileName) {
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Result outputTarget = new StreamResult(outputStream);
DOMOutputter outputter = new DOMOutputter();
org.w3c.dom.Document w3cDoc = outputter.output(doc);
Source xmlSource = new DOMSource(w3cDoc);
stream = res.getOutputStream();
res.setContentType("text/xml");
res.addHeader("Content-Disposition", "attachment; filename=" + fileName);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
buf = new BufferedInputStream(is);
int readBytes = 0;
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (buf != null)
try {
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String getXMLAsString(Object context) {
return getXMLAsString(context, "UTF-8");
@@ -297,14 +309,15 @@ public class Action {
// final XMLOutputter outputter = new XMLOutputter(" ", true, encoding);
final Format format = Format.getPrettyFormat();
format.setIndent(" ");
// Despite of setting the expand true (result is <column></column> instead of <column/> browsers like firefox dont display the columns correctly
// Despite of setting the expand true (result is <column></column> instead of <column/> browsers like firefox
// dont display the columns correctly
format.setExpandEmptyElements(true);
format.setEncoding(encoding);
final XMLOutputter outputter = new XMLOutputter(format);
if (context instanceof Document) {
String res = outputter.outputString((Document) context);
String res = outputter.outputString((Document) context);
return res;
}
@@ -26,8 +26,8 @@ import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.domain.tracking.Wind;
import com.sap.sailing.server.RacingEventService;
public class ListEvents extends Action {
public ListEvents(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public class ListEventsAction extends HttpAction {
public ListEventsAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
}
@@ -23,10 +23,10 @@ import com.sap.sailing.domain.tracking.TrackedLegOfCompetitor;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.server.RacingEventService;
public class RankPerLeg2 extends Action {
public class RankPerLeg2Action extends HttpAction {
private final Set<String> competitorNameSet;
public RankPerLeg2(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public RankPerLeg2Action(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
String[] competitors = req.getParameterValues("competitor");
if (competitors == null) {
@@ -24,10 +24,10 @@ import com.sap.sailing.domain.tracking.TrackedLegOfCompetitor;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.server.RacingEventService;
public class RankPerLeg extends Action {
public class RankPerLegAction extends HttpAction {
private final Set<String> competitorNameSet;
public RankPerLeg(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public RankPerLegAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
String[] competitors = req.getParameterValues("competitor");
if (competitors == null) {
@@ -21,10 +21,10 @@ import com.sap.sailing.domain.tracking.TrackedLeg;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.server.RacingEventService;
public class RankPerRace extends Action {
public class RankPerRaceAction extends HttpAction {
private final Set<String> competitorNameSet;
public RankPerRace(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
public RankPerRaceAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
String[] competitors = req.getParameterValues("competitor");
if (competitors == null) {
@@ -1,392 +0,0 @@
package com.sap.sailing.xcelsiusadapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Document;
import org.jdom.Element;
import com.sap.sailing.domain.base.Competitor;
import com.sap.sailing.domain.base.Leg;
import com.sap.sailing.domain.base.RaceDefinition;
import com.sap.sailing.domain.base.Regatta;
import com.sap.sailing.domain.base.impl.MillisecondsTimePoint;
import com.sap.sailing.domain.common.Position;
import com.sap.sailing.domain.common.TimePoint;
import com.sap.sailing.domain.common.WindSource;
import com.sap.sailing.domain.common.WindSourceType;
import com.sap.sailing.domain.common.impl.Util.Pair;
import com.sap.sailing.domain.common.impl.WindSourceImpl;
import com.sap.sailing.domain.tracking.MarkPassing;
import com.sap.sailing.domain.tracking.TrackedLeg;
import com.sap.sailing.domain.tracking.TrackedLegOfCompetitor;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.domain.tracking.WindTrack;
import com.sap.sailing.domain.tracking.WindWithConfidence;
import com.sap.sailing.server.RacingEventService;
public class RegattaDataPerLeg extends Action {
public RegattaDataPerLeg(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
}
public void perform() throws Exception {
final Regatta regatta = getRegatta(); // Get regatta data from request (get value for regatta name from URL parameter regatta)
// if the regatta does not exist a tag <message> will be returned with a text message from function
// getRegatta().
if (regatta == null) {
return;
}
final Document doc = new Document(); // initialize xml document
final Element regatta_node = addNamedElement(doc, "regatta"); // add root to xml
addNamedElementWithValue(regatta_node, "name", regatta.getName());
addNamedElementWithValue(regatta_node, "boat_class", regatta.getBoatClass().getName());
/*
* Races
*/
final HashMap<String, RaceDefinition> races = getRaces(regatta); // get races for the regatta
final Element races_node = addNamedElement(regatta_node, "races"); // add node that contains all races
for (final RaceDefinition race : races.values()) { // for each race in the list
final Element race_node = addNamedElement(races_node, "race"); // add race node for the current race
addNamedElementWithValue(race_node, "name", race.getName()); // add name node to current race
// skip race if not tracked
final TrackedRace trackedRace = getTrackedRace(regatta, race);
if (trackedRace == null || !trackedRace.hasGPSData()) {
continue;
}
final TimePoint raceStarted = getTimePoint(trackedRace); // get TimePoint for when the race started
if (raceStarted == null) {
continue;
}
long minNextLegStart = raceStarted.asMillis(); // variable for keeping track of when the first competitor
// started the next leg
TimePoint legStarted = new MillisecondsTimePoint(minNextLegStart); // get TimePoint for when the leg started
addNamedElementWithValue(race_node, "start_time_ms", raceStarted.asMillis()); // add the starttime to the
if (trackedRace.getEndOfRace() != null) {
addNamedElementWithValue(race_node, "assumed_end_ms", trackedRace.getEndOfRace().asMillis()); // add the assumed enddtime
} else {
addNamedElementWithValue(race_node, "assumed_end_ms", 0); // add the assumed enddtime
}
Calendar cal = Calendar.getInstance();
cal.setTime(raceStarted.asDate());
addNamedElementWithValue(race_node, "start_time_year", cal.get(Calendar.YEAR));
int month = cal.get(Calendar.MONTH) + 1;
addNamedElementWithValue(race_node, "start_time_month", month);
addNamedElementWithValue(race_node, "start_time_day", cal.get(Calendar.DAY_OF_MONTH));
addNamedElementWithValue(race_node, "start_time_hour", cal.get(Calendar.HOUR_OF_DAY));
addNamedElementWithValue(race_node, "start_time_minute", cal.get(Calendar.MINUTE));
addNamedElementWithValue(race_node, "start_time_second", cal.get(Calendar.SECOND));
addNamedElementWithValue(race_node, "start_time_formatted", (cal.get(Calendar.DAY_OF_MONTH) < 10 ? ("0" + cal.get(Calendar.DAY_OF_MONTH)) : cal.get(Calendar.DAY_OF_MONTH))
+ "."
+ (month < 10 ? ("0" + month) : month)
+ "."
+ cal.get(Calendar.YEAR)
+ " - "
+ (cal.get(Calendar.HOUR_OF_DAY) < 10 ? ("0" + cal.get(Calendar.HOUR_OF_DAY)) : cal
.get(Calendar.HOUR_OF_DAY))
+ ":"
+ (cal.get(Calendar.MINUTE) < 10 ? ("0" + cal.get(Calendar.MINUTE)) : cal
.get(Calendar.MINUTE))
+ ":"
+ (cal.get(Calendar.SECOND) < 10 ? ("0" + cal.get(Calendar.SECOND)) : cal
.get(Calendar.SECOND)));
Pair<Double, Double> averageWindSpeedofRace = calculateAverageWindSpeedofRace(trackedRace);
String wind_strength = "";
if (averageWindSpeedofRace != null) {
if (averageWindSpeedofRace.getA() < 4) {
wind_strength = "Very light";
} else if (averageWindSpeedofRace.getA() >= 4 && averageWindSpeedofRace.getA() < 8) {
wind_strength = "Light";
} else if (averageWindSpeedofRace.getA() >= 8 && averageWindSpeedofRace.getA() < 14) {
wind_strength = "Medium";
} else if (averageWindSpeedofRace.getA() >= 14 && averageWindSpeedofRace.getA() < 20) {
wind_strength = "Strong";
} else if (averageWindSpeedofRace.getA() >= 20) {
wind_strength = "Very strong";
}
}
Double wind_speed = 0.0;
Double wind_confi = 0.0;
if (averageWindSpeedofRace != null) {
wind_speed = averageWindSpeedofRace.getA();
wind_confi = averageWindSpeedofRace.getB();
}
addNamedElementWithValue(race_node, "average_wind_speed", wind_speed);
addNamedElementWithValue(race_node, "average_wind_speed_confidence", wind_confi);
addNamedElementWithValue(race_node, "wind_strength", wind_strength);
/*
* Legs
*/
int i = 0; // initialize leg index
TrackedLeg previousLeg = null;
final Element legs_node = addNamedElement(race_node, "legs"); // add element that holds all legs for the
// race
for (final TrackedLeg trackedLeg : trackedRace.getTrackedLegs()) {
final Leg leg = trackedLeg.getLeg();
final Element leg_node = addNamedElement(legs_node, "leg"); // add element for single leg
addNamedElementWithValue(leg_node, "leg_number", ++i);
addNamedElementWithValue(leg_node, "mark_from", leg.getFrom().getName());
addNamedElementWithValue(leg_node, "mark_to", leg.getTo().getName());
addNamedElementWithValue(leg_node, "leg_type", (trackedLeg.getLegType(legStarted).toString()));
/*
* Competitors
*/
LinkedHashMap<Competitor, Integer> ranks = trackedLeg.getRanks(legStarted); // get the ranking
// information for the race
// (at leg start time)
final Element competitor_data_node = addNamedElement(leg_node, "competitor_data"); // add element that
// holds the leg
// summary data for
// each competitor
for (final Competitor competitor : ranks.keySet()) { // Get competitor data
TrackedLegOfCompetitor trackedLegOfCompetitor = trackedLeg.getTrackedLeg(competitor); // Get data
TimePoint compareLegEnd = new MillisecondsTimePoint(0);
// time elapsed / when did the competitor pass the end mark of the leg
MarkPassing mp = trackedRace.getMarkPassing(competitor, leg.getTo());
if (mp != null) {
compareLegEnd = mp.getTimePoint();
}
final long compLegTimeAlt = trackedLegOfCompetitor.getTimeInMilliSeconds(compareLegEnd);
final TimePoint compFinishedLeg = compareLegEnd;
// plausibility check
// competitor has finished the leg and the leg end time is not the race start time
if (trackedLegOfCompetitor.hasFinishedLeg(compFinishedLeg) && compareLegEnd.asMillis() != 0) {
// Calculate rank loss/gain
int posGL = 0;
if (previousLeg != null) {
posGL = trackedLegOfCompetitor.getRank(compFinishedLeg)
- previousLeg.getTrackedLeg(competitor).getRank(compFinishedLeg);
}
final Element competitor_node = addNamedElement(competitor_data_node, "competitor");
try {
addNamedElementWithValue(competitor_node, "name", competitor.getName());
addNamedElementWithValue(competitor_node, "nationality", competitor.getTeam()
.getNationality().getThreeLetterIOCAcronym());
addNamedElementWithValue(competitor_node, "sail_id", competitor.getBoat().getSailID());
String sail_id = competitor.getBoat().getSailID();
if (sail_id.matches("^[A-Z]{3}\\s[0-9]*")) {
Pattern regex = Pattern.compile("(^[A-Z]{3})\\s([0-9]*)");
Matcher regexMatcher = regex.matcher(sail_id);
try {
String resultString = regexMatcher.replaceAll("$1$2");
addNamedElementWithValue(competitor_node, "sail_id_formatted", resultString);
} catch (Exception e) {
e.printStackTrace();
}
} else if (sail_id.matches("^[A-Z]{3}\\S[0-9]*")) {
addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
} else if (sail_id.matches("[0-9]*")){
addNamedElementWithValue(competitor_node, "sail_id_formatted", competitor.getTeam().getNationality().getThreeLetterIOCAcronym() + sail_id);
} else {
addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
}
addNamedElementWithValue(competitor_node, "leg_finished_time_ms", compFinishedLeg.asMillis());
addNamedElementWithValue(competitor_node, "time_elapsed_ms", compFinishedLeg.asMillis() - raceStarted.asMillis());
addNamedElementWithValue(competitor_node, "leg_time_ms", compLegTimeAlt);
addNamedElementWithValue(competitor_node, "leg_rank", trackedLegOfCompetitor.getRank(compFinishedLeg));
addNamedElementWithValue(competitor_node, "race_final_rank", trackedRace.getRank(competitor));
addNamedElementWithValue(competitor_node, "rank_gain", posGL * -1); // Ranks Gained/Lost
addNamedElementWithValue(competitor_node, "gap_to_leader_s", trackedLegOfCompetitor.getGapToLeaderInSeconds(compFinishedLeg));
addNamedElementWithValue(competitor_node, "ww_distance_to_leader_m", 0);
// addNamedElementWithValue(competitor_node, "avg_xte", trackedLegOfCompetitor.getAverageCrossTrackError(compFinishedLeg).getMeters());
// addNamedElementWithValue(competitor_node, "avg_vmg_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());//windwardSpeed over ground on leg finished time
addNamedElementWithValue(competitor_node, "avg_speed_og_kn", trackedLegOfCompetitor.getAverageSpeedOverGround(compFinishedLeg).getKnots());
addNamedElementWithValue(competitor_node, "avg_speed_ww_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());// windwardSpeed over
// ground on leg finished
// time
addNamedElementWithValue(competitor_node, "distance_traveled_m", trackedLegOfCompetitor.getDistanceTraveled(compFinishedLeg).getMeters());
addNamedElementWithValue(competitor_node, "number_of_jibes", trackedLegOfCompetitor.getNumberOfJibes(compFinishedLeg));
addNamedElementWithValue(competitor_node, "number_of_tacks", trackedLegOfCompetitor.getNumberOfTacks(compFinishedLeg));
addNamedElementWithValue(competitor_node, "number_of_penalty_circles", trackedLegOfCompetitor.getNumberOfPenaltyCircles(compFinishedLeg));
addNamedElementWithValue(competitor_node, "average_wind_speed", wind_speed);
addNamedElementWithValue(competitor_node, "average_wind_speed_confidence", wind_confi);
// Waypoint finish = trackedRace.getRace().getCourse().getLastWaypoint();
//
// Iterable<MarkPassing> markpassings = trackedRace.getMarkPassingsInOrder(finish);
// Iterator<MarkPassing> iter = markpassings.iterator();
// MarkPassing firstMarkPassing = null;
// if (iter.hasNext()) {
// firstMarkPassing = iter.next();
// }
//
//
//// Map<Waypoint, NavigableSet<MarkPassing>> markPassingsForWaypoint = new HashMap<Waypoint, NavigableSet<MarkPassing>>();
//// for (Waypoint waypoint : trackedRace.getRace().getCourse().getWaypoints()) {
//// markPassingsForWaypoint.put(waypoint, new ConcurrentSkipListSet<MarkPassing>(
//// MarkPassingByTimeComparator.INSTANCE));
//// }
////
//// NavigableSet<MarkPassing> markPassingsInOrder = markPassingsForWaypoint.get(finish);
//// MarkPassing firstMarkPassing = null;
//// synchronized (markPassingsInOrder) {
//// if (!markPassingsInOrder.isEmpty()) {
//// firstMarkPassing = markPassingsInOrder.first();
//// }
//// }
// TimePoint timeOfFirstMarkPassing = null;
// if (firstMarkPassing != null) {
// timeOfFirstMarkPassing = firstMarkPassing.getTimePoint();
// }
//
// trackedRace.getWindwardDistanceToOverallLeader(competitor, timeOfFirstMarkPassing);
// assign the smallest start time for the next leg
minNextLegStart = (minNextLegStart > compFinishedLeg.asMillis() ? compFinishedLeg
.asMillis() : minNextLegStart);
} catch (Exception ex) {
//competitor_data_node.removeContent(competitor_node); // if the competitor dataset is not complete, remove it from the list
// complete, remove it from the list
}
} else {
System.err.print("Competitpr Skipped:" + competitor.getName() + "; Race:" + race.getName()
+ "; Leg+" + ((Integer) i).toString());
}
} // competitor data end
legStarted = new MillisecondsTimePoint(minNextLegStart);
minNextLegStart = Long.MAX_VALUE;
previousLeg = trackedLeg;
// if the leg does not contain any competitor info
if (competitor_data_node.getChildren("competitor").size() == 0) {
legs_node.removeContent(leg_node);
}
} // leg end
// if the race does not contain any leg info
if (legs_node.getChildren("leg").size() == 0) {
races_node.removeContent(race_node);
}
} // regatta end
sendDocument(doc, regatta.getName() + ".xml");// output doc to client
} // function end
private Pair<Double, Double> calculateAverageWindSpeedofRace(TrackedRace trackedRace) {
Pair<Double, Double> result = null;
if (trackedRace.getEndOfRace() != null) {
TimePoint fromTimePoint = trackedRace.getStartOfRace();
TimePoint toTimePoint = trackedRace.getEndOfRace();
long resolutionInMilliseconds = 60 * 1000 * 5; // 5 min
List<WindSource> windSourcesToDeliver = new ArrayList<WindSource>();
WindSourceImpl windSource = new WindSourceImpl(WindSourceType.COMBINED);
windSourcesToDeliver.add(windSource);
double sumWindSpeed = 0.0;
double sumWindSpeedConfidence = 0.0;
int speedCounter = 0;
int numberOfFixes = (int) ((toTimePoint.asMillis() - fromTimePoint.asMillis()) / resolutionInMilliseconds);
WindTrack windTrack = trackedRace.getOrCreateWindTrack(windSource);
TimePoint timePoint = fromTimePoint;
for (int i = 0; i < numberOfFixes && toTimePoint != null && timePoint.compareTo(toTimePoint) < 0; i++) {
WindWithConfidence<Pair<Position, TimePoint>> averagedWindWithConfidence = windTrack
.getAveragedWindWithConfidence(null, timePoint);
if (averagedWindWithConfidence != null) {
double windSpeedinKnots = averagedWindWithConfidence.getObject().getKnots();
double confidence = averagedWindWithConfidence.getConfidence();
sumWindSpeed += windSpeedinKnots;
sumWindSpeedConfidence += confidence;
speedCounter++;
}
timePoint = new MillisecondsTimePoint(timePoint.asMillis() + resolutionInMilliseconds);
}
if (speedCounter > 0) {
double averageWindSpeed = sumWindSpeed / speedCounter;
double averageWindSpeedConfidence = sumWindSpeedConfidence / speedCounter;
result = new Pair<Double, Double>(averageWindSpeed, averageWindSpeedConfidence);
}
} else {
result = new Pair<Double, Double>(0.0, 0.0);
}
return result;
}
private void addNamedElementWithValue(Element parent, String newChildName, Integer i) {
if (i == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, i.toString());
}
}
private void addNamedElementWithValue(Element parent, String newChildName, Double dbl) {
if (dbl == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, dbl.toString());
}
}
private void addNamedElementWithValue(Element parent, String newChildName, Long l) {
if (l == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, l.toString());
}
}
private Element addNamedElement(Document doc, String newChildName) {
final Element newChild = new Element(newChildName);
doc.addContent(newChild);
return newChild;
}
private Element addNamedElementWithValue(Element parent, String newChildName, String value) {
final Element newChild = new Element(newChildName);
newChild.addContent(value);
parent.addContent(newChild);
return newChild;
}
private Element addNamedElement(Element parent, String newChildName) {
final Element newChild = new Element(newChildName);
parent.addContent(newChild);
return newChild;
}
}
@@ -0,0 +1,636 @@
package com.sap.sailing.xcelsiusadapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Document;
import org.jdom.Element;
import com.sap.sailing.domain.base.Competitor;
import com.sap.sailing.domain.base.Fleet;
import com.sap.sailing.domain.base.Leg;
import com.sap.sailing.domain.base.RaceColumn;
import com.sap.sailing.domain.base.RaceDefinition;
import com.sap.sailing.domain.base.impl.MillisecondsTimePoint;
import com.sap.sailing.domain.common.Position;
import com.sap.sailing.domain.common.TimePoint;
import com.sap.sailing.domain.common.WindSource;
import com.sap.sailing.domain.common.WindSourceType;
import com.sap.sailing.domain.common.impl.Util.Pair;
import com.sap.sailing.domain.common.impl.WindSourceImpl;
import com.sap.sailing.domain.leaderboard.Leaderboard;
import com.sap.sailing.domain.leaderboard.RegattaLeaderboard;
import com.sap.sailing.domain.tracking.MarkPassing;
import com.sap.sailing.domain.tracking.TrackedLeg;
import com.sap.sailing.domain.tracking.TrackedLegOfCompetitor;
import com.sap.sailing.domain.tracking.TrackedRace;
import com.sap.sailing.domain.tracking.WindTrack;
import com.sap.sailing.domain.tracking.WindWithConfidence;
import com.sap.sailing.server.RacingEventService;
public class RegattaDataPerLegAction extends HttpAction {
public RegattaDataPerLegAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
}
public void perform() throws Exception {
// final Regatta regatta = getRegatta(); // Get regatta data from request (get value for regatta name from URL parameter regatta)
// // if the regatta does not exist a tag <message> will be returned with a text message from function
// // getRegatta().
// if (regatta == null) {
// return;
// }
final RegattaLeaderboard leaderboard = getRegattaLeaderboard(); // Get leaderboard data from request (get value for regatta name from URL parameter regatta)
// if the regatta does not exist a tag <message> will be returned with a text message from function
// getLeaderboard().
if (leaderboard == null) {
return;
}
final Document doc = new Document(); // initialize xml document
final Element regatta_node = addNamedElement(doc, "regatta"); // add root to xml
addNamedElementWithValue(regatta_node, "name", leaderboard.getName());
addNamedElementWithValue(regatta_node, "boat_class", leaderboard.getRegatta().getBoatClass().getName());
/*
* Races
*/
// final HashMap<String, RaceDefinition> races = getRaces(regatta); // get races for the regatta
final Element races_node = addNamedElement(regatta_node, "races"); // add node that contains all races
for (RaceColumn r : leaderboard.getRaceColumns()) {
for (Fleet f : r.getFleets()) {
TrackedRace trackedRace = r.getTrackedRace(f);
// skip race if not tracked
if (trackedRace == null || !trackedRace.hasGPSData()) {
continue;
}
RaceDefinition race = trackedRace.getRace();
final Element race_node = addNamedElement(races_node, "race"); // add race node for the current race
addNamedElementWithValue(race_node, "name", race.getName()); // add name node to current race
final TimePoint raceStarted = getTimePoint(trackedRace); // get TimePoint for when the race started
if (raceStarted == null) {
continue;
}
long minNextLegStart = raceStarted.asMillis(); // variable for keeping track of when the first competitor
// started the next leg
TimePoint legStarted = new MillisecondsTimePoint(minNextLegStart); // get TimePoint for when the leg started
addNamedElementWithValue(race_node, "start_time_ms", raceStarted.asMillis()); // add the starttime to the
if (trackedRace.getEndOfRace() != null) {
addNamedElementWithValue(race_node, "assumed_end_ms", trackedRace.getEndOfRace().asMillis()); // add the assumed enddtime
} else {
addNamedElementWithValue(race_node, "assumed_end_ms", 0); // add the assumed enddtime
}
Calendar cal = Calendar.getInstance();
cal.setTime(raceStarted.asDate());
addNamedElementWithValue(race_node, "start_time_year", cal.get(Calendar.YEAR));
int month = cal.get(Calendar.MONTH) + 1;
addNamedElementWithValue(race_node, "start_time_month", month);
addNamedElementWithValue(race_node, "start_time_day", cal.get(Calendar.DAY_OF_MONTH));
addNamedElementWithValue(race_node, "start_time_hour", cal.get(Calendar.HOUR_OF_DAY));
addNamedElementWithValue(race_node, "start_time_minute", cal.get(Calendar.MINUTE));
addNamedElementWithValue(race_node, "start_time_second", cal.get(Calendar.SECOND));
addNamedElementWithValue(race_node, "start_time_formatted", (cal.get(Calendar.DAY_OF_MONTH) < 10 ? ("0" + cal.get(Calendar.DAY_OF_MONTH)) : cal.get(Calendar.DAY_OF_MONTH))
+ "."
+ (month < 10 ? ("0" + month) : month)
+ "."
+ cal.get(Calendar.YEAR)
+ " - "
+ (cal.get(Calendar.HOUR_OF_DAY) < 10 ? ("0" + cal.get(Calendar.HOUR_OF_DAY)) : cal
.get(Calendar.HOUR_OF_DAY))
+ ":"
+ (cal.get(Calendar.MINUTE) < 10 ? ("0" + cal.get(Calendar.MINUTE)) : cal
.get(Calendar.MINUTE))
+ ":"
+ (cal.get(Calendar.SECOND) < 10 ? ("0" + cal.get(Calendar.SECOND)) : cal
.get(Calendar.SECOND)));
Pair<Double, Double> averageWindSpeedofRace = calculateAverageWindSpeedofRace(trackedRace);
String wind_strength = "";
if (averageWindSpeedofRace != null) {
if (averageWindSpeedofRace.getA() < 4) {
wind_strength = "Very light";
} else if (averageWindSpeedofRace.getA() >= 4 && averageWindSpeedofRace.getA() < 8) {
wind_strength = "Light";
} else if (averageWindSpeedofRace.getA() >= 8 && averageWindSpeedofRace.getA() < 14) {
wind_strength = "Medium";
} else if (averageWindSpeedofRace.getA() >= 14 && averageWindSpeedofRace.getA() < 20) {
wind_strength = "Strong";
} else if (averageWindSpeedofRace.getA() >= 20) {
wind_strength = "Very strong";
}
}
Double wind_speed = 0.0;
Double wind_confi = 0.0;
if (averageWindSpeedofRace != null) {
wind_speed = averageWindSpeedofRace.getA();
wind_confi = averageWindSpeedofRace.getB();
}
addNamedElementWithValue(race_node, "average_wind_speed", wind_speed);
addNamedElementWithValue(race_node, "average_wind_speed_confidence", wind_confi);
addNamedElementWithValue(race_node, "wind_strength", wind_strength);
/*
* Legs
*/
int i = 0; // initialize leg index
TrackedLeg previousLeg = null;
final Element legs_node = addNamedElement(race_node, "legs"); // add element that holds all legs for the
// race
for (final TrackedLeg trackedLeg : trackedRace.getTrackedLegs()) {
final Leg leg = trackedLeg.getLeg();
final Element leg_node = addNamedElement(legs_node, "leg"); // add element for single leg
addNamedElementWithValue(leg_node, "leg_number", ++i);
addNamedElementWithValue(leg_node, "mark_from", leg.getFrom().getName());
addNamedElementWithValue(leg_node, "mark_to", leg.getTo().getName());
addNamedElementWithValue(leg_node, "leg_type", (trackedLeg.getLegType(legStarted).toString()));
/*
* Competitors
*/
// LinkedHashMap<Competitor, Integer> ranks = trackedLeg.getRanks(legStarted); // get the ranking
// information for the race
// (at leg start time)
final Element competitor_data_node = addNamedElement(leg_node, "competitor_data"); // add element that
// holds the leg
// summary data for
// each competitor
for (Competitor competitor : leaderboard.getAllCompetitors()) { // Get competitor data
TrackedLegOfCompetitor trackedLegOfCompetitor = trackedLeg.getTrackedLeg(competitor); // Get data
TimePoint compareLegEnd = new MillisecondsTimePoint(0);
// time elapsed / when did the competitor pass the end mark of the leg
MarkPassing mp = trackedRace.getMarkPassing(competitor, leg.getTo());
if (mp != null) {
compareLegEnd = mp.getTimePoint();
} else {
continue;
}
if (trackedLegOfCompetitor == null || compareLegEnd == null) {
continue;
}
long compLegTimeAlt = -1;
try {
compLegTimeAlt = trackedLegOfCompetitor.getTimeInMilliSeconds(compareLegEnd);
} catch (Exception e1) {
// e1.printStackTrace();
// If this happens, the race is probably broken
}
TimePoint compFinishedLeg = compareLegEnd;
// plausibility check
// competitor has finished the leg and the leg end time is not the race start time
if (trackedLegOfCompetitor.hasFinishedLeg(compFinishedLeg) && compareLegEnd.asMillis() != 0) {
// Calculate rank loss/gain
int posGL = 0;
if (previousLeg != null) {
posGL = trackedLegOfCompetitor.getRank(compFinishedLeg)
- previousLeg.getTrackedLeg(competitor).getRank(compFinishedLeg);
}
final Element competitor_node = addNamedElement(competitor_data_node, "competitor");
try {
addNamedElementWithValue(competitor_node, "name", competitor.getName());
addNamedElementWithValue(competitor_node, "nationality", competitor.getTeam()
.getNationality().getThreeLetterIOCAcronym());
addNamedElementWithValue(competitor_node, "sail_id", competitor.getBoat().getSailID());
String sail_id = competitor.getBoat().getSailID();
if (sail_id.matches("^[A-Z]{3}\\s[0-9]*")) {
Pattern regex = Pattern.compile("(^[A-Z]{3})\\s([0-9]*)");
Matcher regexMatcher = regex.matcher(sail_id);
try {
String resultString = regexMatcher.replaceAll("$1$2");
addNamedElementWithValue(competitor_node, "sail_id_formatted", resultString);
} catch (Exception e) {
e.printStackTrace();
}
} else if (sail_id.matches("^[A-Z]{3}\\S[0-9]*")) {
addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
} else if (sail_id.matches("[0-9]*")){
addNamedElementWithValue(competitor_node, "sail_id_formatted", competitor.getTeam().getNationality().getThreeLetterIOCAcronym() + sail_id);
} else {
addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
}
addNamedElementWithValue(competitor_node, "leg_finished_time_ms", compFinishedLeg.asMillis());
addNamedElementWithValue(competitor_node, "time_elapsed_ms", compFinishedLeg.asMillis() - raceStarted.asMillis());
addNamedElementWithValue(competitor_node, "leg_time_ms", compLegTimeAlt);
addNamedElementWithValue(competitor_node, "leg_rank", trackedLegOfCompetitor.getRank(compFinishedLeg));
addNamedElementWithValue(competitor_node, "race_final_rank", trackedRace.getRank(competitor));
//
// addNamedElementWithValue(competitor_node, "race_points", leaderboard.getTotalPoints(competitor, r, MillisecondsTimePoint.now()));
//
addNamedElementWithValue(competitor_node, "rank_gain", posGL * -1); // Ranks Gained/Lost
addNamedElementWithValue(competitor_node, "gap_to_leader_s", trackedLegOfCompetitor.getGapToLeaderInSeconds(compFinishedLeg));
addNamedElementWithValue(competitor_node, "ww_distance_to_leader_m", 0);
// addNamedElementWithValue(competitor_node, "avg_xte", trackedLegOfCompetitor.getAverageCrossTrackError(compFinishedLeg).getMeters());
// addNamedElementWithValue(competitor_node, "avg_vmg_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());//windwardSpeed over ground on leg finished time
addNamedElementWithValue(competitor_node, "avg_speed_og_kn", trackedLegOfCompetitor.getAverageSpeedOverGround(compFinishedLeg).getKnots());
addNamedElementWithValue(competitor_node, "avg_speed_ww_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());// windwardSpeed over
// ground on leg finished
// time
addNamedElementWithValue(competitor_node, "distance_traveled_m", trackedLegOfCompetitor.getDistanceTraveled(compFinishedLeg).getMeters());
addNamedElementWithValue(competitor_node, "number_of_jibes", trackedLegOfCompetitor.getNumberOfJibes(compFinishedLeg));
addNamedElementWithValue(competitor_node, "number_of_tacks", trackedLegOfCompetitor.getNumberOfTacks(compFinishedLeg));
addNamedElementWithValue(competitor_node, "number_of_penalty_circles", trackedLegOfCompetitor.getNumberOfPenaltyCircles(compFinishedLeg));
addNamedElementWithValue(competitor_node, "average_wind_speed", wind_speed);
addNamedElementWithValue(competitor_node, "average_wind_speed_confidence", wind_confi);
// assign the smallest start time for the next leg
minNextLegStart = (minNextLegStart > compFinishedLeg.asMillis() ? compFinishedLeg
.asMillis() : minNextLegStart);
} catch (Exception ex) {
//competitor_data_node.removeContent(competitor_node); // if the competitor dataset is not complete, remove it from the list
// complete, remove it from the list
}
} else {
System.err.print("Competitpr Skipped:" + competitor.getName() + "; Race:" + race.getName()
+ "; Leg+" + ((Integer) i).toString());
}
} // competitor data end
legStarted = new MillisecondsTimePoint(minNextLegStart);
minNextLegStart = Long.MAX_VALUE;
previousLeg = trackedLeg;
// if the leg does not contain any competitor info
if (competitor_data_node.getChildren("competitor").size() == 0) {
legs_node.removeContent(leg_node);
}
} // leg end
// if the race does not contain any leg info
if (legs_node.getChildren("leg").size() == 0) {
races_node.removeContent(race_node);
}
trackedRace.getRace().getBoatClass();
}
}
sendDocument(doc, leaderboard.getName() + ".xml");// output doc to client
// for (final RaceDefinition race : races.values()) { // for each race in the list
// final Element race_node = addNamedElement(races_node, "race"); // add race node for the current race
// addNamedElementWithValue(race_node, "name", race.getName()); // add name node to current race
//
// // skip race if not tracked
// final TrackedRace trackedRace = getTrackedRace(regatta, race);
// if (trackedRace == null || !trackedRace.hasGPSData()) {
// continue;
// }
//
// final TimePoint raceStarted = getTimePoint(trackedRace); // get TimePoint for when the race started
// if (raceStarted == null) {
// continue;
// }
//
// long minNextLegStart = raceStarted.asMillis(); // variable for keeping track of when the first competitor
// // started the next leg
// TimePoint legStarted = new MillisecondsTimePoint(minNextLegStart); // get TimePoint for when the leg started
//
// addNamedElementWithValue(race_node, "start_time_ms", raceStarted.asMillis()); // add the starttime to the
// if (trackedRace.getEndOfRace() != null) {
// addNamedElementWithValue(race_node, "assumed_end_ms", trackedRace.getEndOfRace().asMillis()); // add the assumed enddtime
// } else {
// addNamedElementWithValue(race_node, "assumed_end_ms", 0); // add the assumed enddtime
// }
//
// Calendar cal = Calendar.getInstance();
// cal.setTime(raceStarted.asDate());
// addNamedElementWithValue(race_node, "start_time_year", cal.get(Calendar.YEAR));
// int month = cal.get(Calendar.MONTH) + 1;
// addNamedElementWithValue(race_node, "start_time_month", month);
// addNamedElementWithValue(race_node, "start_time_day", cal.get(Calendar.DAY_OF_MONTH));
// addNamedElementWithValue(race_node, "start_time_hour", cal.get(Calendar.HOUR_OF_DAY));
// addNamedElementWithValue(race_node, "start_time_minute", cal.get(Calendar.MINUTE));
// addNamedElementWithValue(race_node, "start_time_second", cal.get(Calendar.SECOND));
// addNamedElementWithValue(race_node, "start_time_formatted", (cal.get(Calendar.DAY_OF_MONTH) < 10 ? ("0" + cal.get(Calendar.DAY_OF_MONTH)) : cal.get(Calendar.DAY_OF_MONTH))
// + "."
// + (month < 10 ? ("0" + month) : month)
// + "."
// + cal.get(Calendar.YEAR)
// + " - "
// + (cal.get(Calendar.HOUR_OF_DAY) < 10 ? ("0" + cal.get(Calendar.HOUR_OF_DAY)) : cal
// .get(Calendar.HOUR_OF_DAY))
// + ":"
// + (cal.get(Calendar.MINUTE) < 10 ? ("0" + cal.get(Calendar.MINUTE)) : cal
// .get(Calendar.MINUTE))
// + ":"
// + (cal.get(Calendar.SECOND) < 10 ? ("0" + cal.get(Calendar.SECOND)) : cal
// .get(Calendar.SECOND)));
//
// Pair<Double, Double> averageWindSpeedofRace = calculateAverageWindSpeedofRace(trackedRace);
// String wind_strength = "";
// if (averageWindSpeedofRace != null) {
// if (averageWindSpeedofRace.getA() < 4) {
// wind_strength = "Very light";
// } else if (averageWindSpeedofRace.getA() >= 4 && averageWindSpeedofRace.getA() < 8) {
// wind_strength = "Light";
// } else if (averageWindSpeedofRace.getA() >= 8 && averageWindSpeedofRace.getA() < 14) {
// wind_strength = "Medium";
// } else if (averageWindSpeedofRace.getA() >= 14 && averageWindSpeedofRace.getA() < 20) {
// wind_strength = "Strong";
// } else if (averageWindSpeedofRace.getA() >= 20) {
// wind_strength = "Very strong";
// }
// }
//
// Double wind_speed = 0.0;
// Double wind_confi = 0.0;
//
// if (averageWindSpeedofRace != null) {
// wind_speed = averageWindSpeedofRace.getA();
// wind_confi = averageWindSpeedofRace.getB();
// }
//
// addNamedElementWithValue(race_node, "average_wind_speed", wind_speed);
// addNamedElementWithValue(race_node, "average_wind_speed_confidence", wind_confi);
// addNamedElementWithValue(race_node, "wind_strength", wind_strength);
//
// /*
// * Legs
// */
// int i = 0; // initialize leg index
// TrackedLeg previousLeg = null;
//
// final Element legs_node = addNamedElement(race_node, "legs"); // add element that holds all legs for the
// // race
//
// for (final TrackedLeg trackedLeg : trackedRace.getTrackedLegs()) {
// final Leg leg = trackedLeg.getLeg();
// final Element leg_node = addNamedElement(legs_node, "leg"); // add element for single leg
//
// addNamedElementWithValue(leg_node, "leg_number", ++i);
// addNamedElementWithValue(leg_node, "mark_from", leg.getFrom().getName());
// addNamedElementWithValue(leg_node, "mark_to", leg.getTo().getName());
// addNamedElementWithValue(leg_node, "leg_type", (trackedLeg.getLegType(legStarted).toString()));
//
// /*
// * Competitors
// */
// LinkedHashMap<Competitor, Integer> ranks = trackedLeg.getRanks(legStarted); // get the ranking
// // information for the race
// // (at leg start time)
// final Element competitor_data_node = addNamedElement(leg_node, "competitor_data"); // add element that
// // holds the leg
// // summary data for
// // each competitor
//
// for (final Competitor competitor : ranks.keySet()) { // Get competitor data
// TrackedLegOfCompetitor trackedLegOfCompetitor = trackedLeg.getTrackedLeg(competitor); // Get data
// TimePoint compareLegEnd = new MillisecondsTimePoint(0);
// // time elapsed / when did the competitor pass the end mark of the leg
// MarkPassing mp = trackedRace.getMarkPassing(competitor, leg.getTo());
// if (mp != null) {
// compareLegEnd = mp.getTimePoint();
// }
// final long compLegTimeAlt = trackedLegOfCompetitor.getTimeInMilliSeconds(compareLegEnd);
// final TimePoint compFinishedLeg = compareLegEnd;
//
// // plausibility check
// // competitor has finished the leg and the leg end time is not the race start time
// if (trackedLegOfCompetitor.hasFinishedLeg(compFinishedLeg) && compareLegEnd.asMillis() != 0) {
// // Calculate rank loss/gain
// int posGL = 0;
// if (previousLeg != null) {
// posGL = trackedLegOfCompetitor.getRank(compFinishedLeg)
// - previousLeg.getTrackedLeg(competitor).getRank(compFinishedLeg);
// }
//
// final Element competitor_node = addNamedElement(competitor_data_node, "competitor");
// try {
// addNamedElementWithValue(competitor_node, "name", competitor.getName());
// addNamedElementWithValue(competitor_node, "nationality", competitor.getTeam()
// .getNationality().getThreeLetterIOCAcronym());
// addNamedElementWithValue(competitor_node, "sail_id", competitor.getBoat().getSailID());
// String sail_id = competitor.getBoat().getSailID();
// if (sail_id.matches("^[A-Z]{3}\\s[0-9]*")) {
//
// Pattern regex = Pattern.compile("(^[A-Z]{3})\\s([0-9]*)");
// Matcher regexMatcher = regex.matcher(sail_id);
// try {
// String resultString = regexMatcher.replaceAll("$1$2");
// addNamedElementWithValue(competitor_node, "sail_id_formatted", resultString);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
//
// } else if (sail_id.matches("^[A-Z]{3}\\S[0-9]*")) {
// addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
// } else if (sail_id.matches("[0-9]*")){
// addNamedElementWithValue(competitor_node, "sail_id_formatted", competitor.getTeam().getNationality().getThreeLetterIOCAcronym() + sail_id);
// } else {
// addNamedElementWithValue(competitor_node, "sail_id_formatted", sail_id);
// }
// addNamedElementWithValue(competitor_node, "leg_finished_time_ms", compFinishedLeg.asMillis());
// addNamedElementWithValue(competitor_node, "time_elapsed_ms", compFinishedLeg.asMillis() - raceStarted.asMillis());
// addNamedElementWithValue(competitor_node, "leg_time_ms", compLegTimeAlt);
// addNamedElementWithValue(competitor_node, "leg_rank", trackedLegOfCompetitor.getRank(compFinishedLeg));
// addNamedElementWithValue(competitor_node, "race_final_rank", trackedRace.getRank(competitor));
// addNamedElementWithValue(competitor_node, "rank_gain", posGL * -1); // Ranks Gained/Lost
// addNamedElementWithValue(competitor_node, "gap_to_leader_s", trackedLegOfCompetitor.getGapToLeaderInSeconds(compFinishedLeg));
// addNamedElementWithValue(competitor_node, "ww_distance_to_leader_m", 0);
//// addNamedElementWithValue(competitor_node, "avg_xte", trackedLegOfCompetitor.getAverageCrossTrackError(compFinishedLeg).getMeters());
//// addNamedElementWithValue(competitor_node, "avg_vmg_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());//windwardSpeed over ground on leg finished time
// addNamedElementWithValue(competitor_node, "avg_speed_og_kn", trackedLegOfCompetitor.getAverageSpeedOverGround(compFinishedLeg).getKnots());
// addNamedElementWithValue(competitor_node, "avg_speed_ww_kn", trackedLegOfCompetitor.getAverageVelocityMadeGood(compFinishedLeg).getKnots());// windwardSpeed over
// // ground on leg finished
// // time
// addNamedElementWithValue(competitor_node, "distance_traveled_m", trackedLegOfCompetitor.getDistanceTraveled(compFinishedLeg).getMeters());
// addNamedElementWithValue(competitor_node, "number_of_jibes", trackedLegOfCompetitor.getNumberOfJibes(compFinishedLeg));
// addNamedElementWithValue(competitor_node, "number_of_tacks", trackedLegOfCompetitor.getNumberOfTacks(compFinishedLeg));
// addNamedElementWithValue(competitor_node, "number_of_penalty_circles", trackedLegOfCompetitor.getNumberOfPenaltyCircles(compFinishedLeg));
//
// addNamedElementWithValue(competitor_node, "average_wind_speed", wind_speed);
// addNamedElementWithValue(competitor_node, "average_wind_speed_confidence", wind_confi);
//
//// Waypoint finish = trackedRace.getRace().getCourse().getLastWaypoint();
////
//// Iterable<MarkPassing> markpassings = trackedRace.getMarkPassingsInOrder(finish);
//// Iterator<MarkPassing> iter = markpassings.iterator();
//// MarkPassing firstMarkPassing = null;
//// if (iter.hasNext()) {
//// firstMarkPassing = iter.next();
//// }
////
////
////// Map<Waypoint, NavigableSet<MarkPassing>> markPassingsForWaypoint = new HashMap<Waypoint, NavigableSet<MarkPassing>>();
////// for (Waypoint waypoint : trackedRace.getRace().getCourse().getWaypoints()) {
////// markPassingsForWaypoint.put(waypoint, new ConcurrentSkipListSet<MarkPassing>(
////// MarkPassingByTimeComparator.INSTANCE));
////// }
//////
////// NavigableSet<MarkPassing> markPassingsInOrder = markPassingsForWaypoint.get(finish);
////// MarkPassing firstMarkPassing = null;
////// synchronized (markPassingsInOrder) {
////// if (!markPassingsInOrder.isEmpty()) {
////// firstMarkPassing = markPassingsInOrder.first();
////// }
////// }
//// TimePoint timeOfFirstMarkPassing = null;
//// if (firstMarkPassing != null) {
//// timeOfFirstMarkPassing = firstMarkPassing.getTimePoint();
//// }
////
//// trackedRace.getWindwardDistanceToOverallLeader(competitor, timeOfFirstMarkPassing);
//
//
//
//
// // assign the smallest start time for the next leg
// minNextLegStart = (minNextLegStart > compFinishedLeg.asMillis() ? compFinishedLeg
// .asMillis() : minNextLegStart);
// } catch (Exception ex) {
// //competitor_data_node.removeContent(competitor_node); // if the competitor dataset is not complete, remove it from the list
// // complete, remove it from the list
// }
// } else {
// System.err.print("Competitpr Skipped:" + competitor.getName() + "; Race:" + race.getName()
// + "; Leg+" + ((Integer) i).toString());
// }
//
// } // competitor data end
// legStarted = new MillisecondsTimePoint(minNextLegStart);
// minNextLegStart = Long.MAX_VALUE;
// previousLeg = trackedLeg;
//
// // if the leg does not contain any competitor info
// if (competitor_data_node.getChildren("competitor").size() == 0) {
// legs_node.removeContent(leg_node);
// }
//
// } // leg end
// // if the race does not contain any leg info
// if (legs_node.getChildren("leg").size() == 0) {
// races_node.removeContent(race_node);
// }
// } // regatta end
// sendDocument(doc, regatta.getName() + ".xml");// output doc to client
} // function end
private Pair<Double, Double> calculateAverageWindSpeedofRace(TrackedRace trackedRace) {
Pair<Double, Double> result = null;
if (trackedRace.getEndOfRace() != null) {
TimePoint fromTimePoint = trackedRace.getStartOfRace();
TimePoint toTimePoint = trackedRace.getEndOfRace();
long resolutionInMilliseconds = 60 * 1000 * 5; // 5 min
List<WindSource> windSourcesToDeliver = new ArrayList<WindSource>();
WindSourceImpl windSource = new WindSourceImpl(WindSourceType.COMBINED);
windSourcesToDeliver.add(windSource);
double sumWindSpeed = 0.0;
double sumWindSpeedConfidence = 0.0;
int speedCounter = 0;
int numberOfFixes = (int) ((toTimePoint.asMillis() - fromTimePoint.asMillis()) / resolutionInMilliseconds);
WindTrack windTrack = trackedRace.getOrCreateWindTrack(windSource);
TimePoint timePoint = fromTimePoint;
for (int i = 0; i < numberOfFixes && toTimePoint != null && timePoint.compareTo(toTimePoint) < 0; i++) {
WindWithConfidence<Pair<Position, TimePoint>> averagedWindWithConfidence = windTrack
.getAveragedWindWithConfidence(null, timePoint);
if (averagedWindWithConfidence != null) {
double windSpeedinKnots = averagedWindWithConfidence.getObject().getKnots();
double confidence = averagedWindWithConfidence.getConfidence();
sumWindSpeed += windSpeedinKnots;
sumWindSpeedConfidence += confidence;
speedCounter++;
}
timePoint = new MillisecondsTimePoint(timePoint.asMillis() + resolutionInMilliseconds);
}
if (speedCounter > 0) {
double averageWindSpeed = sumWindSpeed / speedCounter;
double averageWindSpeedConfidence = sumWindSpeedConfidence / speedCounter;
result = new Pair<Double, Double>(averageWindSpeed, averageWindSpeedConfidence);
}
} else {
result = new Pair<Double, Double>(0.0, 0.0);
}
return result;
}
private void addNamedElementWithValue(Element parent, String newChildName, Integer i) {
if (i == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, i.toString());
}
}
private void addNamedElementWithValue(Element parent, String newChildName, Double dbl) {
if (dbl == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, dbl.toString());
}
}
private void addNamedElementWithValue(Element parent, String newChildName, Long l) {
if (l == null) {
addNamedElementWithValue(parent, newChildName, "0");
} else {
addNamedElementWithValue(parent, newChildName, l.toString());
}
}
private Element addNamedElement(Document doc, String newChildName) {
final Element newChild = new Element(newChildName);
doc.addContent(newChild);
return newChild;
}
private Element addNamedElementWithValue(Element parent, String newChildName, String value) {
final Element newChild = new Element(newChildName);
newChild.addContent(value);
parent.addContent(newChild);
return newChild;
}
private Element addNamedElement(Element parent, String newChildName) {
final Element newChild = new Element(newChildName);
parent.addContent(newChild);
return newChild;
}
}
@@ -1,47 +0,0 @@
package com.sap.sailing.xcelsiusadapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Document;
import com.sap.sailing.domain.base.*;
import com.sap.sailing.server.RacingEventService;
public class RegattaList extends Action {
public RegattaList(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
}
public void perform() throws Exception {
final Document table = getTable("data");
for(Regatta regatta : getRegattas().values()){
if(regatta == null){
continue;
}
addRow();
addColumn(regatta.getName());
}
say(table);// output doc to client
} // function end
}
@@ -0,0 +1,31 @@
package com.sap.sailing.xcelsiusadapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.Document;
import com.sap.sailing.domain.base.*;
import com.sap.sailing.server.RacingEventService;
public class RegattaListAction extends HttpAction {
public RegattaListAction(HttpServletRequest req, HttpServletResponse res, RacingEventService service, int maxRows) {
super(req, res, service, maxRows);
}
public void perform() throws Exception {
final Document table = getTable("data");
for (Regatta regatta : getRegattas().values()) {
if (regatta == null) {
continue;
}
addRow();
addColumn(regatta.getName());
}
say(table);
}
}
@@ -1,662 +0,0 @@
package com.sap.sailing.xcelsiusadapter;
import java.util.ArrayList;
import java.util.List;
/**
* Some String Utilities.
*/
public class StringUtility {
/**
* Return a hashcode as a positive Integer for a String.<p>
*
* In contrast to .hashCode(), this function returns a positive
* Integer. This is helpful to use Strings as a unique key in
* places (e.g. JavaScript) where you would be bothered by
* special characters in the String.
*
* @param sIn The String to get a hashcode for.
* @return The hashcode as a positive Integer in a String.
*/
public static String hashCode(String sIn) {
if (sIn == null) {
return null;
}
return "" + Math.abs(sIn.hashCode());
}
/**
* Escape quotes and linebreaks in a String.<p>
*
* @param sIn the String that has to be escaped
* @return The escaped String
*/
public static String escapeQuotes(String sIn) {
if (sIn == null) {
return "";
}
int len = sIn.length();
String res = "";
char c;
for (int i = 0; i < len; i++) {
c = sIn.charAt(i);
switch (c) {
case '\n':
res += "\\n";
break;
case '\r':
break;
case '\\':
res += "\\\\";
break;
case '"':
res += "\\" + c;
break;
case '\'':
res += "\\" + c;
break;
default:
res += c;
}
}
return res;
}
/**
* Returns an array of string related to the key value string.<p>
*
* If there is nothing left or right of the separator, that position
* is returned as an empty string:<p>
*
* <ul>
* <li><code>a/b/c</code> returns "a", "b", "c". </li>
* <li><code>/a/b/c</code> returns "", "a", "b", "c". </li>
* <li><code>a/b/c/</code> returns "a", "b", "c", "".</li>
* <li><code>/a/b/c/</code> returns "", "a", "b", "c", "".</li>
* <ul>
* <p>
* If you do not want empty Strings, you can operate
* {@link #condense(String[])} on the return value.
*
* @param strParamVal the String that has to be splitted
* @param strSep the Separator at which the String shall be splitted
* @return Array of Strings with the Substrings.
*/
public static String[] split(String strParamVal, String strSep) {
if ((strSep == null) || "".equals(strSep)) {
return new String[] { strParamVal };
}
String[] strRetList = new String[0];
/*
* This has bugged me a lot: We do not want to
* return anything if we have an empty String.
* Previously, as we did not find the separator,
* the recursive algorithm returned a String
* array of length one with the string itself.
* If then we checked for length, we were
* like thinking there was a length, while the
* String in reality had been empty.
*/
if ((strParamVal == null) || (strParamVal.length() == 0)) {
return strRetList;
}
final int separatorPosition = strParamVal.indexOf(strSep);
final int separatorLength = strSep.length();
/*
* If we no longer have the separator,
* we do not need to split the String
* again.
*/
if (separatorPosition < 0) {
strRetList = new String[1];
strRetList[0] = strParamVal;
return strRetList;
}
String lowValue = "";
String highValue = "";
lowValue = strParamVal.substring(0, separatorPosition);
if (strParamVal.length() >= (separatorPosition + separatorLength)) {
highValue = strParamVal.substring((strParamVal.equals(strSep)) ? 0 : (separatorPosition + separatorLength));
}
final String[] recursion = ("".equals(highValue) || strParamVal.equals(strSep)) ? new String[] { "" } : split(highValue, strSep);
final int recursionLength = recursion.length;
strRetList = new String[recursionLength + 1];
strRetList[0] = lowValue;
for (int i = 0; i < recursionLength; i++) {
strRetList[i + 1] = recursion[i];
}
/* I rewrote this completely passing to a recursive
* way of doing things. This cleans up considerably
* the code. For legacy, here is the old way:
String[] strRetList = new String[0];
String strVar = "";
int iPos = 0;
int i;
if (strParamVal != null) { strVar = strParamVal; }
if (strVar.length() > 0) {
//-- Get the Number of items in strParamVal value
int iCpt = 0;
while (iPos >= 0) {
iPos = strVar.indexOf(strSep);
if (iPos >= 0) {
strVar = strVar.substring(iPos + 1);
iCpt = iCpt + 1;
} else {
if (strVar.length() >= 0) { iCpt = iCpt + 1; }
}
}
//-- Initialize the size of the list
strRetList = new String[iCpt];
//-- Get the list of values
strVar = strParamVal;
i = 0;
iPos = 0;
while (iPos >= 0) {
iPos = strVar.indexOf(strSep);
if (iPos >= 0) {
strRetList[i++] = strVar.substring(0, iPos);
strVar = strVar.substring(iPos + 1);
} else {
if (strVar.length() > 0) { strRetList[i++] = strVar; }
}
}
}
*/
return strRetList;
}
/**
* Returns an array of string related to the key value string.<p>
* An array of string is passed; every single string is split, and
* an array containing all substrings of all strings is returned.
*
* @param strParamVals the String array containing Strings that have to be splitted
* @param strSep the Separator at which the String shall be splitted
* @return Array of Strings with the Substrings.
*/
public static String[] split(String[] strParamVals, String strSep) {
int count = 0;
if (strParamVals == null) {
return new String[0];
}
for (int i = 0; i < strParamVals.length; i++) {
String[] s = split(strParamVals[i], strSep);
count += s.length;
}
String[] strRetList = new String[count];
count = 0;
for (int i = 0; i < strParamVals.length; i++) {
String[] s = split(strParamVals[i], strSep);
for (int j = 0; j < s.length; j++) {
strRetList[count++] = s[j];
}
}
return strRetList;
}
/**
* Condense a String array by removing all empty Strings.
*
* @param strParamValues The String Array.
* @return A String Array in the same order, but without
* empty Strings.
*/
public static String[] condense(String[] strParamValues) {
return condense(strParamValues, 0);
}
/**
* Condense a String array by removing all empty Strings
* except at the beginning the number of strings that can
* be ignored even if they are empty.
*
* @param strParamValues The String Array.
* @param ignore the number of possible empty strings that
* may pass through at the beginning.
* @return A String Array in the same order, but without
* empty Strings.
*/
public static String[] condense(String[] strParamValues, int ignore) {
final List<String> theValues = new ArrayList<String>();
for (int i = 0; i < strParamValues.length; i++) {
if ((ignore < i) || !"".equals(strParamValues[i])) {
theValues.add(strParamValues[i]);
}
}
final String[] result = new String[theValues.size()];
int i = 0;
for (final String theValue : theValues) {
result[i++] = theValue;
}
return result;
}
/**
* Converts an array to a string.<p>
*
* Only Strings that are not empty are put into the concatenated string.
*
* @param strParamVals the String Array that has to be joined
* @param strSep the Separator that has to be put between the Strings
* @return The concatenated String
*/
public static String join(String[] strParamVals, String strSep) {
String strRet = "";
int numValues = 0;
if (null != strParamVals) {
for (int i = 0; i < strParamVals.length; i++) {
if ((strParamVals[i] != null) && (strParamVals[i].length() > 0)) {
if (numValues == 0) {
strRet = strParamVals[i];
} else {
strRet += strSep + strParamVals[i];
}
numValues++;
}
}
}
return strRet;
}
/**
* Removes blank spaces between values and separator.<p>
*
* @param strPromptValue The String to be trimmed around separators
* @param strSep the Separator the String has to be trimmed around
* @return The updated String
*/
public static String trimPrompt(String strPromptValue, String strSep) {
if (null != strPromptValue) {
String[] arrPromptValues = split(strPromptValue, strSep);
for (int j = 0; j < arrPromptValues.length; j++) {
if (arrPromptValues[j] != null) {
arrPromptValues[j] = arrPromptValues[j].trim();
}
}
strPromptValue = join(arrPromptValues, strSep);
}
return strPromptValue;
}
/**
* Replaces String into a text.<p>
*
* @param strText The Text in which the substitution shall be done
* @param strOldString The String that has to be replaced
* @param strNewString The replacement String
* @param blnAll true, if all matches shall be replaced, false for only first match.
* @return The updated String
*/
public static String replace(String strText, String strOldString, String strNewString, boolean blnAll) {
if (null != strText) {
int iLength = strOldString.length();
int iPos = 0;
while (iPos >= 0) {
iPos = strText.indexOf(strOldString);
if (iPos >= 0) {
String strLeft = strText.substring(0, iPos);
String strRight = strText.substring(iPos + iLength);
strText = strLeft + strNewString + strRight;
iPos += iLength;
if (!blnAll) {
break;
}
}
}
}
return strText;
}
/**
* Strip leading String from a String.<p>
*
* Example: From <code>/BISDK</code>, strip
* the <code>/</code>, so that you get <code>BISDK</code>.<p>
*
* If there are multiple occurrences at the beginning,
* they are all suppressed.
*
* @param strText The String to strip from.
* @param toStrip The Fraction to suppress.
* @return String where the leading part was eliminated.
*/
public static String stripLeading(String strText, String toStrip) {
String stripped = strText;
while (stripped.startsWith(toStrip)) {
stripped = stripped.substring(toStrip.length());
}
return stripped;
}
/**
* Strip trailing String from a String.<p>
*
* Example: From <code>BISDK/</code>, strip
* the <code>/</code>, so that you get <code>BISDK</code>.<p>
*
* If there are multiple occurrences at the beginning,
* they are all suppressed.
*
* @param strText The String to strip from.
* @param toStrip The Fraction to suppress.
* @return String where the trailing part was eliminated.
*/
public static String stripTrailing(String strText, String toStrip) {
String stripped = strText;
while (stripped.endsWith(toStrip)) {
stripped = stripped.substring(0, stripped.length() - toStrip.length());
}
return stripped;
}
/**
* Strip leading and trailing String from a String.<p>
*
* Example: From <code>/BISDK/</code>, strip
* the <code>/</code>, so that you get <code>BISDK</code>.<p>
*
* If there are multiple occurrences at the beginning or end,
* they are all suppressed.
*
* @param strText The String to strip from.
* @param toStrip The Fraction to suppress.
* @return String where the leading and trailing parts were eliminated.
*/
public static String stripBoth(String strText, String toStrip) {
return StringUtility.stripLeading(StringUtility.stripTrailing(strText, toStrip), toStrip);
}
/**
* Parse year, month, day out of a date string.<p>
*
* @param strDate The Date String that is to be parsed, e.g. "2004-12-30"
* @param strFormat The Date Format pattern, e.g. "y-mm-dd". The following
* pattern entries are possible: "y" for 4-digit year, "yy" for two-digit year;
* "mm" for the month number, zero-padded;
* "dd" for the day number, zero-padded.
* @return String Array with the following entries:
* <ul>
* <li>[ 0]=Year</li>
* <li>[ 1]=Month</li>
* <li>[ 2]=Day</li>
* </ul>
*/
public static String[] parseDate(String strDate, String strFormat) {
/* get the year positions */
int yrStart = strFormat.indexOf("y");
int yrEnd = strFormat.lastIndexOf("y");
int yrComp = 0;
if ((yrStart < 0) || (yrEnd < 0)) {
return new String[0];
}
if (yrStart == yrEnd) {
yrComp = 3;
}
yrEnd += yrComp + 1;
/* get the month positions */
int moStart = strFormat.indexOf("m");
int moEnd = strFormat.lastIndexOf("m");
if ((moStart < 0) || (moEnd < 0)) {
return new String[0];
}
if (moStart > yrStart) {
moStart += yrComp;
moEnd += yrComp + 1;
}
/* get the day positions */
int dyStart = strFormat.indexOf("d");
int dyEnd = strFormat.lastIndexOf("d");
if ((dyStart < 0) || (dyEnd < 0)) {
return new String[0];
}
if (dyStart > yrStart) {
dyStart += yrComp;
dyEnd += yrComp + 1;
}
String[] ret = new String[3];
ret[0] = strDate.substring(yrStart, yrEnd);
ret[1] = strDate.substring(moStart, moEnd);
ret[2] = strDate.substring(dyStart, dyEnd);
return ret;
}
/**
* Convert a String into an Integer and return 0 if this is not possible.<p>
*
* @param strString The String that has to be converted
* @return The Integer Value
*/
public static int StringToInteger(String strString) {
try {
return Integer.parseInt(strString);
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Convert a String into an Integer and return a default value if this not possible.<p>
*
* @param strString The String that has to be converted
* @param intDefault The default value that shall be returned on error
* @return The Integer Value
*/
public static int StringToInteger(String strString, int intDefault) {
try {
return Integer.parseInt(strString);
} catch (NumberFormatException e) {
return intDefault;
}
}
/**
* Return a non null value for the given string.<p>
*
* @param strString The String that has to be checked against null
* @param strDefaultValue The default value in case the String is null
* @return The checked String.
*/
public static String getNonNullValue(String strString, String strDefaultValue) {
if (strString == null) {
strString = strDefaultValue;
} else if ("null".equals(strString)) {
strString = strDefaultValue;
}
return strString;
}
/**
* Return a non null value for the given string,
* considering that default value is an empty string.<p>
*
* @param strString The String that has to be checked against null
* @return The checked String.
*/
public static String getNonNullValue(String strString) {
return getNonNullValue(strString, "");
}
/**
* Return an array of non null values for the given string array.<p>
*
* @param strString The String array that has to be checked against null
* @return The checked String array.
*/
public static String[] getNonNullValues(String[] strString) {
if (strString == null) {
strString = new String[0];
}
return strString;
}
/**
* Get the name or the value of a parameter. The parameter may look like:
* <p>
* <xmp>
* aname=bvalue
* -x=y
* --parameter=value
* </xmp>
* <p>
* @param parameter A String as shown in the above examples.
* @param name true if the name is required, false if the value is required.
* @param casesensitive false if the parameters are to be converted to all upper case, else true.
* @return Name or value, depending on the name parameter; null if an error occurred.
*/
public static String getParameter(String parameter, boolean name, boolean casesensitive) {
if (parameter == null) {
return null;
}
String[] parametertokens = split(parameter, "=");
if ((parametertokens == null) || ((parametertokens.length < 1) && name) || ((parametertokens.length < 2) && !name)) {
return null;
}
if (name) {
String parametername = parametertokens[0];
while ("-".equals(parametername.substring(0, 1))) {
parametername = parametername.substring(1);
}
if (casesensitive) {
return parametername;
} else {
return parametername.toUpperCase();
}
}
return parametertokens[1];
}
/**
* URLEncode a String.
*
* This is a proxy to java.net.URLEncoder.encode(), as the
* one parameter version is deprecated and the two parameter
* version throws an UnsupportedEncodingException which we
* normally never run into.
*
* @param s The String to encode.
* @return The encoded String.
*/
public static String URLEncode(String s) {
// /*
// * JDK 1.3.1
// */
// return java.net.URLEncoder.encode(s);
/*
* JDK 1.4.2
*/
try {
return java.net.URLEncoder.encode(s, "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return s;
}
}
/**
* URLDecode a String.
*
* This is a proxy to java.net.URLDecoder.decode(), as the
* one parameter version is deprecated and the two parameter
* version throws an UnsupportedEncodingException which we
* normally never run into.
*
* @param s The String to decode.
* @return The decoded String.
*/
public static String URLDecode(String s) {
// /*
// * JDK 1.3.1
// */
// return java.net.URLDecoder.decode(s);
/*
* JDK 1.4.2
*/
try {
return java.net.URLDecoder.decode(s, "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return s;
}
}
}
@@ -8,10 +8,10 @@ import javax.servlet.http.HttpServletResponse;
import com.sap.sailing.server.gateway.SailingServerHttpServlet;
public class XcelsiusApp extends SailingServerHttpServlet {
public class XcelsiusServlet extends SailingServerHttpServlet {
private static final long serialVersionUID = -6849138354941569249L;
public XcelsiusApp() {
public XcelsiusServlet() {
}
@Override
@@ -30,38 +30,38 @@ public class XcelsiusApp extends SailingServerHttpServlet {
// ignore and leave at -1
}
if ("getRankPerLeg".equals(action)) {
final RankPerLeg a = new RankPerLeg(req, res, getService(), maxRows);
final RankPerLegAction a = new RankPerLegAction(req, res, getService(), maxRows);
a.perform();
return;
} else if ("getRankPerLeg2".equals(action)) {
new RankPerLeg2(req, res, getService(), maxRows).perform();
new RankPerLeg2Action(req, res, getService(), maxRows).perform();
return;
} else if ("gpsPerRace".equals(action)) {
final GPSPerRace a = new GPSPerRace(req, res, getService(), maxRows);
final GPSPerRaceAction a = new GPSPerRaceAction(req, res, getService(), maxRows);
a.perform();
return;
} else if ("listEvents".equals(action)) {
final ListEvents a = new ListEvents(req, res, getService(), maxRows);
final ListEventsAction a = new ListEventsAction(req, res, getService(), maxRows);
a.perform();
return;
} else if ("getRankPerRace".equals(action)) {
final RankPerRace a = new RankPerRace(req, res, getService(), maxRows);
final RankPerRaceAction a = new RankPerRaceAction(req, res, getService(), maxRows);
a.perform();
return;
} else if ("getRegattaDataPerLeg".equals(action)) {
final RegattaDataPerLeg a = new RegattaDataPerLeg(req, res, getService(), maxRows);
final RegattaDataPerLegAction a = new RegattaDataPerLegAction(req, res, getService(), maxRows);
a.perform();
return;
}else if ("getRegattaList".equals(action)) {
final RegattaList a = new RegattaList(req, res, getService(), maxRows);
final RegattaListAction a = new RegattaListAction(req, res, getService(), maxRows);
a.perform();
return;
}else {
}
Action.say("Unknown action", res);
HttpAction.say("Unknown action", res);
return;
}
Action.say("Please use the action= parameter to specify an action.", res);
HttpAction.say("Please use the action= parameter to specify an action.", res);
return;
} catch (Exception e) {
throw (new ServletException(e));