mirror of
https://github.com/eclipse-sailing-analytics/sailing-analytics.git
synced 2026-11-16 07:10:48 +00:00
Merge remote-tracking branch 'origin/bug5170'
This commit is contained in:
commit
8d52d71216
26 files changed
+993
-479
No files matched your search
+22
-7
@@ -5,6 +5,7 @@ import java.util.Map;
|
||||
|
||||
import com.sap.sailing.domain.common.impl.KnotSpeedImpl;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
@@ -24,10 +25,9 @@ import com.sap.sse.common.impl.DegreeBearingImpl;
|
||||
* {@link RankingMetric}.
|
||||
* <p>
|
||||
*
|
||||
* The {@link WithID} interface is to be implemented such that a {@link String} is produced as the ID that contains the
|
||||
* concatenation (without intermediate white space) of the {@code NatAuth}, the {@code CertNo} and the {@code BIN}
|
||||
* fields, as provided as single fields in the JSON representation, and as provided in the concatenated form in the
|
||||
* {@code NATCERTN.FILE_ID} column in the RMS format.
|
||||
* The {@link WithID} interface is to be implemented based on the {@link #getReferenceNumber()} which is unique across the
|
||||
* ORC world-wide certificate database. Note that the {@link #getBoatKey()} consisting of the {@link #getFileId()} and the
|
||||
* {@link #getIssuingCountry()} field values is a unique key for the boat to which the certificate belongs.
|
||||
* <p>
|
||||
*
|
||||
* The certificate contains time allowances (or, conversely, speed predictions) for a combination of true wind speeds
|
||||
@@ -64,13 +64,28 @@ public interface ORCCertificate extends WithID, Serializable {
|
||||
Bearing[] ALLOWANCES_TRUE_WIND_ANGLES = { new DegreeBearingImpl(52), new DegreeBearingImpl(60),
|
||||
new DegreeBearingImpl(75), new DegreeBearingImpl(90), new DegreeBearingImpl(110),
|
||||
new DegreeBearingImpl(120), new DegreeBearingImpl(135), new DegreeBearingImpl(150) };
|
||||
|
||||
/**
|
||||
* As the ID of an ORC certificate we use the concatenation (without intermediate white space) of the
|
||||
* {@code NatAuth}, the {@code CertNo} and the {@code BIN} fields, as provided as single fields in the JSON
|
||||
* representation
|
||||
* We use the {@link #getReferenceNumber() reference number ("RefNo")} as the ID of a certificate document.
|
||||
* It is unique for all of ORC's certificates issued world-wide.
|
||||
*/
|
||||
@Override
|
||||
String getId();
|
||||
|
||||
String getReferenceNumber();
|
||||
|
||||
/**
|
||||
* Technically, at ORC a certificate's boat is identified by a "file ID" as returned by this method, together
|
||||
* with the {@link #getIssuingCountry() issuing country} which together makes this a unique boat key. For each
|
||||
* such boat key there is at most one valid certificate at a time.
|
||||
*/
|
||||
String getFileId();
|
||||
|
||||
/**
|
||||
* The country whose authority issued this certificate. Together with the {@link #getFileId() file ID} this makes for a
|
||||
* unique key of the boat to which this certifiate belongs.
|
||||
*/
|
||||
CountryCode getIssuingCountry();
|
||||
|
||||
/**
|
||||
* Returns the sailnumber of the {@link Competitor} which this certificate belongs to.
|
||||
|
||||
+39
-15
@@ -6,6 +6,7 @@ import java.util.Map;
|
||||
import com.sap.sailing.domain.common.impl.NauticalMileDistance;
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
@@ -24,7 +25,7 @@ import com.sap.sse.common.Util;
|
||||
public class ORCCertificateImpl implements ORCCertificate {
|
||||
private static final long serialVersionUID = 8725162998514202782L;
|
||||
|
||||
private final String idConsistingOfNatAuthCertNoAndBIN;
|
||||
private final String referenceNumber;
|
||||
|
||||
public final static Distance NAUTICAL_MILE = new NauticalMileDistance(1);
|
||||
|
||||
@@ -35,7 +36,9 @@ public class ORCCertificateImpl implements ORCCertificate {
|
||||
private final Duration gph;
|
||||
private final Double cdl;
|
||||
private final TimePoint issueDate;
|
||||
|
||||
private final String fileId;
|
||||
private final CountryCode issuingCountry;
|
||||
|
||||
/**
|
||||
* The "core" of the certificate for performance curve scoring; the values in the map tell how fast the boat
|
||||
* described by this certificate is expected to sail for the true wind speed (TWS) provided by the key, and the true
|
||||
@@ -111,11 +114,13 @@ public class ORCCertificateImpl implements ORCCertificate {
|
||||
* {@link ORCCertificate#ALLOWANCES_TRUE_WIND_ANGLES}.
|
||||
*/
|
||||
public ORCCertificateImpl(Speed[] allowancesTrueWindSpeeds, Bearing[] allowancesTrueWindAngles,
|
||||
String idConsistingOfNatAuthCertNoAndBIN, String sailnumber, String boatName, String boatClassName,
|
||||
Distance length, Duration gph, Double cdl, TimePoint issueDate,
|
||||
String referenceNumber, String fileId, String sailnumber, String boatName,
|
||||
String boatClassName, Distance length, Duration gph, Double cdl,
|
||||
TimePoint issueDate, CountryCode issuingCountry,
|
||||
Map<Speed, Map<Bearing, Speed>> velocityPredictionsPerTrueWindSpeedAndAngle, Map<Speed, Bearing> beatAngles,
|
||||
Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed, Map<Speed, Duration> beatAllowancePerTrueWindSpeed,
|
||||
Map<Speed, Bearing> runAngles, Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed,
|
||||
Map<Speed, Bearing> runAngles,
|
||||
Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed,
|
||||
Map<Speed, Duration> runAllowancePerTrueWindSpeed,
|
||||
Map<Speed, Speed> windwardLeewardSpeedPredictionsPerTrueWindSpeed,
|
||||
Map<Speed, Speed> longDistanceSpeedPredictionsPerTrueWindSpeed,
|
||||
@@ -123,7 +128,9 @@ public class ORCCertificateImpl implements ORCCertificate {
|
||||
Map<Speed, Speed> nonSpinnakerSpeedPredictionsPerTrueWindSpeed) {
|
||||
this.allowancesTrueWindAngles = allowancesTrueWindAngles;
|
||||
this.allowancesTrueWindSpeeds = allowancesTrueWindSpeeds;
|
||||
this.idConsistingOfNatAuthCertNoAndBIN = idConsistingOfNatAuthCertNoAndBIN;
|
||||
this.referenceNumber = referenceNumber;
|
||||
this.fileId = fileId;
|
||||
this.issuingCountry = issuingCountry;
|
||||
this.sailNumber = sailnumber;
|
||||
this.boatName = boatName;
|
||||
this.boatClassName = boatClassName;
|
||||
@@ -150,21 +157,23 @@ public class ORCCertificateImpl implements ORCCertificate {
|
||||
* {@link ORCCertificate#ALLOWANCES_TRUE_WIND_ANGLES}, respectively, for the matrix of time allowances
|
||||
* or, conversely, the speed predictions.
|
||||
*/
|
||||
public ORCCertificateImpl(String idConsistingOfNatAuthCertNoAndBIN,
|
||||
String sailnumber, String boatName, String boatClassName,
|
||||
Distance length, Duration gph,
|
||||
Double cdl, TimePoint issueDate,
|
||||
Map<Speed, Map<Bearing, Speed>> velocityPredictionsPerTrueWindSpeedAndAngle,
|
||||
public ORCCertificateImpl(String referenceNumber,
|
||||
String fileId, String sailnumber, String boatName,
|
||||
String boatClassName, Distance length,
|
||||
Duration gph, Double cdl,
|
||||
TimePoint issueDate,
|
||||
CountryCode issuingCountry, Map<Speed, Map<Bearing, Speed>> velocityPredictionsPerTrueWindSpeedAndAngle,
|
||||
Map<Speed, Bearing> beatAngles, Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed,
|
||||
Map<Speed, Duration> beatAllowancePerTrueWindSpeed, Map<Speed, Bearing> runAngles,
|
||||
Map<Speed, Duration> beatAllowancePerTrueWindSpeed,
|
||||
Map<Speed, Bearing> runAngles,
|
||||
Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed,
|
||||
Map<Speed, Duration> runAllowancePerTrueWindSpeed,
|
||||
Map<Speed, Speed> windwardLeewardSpeedPredictionsPerTrueWindSpeed,
|
||||
Map<Speed, Speed> longDistanceSpeedPredictionsPerTrueWindSpeed,
|
||||
Map<Speed, Speed> circularRandomSpeedPredictionsPerTrueWindSpeed,
|
||||
Map<Speed, Speed> nonSpinnakerSpeedPredictionsPerTrueWindSpeed) {
|
||||
this(ALLOWANCES_TRUE_WIND_SPEEDS, ALLOWANCES_TRUE_WIND_ANGLES, idConsistingOfNatAuthCertNoAndBIN, sailnumber,
|
||||
boatName, boatClassName, length, gph, cdl, issueDate, velocityPredictionsPerTrueWindSpeedAndAngle,
|
||||
this(ALLOWANCES_TRUE_WIND_SPEEDS, ALLOWANCES_TRUE_WIND_ANGLES, referenceNumber, fileId, sailnumber, boatName,
|
||||
boatClassName, length, gph, cdl, issueDate, issuingCountry, velocityPredictionsPerTrueWindSpeedAndAngle,
|
||||
beatAngles, beatVMGPredictionPerTrueWindSpeed, beatAllowancePerTrueWindSpeed, runAngles,
|
||||
runVMGPredictionPerTrueWindSpeed, runAllowancePerTrueWindSpeed,
|
||||
windwardLeewardSpeedPredictionsPerTrueWindSpeed, longDistanceSpeedPredictionsPerTrueWindSpeed,
|
||||
@@ -173,7 +182,22 @@ public class ORCCertificateImpl implements ORCCertificate {
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return idConsistingOfNatAuthCertNoAndBIN;
|
||||
return getReferenceNumber();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceNumber() {
|
||||
return referenceNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFileId() {
|
||||
return fileId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountryCode getIssuingCountry() {
|
||||
return issuingCountry;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.junit.Rule;
|
||||
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
import com.sap.sse.common.Util;
|
||||
|
||||
|
||||
public abstract class AbstractORCCertificateImporterTest {
|
||||
protected static final String RESOURCES = "resources/orc/";
|
||||
|
||||
@Rule
|
||||
public FailIfNoValidOrcCertificateRule customIgnoreRule = new FailIfNoValidOrcCertificateRule();
|
||||
|
||||
protected void testSimpleLocalFileRead(String fileName, String expectedCertificateId) throws IOException, ParseException {
|
||||
File fileGER = new File(RESOURCES + fileName);
|
||||
ORCCertificatesCollection importer = ORCCertificatesImporter.INSTANCE.read(new FileInputStream(fileGER));
|
||||
ORCCertificate milan = importer.getCertificateById(expectedCertificateId);
|
||||
assertNotNull(milan);
|
||||
}
|
||||
|
||||
@FailIfNoValidOrcCertificates
|
||||
protected void testSimpleOnlineFileRead(String rmsOrJsonFormat) throws IOException, ParseException, InterruptedException {
|
||||
Collection<ORCCertificate> certificates = customIgnoreRule.getAvailableCerts();
|
||||
final ORCCertificate cert = certificates.stream().findFirst().get();
|
||||
String countryCode = cert.getIssuingCountry().getThreeLetterIOCCode();
|
||||
String url = String.format("https://data.orc.org/public/WPub.dll?action=DownRMS&CountryId=%s&ext=%s", countryCode, rmsOrJsonFormat);
|
||||
ORCCertificatesCollection importer = ORCCertificatesImporter.INSTANCE.read(new URL(url).openStream());
|
||||
ORCCertificate someValidCert = null, referenceCert = null;
|
||||
for (ORCCertificate orcCertificate : certificates) {
|
||||
someValidCert = importer.getCertificateById(orcCertificate.getId());
|
||||
if (someValidCert != null) {
|
||||
referenceCert = orcCertificate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertNotNull("None of the certificates "+String.join(", ", Util.map(certificates, c->c.toString()))+
|
||||
" was found when importing the country document from "+url, someValidCert);
|
||||
assertNotNull(referenceCert);
|
||||
assertEquals(referenceCert.getGPHInSecondsToTheMile(), someValidCert.getGPHInSecondsToTheMile(), 0.0000001);
|
||||
assertTrue(referenceCert.getWindwardLeewardSpeedPrediction().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds() > 10);
|
||||
assertTrue(referenceCert.getLongDistanceSpeedPredictions().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds() > 10);
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.rules.TestRule;
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runners.model.Statement;
|
||||
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.orc.ORCPublicCertificateDatabase.CertificateHandle;
|
||||
import com.sap.sailing.domain.orc.impl.ORCPublicCertificateDatabaseImpl;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.CountryCodeFactory;
|
||||
|
||||
/***
|
||||
* A IgnoreInvalidOrcCerticatesRule is an implementation of TestRule. This class execution depends on
|
||||
* {@link FailIfNoValidOrcCertificates} annotation on any method in a test class containing
|
||||
* {@link org.junit.rules.TestRule} annotation with current class implementation. When any test class added
|
||||
* {@link FailIfNoValidOrcCertificateRule} rule then before executing all of it's test method, Junit will execute the
|
||||
* evaluate() method of {@link FailIfNoValidOrcCertificateRule} class. This method first check whether the current test
|
||||
* method contains the {@link FailIfNoValidOrcCertificates} annotation, if yes then it will check for any certificate
|
||||
* available to parse on ORC Website. If at least one certificate is available then this method continues execution of
|
||||
* the current test method; otherwise it will let the test fail because the searching for certificates may be broken, or
|
||||
* the unlikely corner case applies where temporarily at the beginning of a new calendar year no valid certificate
|
||||
* exists at all in the ORC database.
|
||||
*
|
||||
* @author Usman Ali
|
||||
*
|
||||
*/
|
||||
|
||||
public class FailIfNoValidOrcCertificateRule implements TestRule {
|
||||
private ORCPublicCertificateDatabase db = new ORCPublicCertificateDatabaseImpl();
|
||||
|
||||
private List<ORCCertificate> availableCerts;
|
||||
|
||||
public Collection<ORCCertificate> getAvailableCerts() {
|
||||
return Collections.unmodifiableCollection(availableCerts);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement apply(Statement base, Description description) {
|
||||
return new IgnorableStatement(base, description);
|
||||
}
|
||||
|
||||
private class IgnorableStatement extends Statement {
|
||||
private final Statement base;
|
||||
private final Description description;
|
||||
|
||||
public IgnorableStatement(Statement base, Description description) {
|
||||
this.base = base;
|
||||
this.description = description;
|
||||
availableCerts = new ArrayList<>();
|
||||
}
|
||||
|
||||
/***
|
||||
* This method executes for every test case having {@link TestRule} annotation of
|
||||
* {@link FailIfNoValidOrcCertificateRule} class. Assume statement at the end of this method evaluates whether
|
||||
* the test method will execute or be ignored.
|
||||
*/
|
||||
@Override
|
||||
public void evaluate() throws Throwable {
|
||||
boolean certificateExists = true;
|
||||
FailIfNoValidOrcCertificates annotation = description.getAnnotation(FailIfNoValidOrcCertificates.class);
|
||||
if (annotation != null) {
|
||||
int year = LocalDate.now().getYear();
|
||||
certificateExists = false;
|
||||
for (CountryCode cc : CountryCodeFactory.INSTANCE.getAll()) {
|
||||
try {
|
||||
Iterable<CertificateHandle> certificateHandles = db.search(cc, year, null, null, null, null, /* includeInvalid */ false);
|
||||
Iterable<ORCCertificate> orcCertificates = db.getCertificates(certificateHandles);
|
||||
orcCertificates.forEach(availableCerts::add);
|
||||
if (orcCertificates.iterator().hasNext()) {
|
||||
certificateExists = true;
|
||||
break;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// Exceptions are ignored because we are searching for any countries orc certificate's
|
||||
// availability.
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(certificateExists);
|
||||
base.evaluate();
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/***
|
||||
* A IgnoreInvalidOrcCerticates is a annotation which is used to identify whether we need to execute the
|
||||
* {@link FailIfNoValidOrcCertificateRule} for that particular test case. i.e. you can find
|
||||
* the usage of {@link FailIfNoValidOrcCertificates} in
|
||||
* {@link TestORCPublicCertificateDatabase} class.
|
||||
*
|
||||
* @author Usman Ali
|
||||
*
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||
@Inherited
|
||||
public @interface FailIfNoValidOrcCertificates {
|
||||
|
||||
}
|
||||
+1
-1
@@ -128,7 +128,7 @@ public class ORCPerformanceCurveRankingTest extends OnlineTracTracBasedTest {
|
||||
final Boat boat = getTrackedRace().getRace().getBoatOfCompetitor(competitor);
|
||||
ORCCertificate certificate;
|
||||
if (boat.getSailID().equals("Air is blue")) {
|
||||
certificate = certificates.getCertificateById("ITA52521I5252");
|
||||
certificate = certificates.getCertificateById("ITA00052727");
|
||||
} else {
|
||||
certificate = certificates.getCertificateById(boat.getSailID());
|
||||
if (certificate == null) {
|
||||
|
||||
+5
-29
@@ -1,45 +1,21 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
|
||||
|
||||
public class TestORCCertificateImporterJSON {
|
||||
private static final String RESOURCES = "resources/orc/";
|
||||
public class TestORCCertificateImporterJSON extends AbstractORCCertificateImporterTest {
|
||||
|
||||
@Test
|
||||
public void testSimpleLocalJSONFileRead() throws IOException, ParseException {
|
||||
File fileGER = new File(RESOURCES + "GER2019.json");
|
||||
ORCCertificatesCollection importer = ORCCertificatesImporter.INSTANCE.read(new FileInputStream(fileGER));
|
||||
ORCCertificate milan = importer.getCertificateById("GER166844GER7323");
|
||||
assertNotNull(milan);
|
||||
testSimpleLocalFileRead("GER2019.json", "GER20041179");
|
||||
}
|
||||
|
||||
@Ignore("Certificate used for testing no longer valid after 2019")
|
||||
@FailIfNoValidOrcCertificates
|
||||
@Test
|
||||
public void testSimpleOnlineJSONFileRead() throws IOException, ParseException {
|
||||
ORCCertificatesCollection importer = ORCCertificatesImporter.INSTANCE.read(new URL("https://data.orc.org/public/WPub.dll?action=DownRMS&CountryId=GER&ext=json").openStream());
|
||||
ORCCertificate swan = importer.getCertificateById("GER140849GER5335");
|
||||
ORCCertificate moana = importer.getCertificateById("GER140772GER5549");
|
||||
assertNotNull(swan);
|
||||
assertNotNull(moana);
|
||||
assertEquals(539.1, swan .getGPHInSecondsToTheMile(), 0.0000001);
|
||||
assertEquals(490.4, moana.getGPHInSecondsToTheMile(), 0.0000001);
|
||||
assertEquals(862.2, swan .getWindwardLeewardSpeedPrediction().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(788.2, moana.getWindwardLeewardSpeedPrediction().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(861.0, swan .getLongDistanceSpeedPredictions().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(787.2, moana.getLongDistanceSpeedPredictions().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
public void testSimpleOnlineJSONFileRead() throws IOException, ParseException, InterruptedException {
|
||||
testSimpleOnlineFileRead("json");
|
||||
}
|
||||
}
|
||||
+7
-26
@@ -1,51 +1,32 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
|
||||
public class TestORCCertificateImporterRMS {
|
||||
public class TestORCCertificateImporterRMS extends AbstractORCCertificateImporterTest {
|
||||
private static final String RESOURCES = "resources/orc/";
|
||||
|
||||
|
||||
@Test
|
||||
public void testSimpleLocalRMSFileRead() throws IOException, ParseException {
|
||||
File fileGER = new File(RESOURCES + "GER2019.rms");
|
||||
ORCCertificatesCollection certificates = ORCCertificatesImporter.INSTANCE.read(new FileInputStream(fileGER));
|
||||
ORCCertificate milan = certificates.getCertificateById("GER166844GER7323");
|
||||
assertNotNull(milan);
|
||||
testSimpleLocalFileRead("GER2019.rms", "GER20041179");
|
||||
}
|
||||
|
||||
@Ignore("Certificate used for testing no longer valid after 2019")
|
||||
@FailIfNoValidOrcCertificates
|
||||
@Test
|
||||
public void testSimpleOnlineRMSFileRead() throws IOException, ParseException {
|
||||
ORCCertificatesCollection certificates = ORCCertificatesImporter.INSTANCE.read(new URL("https://data.orc.org/public/WPub.dll?action=DownRMS&CountryId=GER&ext=rms").openStream());
|
||||
ORCCertificate swan = certificates.getCertificateById("GER140849GER5335");
|
||||
ORCCertificate moana = certificates.getCertificateById("GER140772GER5549");
|
||||
assertNotNull(swan);
|
||||
assertNotNull(moana);
|
||||
assertEquals(539.1, swan .getGPHInSecondsToTheMile(), 0.0000001);
|
||||
assertEquals(490.4, moana.getGPHInSecondsToTheMile(), 0.0000001);
|
||||
assertEquals(862.2, swan .getWindwardLeewardSpeedPrediction().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(788.2, moana.getWindwardLeewardSpeedPrediction().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(861.0, swan .getLongDistanceSpeedPredictions().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
assertEquals(787.2, moana.getLongDistanceSpeedPredictions().get(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS[0]).getDuration(ORCCertificateImpl.NAUTICAL_MILE).asSeconds(), 0.1);
|
||||
public void testSimpleOnlineRMSFileRead() throws IOException, ParseException, InterruptedException {
|
||||
testSimpleOnlineFileRead("rms");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLocalRMSFileReadWithIdenticalSailnumbers() throws IOException, ParseException {
|
||||
//additional test to ensure certificates with same sailnumbers but different ids are equally parsed and saved
|
||||
// additional test to ensure certificates with same sailnumbers but different ids are equally parsed and saved
|
||||
File file = new File(RESOURCES + "multipleIdenticalSailnumbers.rms");
|
||||
ORCCertificatesCollection certificates = ORCCertificatesImporter.INSTANCE.read(new FileInputStream(file));
|
||||
assertEquals(14, ((Collection<?>) (certificates.getCertificateIds())).size());
|
||||
|
||||
+39
-38
@@ -17,7 +17,6 @@ import org.apache.commons.math.MaxIterationsExceededException;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ErrorCollector;
|
||||
@@ -46,7 +45,6 @@ import com.sap.sse.common.impl.DegreeBearingImpl;
|
||||
*
|
||||
*/
|
||||
public class TestORCPerformanceCurve {
|
||||
|
||||
// set true to see all the differences i
|
||||
private final boolean collectErrors = true;
|
||||
|
||||
@@ -56,6 +54,9 @@ public class TestORCPerformanceCurve {
|
||||
private static ORCCertificatesCollection importerOnline;
|
||||
|
||||
private static final String RESOURCES = "resources/orc/";
|
||||
|
||||
@Rule
|
||||
public FailIfNoValidOrcCertificateRule customFailRule = new FailIfNoValidOrcCertificateRule();
|
||||
|
||||
@Rule
|
||||
public ErrorCollector collector = new ErrorCollector();
|
||||
@@ -97,36 +98,36 @@ public class TestORCPerformanceCurve {
|
||||
File fileWithSpecificBins = new File(RESOURCES + "newFormatCertificate.json");
|
||||
importerWithSpecificBins = new ORCCertificatesJsonImporter().read(new FileInputStream(fileWithSpecificBins));
|
||||
// Online File:
|
||||
importerOnline = new ORCCertificatesJsonImporter().read(new URL("https://data.orc.org/public/WPub.dll?action=DownRMS&CountryId=GER&ext=json").openStream());
|
||||
importerOnline = new ORCCertificatesJsonImporter().read(new URL("https://data.orc.org/public/WPub.dll?action=DownBoatRMS&CountryId=GER&ext=json").openStream());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLagrangeInterpolation60() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER20040783");
|
||||
testAllowancePerLeg(certificate, 60.0, 498.4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLagrangeInterpolation62_5() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER20040783");
|
||||
testAllowancePerLeg(certificate, 62.5, 492.2, 425.0, 403.6, 393.1, 386.7, 382.6, 371.4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLagrangeInterpolation98_3() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER20040783");
|
||||
testAllowancePerLeg(certificate, 98.3, 483.6, 418.7, 394.8, 377.9, 360.2, 345.0, 321.7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLagrangeInterpolation120() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER20040783");
|
||||
testAllowancePerLeg(certificate, 120.0, 506);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLagrangeInterpolation138_7() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = importerLocal.getCertificateById("GER20040783");
|
||||
testAllowancePerLeg(certificate, 138.7, 588.1, 468.4, 413.8, 382.6, 355.1, 326.4, 275.4);
|
||||
}
|
||||
|
||||
@@ -141,7 +142,7 @@ public class TestORCPerformanceCurve {
|
||||
|
||||
@Test
|
||||
public void testSimpleConstructedCourse() throws FunctionEvaluationException {
|
||||
ORCCertificate certificate = (ORCCertificate) importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = (ORCCertificate) importerLocal.getCertificateById("GER20040783");
|
||||
List<ORCPerformanceCurveLeg> legs = new ArrayList<>();
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(1.0), new DegreeBearingImpl(0)));
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(1.0), new DegreeBearingImpl(30)));
|
||||
@@ -164,7 +165,7 @@ public class TestORCPerformanceCurve {
|
||||
@Test
|
||||
public void testPerformanceCurveInversion() throws MaxIterationsExceededException, FunctionEvaluationException {
|
||||
Double accuracy = 0.1;
|
||||
ORCCertificate certificate = (ORCCertificate) importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificate = (ORCCertificate) importerLocal.getCertificateById("GER20040783");
|
||||
ORCPerformanceCurveImpl performanceCurve = (ORCPerformanceCurveImpl) new ORCPerformanceCurveImpl(certificate, alturaCourse);
|
||||
testBackwardForward(accuracy, performanceCurve, 11.5);
|
||||
testBackwardForward(accuracy, performanceCurve, 17.23);
|
||||
@@ -193,12 +194,12 @@ public class TestORCPerformanceCurve {
|
||||
@Test
|
||||
public void testImpliedWind() throws MaxIterationsExceededException, FunctionEvaluationException {
|
||||
double accuracy = 0.0001;
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER166844GER7323");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER140618GER5609");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER140755GER5555");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER141411GER6300");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER141432GER5564");
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER20040783");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER20041179");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER30010194");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER20040647");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER30010167");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER20040632");
|
||||
ORCPerformanceCurve performanceCurveMoana = new ORCPerformanceCurveImpl(certificateMoana, alturaCourse);
|
||||
ORCPerformanceCurve performanceCurveMilan = new ORCPerformanceCurveImpl(certificateMilan, alturaCourse);
|
||||
ORCPerformanceCurve performanceCurveTutima = new ORCPerformanceCurveImpl(certificateTutima, alturaCourse);
|
||||
@@ -230,12 +231,12 @@ public class TestORCPerformanceCurve {
|
||||
@Test
|
||||
public void testAllowances() throws FunctionEvaluationException {
|
||||
double accuracy = 0.00001;
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER166844GER7323");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER140618GER5609");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER140755GER5555");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER141411GER6300");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER141432GER5564");
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER20040783");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER20041179");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER30010194");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER20040647");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER30010167");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER20040632");
|
||||
ORCPerformanceCurve performanceCurveMoana = new ORCPerformanceCurveImpl(certificateMoana, alturaCourse);
|
||||
ORCPerformanceCurve performanceCurveMilan = new ORCPerformanceCurveImpl(certificateMilan, alturaCourse);
|
||||
ORCPerformanceCurve performanceCurveTutima = new ORCPerformanceCurveImpl(certificateTutima, alturaCourse);
|
||||
@@ -253,7 +254,7 @@ public class TestORCPerformanceCurve {
|
||||
/**
|
||||
* Tests to make sure, that the structure of the certificate files didn't change and performance curves can be built
|
||||
*/
|
||||
@Ignore("Certificate used for testing no longer valid after 2019")
|
||||
@FailIfNoValidOrcCertificates
|
||||
@Test
|
||||
public void testOnlineImport() throws FunctionEvaluationException {
|
||||
assertFalse(Util.isEmpty(importerOnline.getCertificateIds()));
|
||||
@@ -267,7 +268,7 @@ public class TestORCPerformanceCurve {
|
||||
final double highAccuracy = 0.01;
|
||||
final double allowanceAccuracy = 0.1;
|
||||
final Distance ONE_NAUTICAL_MILE = new NauticalMileDistance(1.0);
|
||||
final ORCCertificate certificateWithSpecificBins = importerWithSpecificBins.getCertificateById("GRA00073GR317");
|
||||
final ORCCertificate certificateWithSpecificBins = importerWithSpecificBins.getCertificateById("N/A");
|
||||
for (final Bearing twa : certificateWithSpecificBins.getTrueWindAngles()) {
|
||||
final ORCPerformanceCurveCourse singleLegOneMileCourseWithTwa = createSingleLegCourseWithTwa(twa);
|
||||
final ORCPerformanceCurve performanceCurveSpecificBins = new ORCPerformanceCurveImpl(certificateWithSpecificBins, singleLegOneMileCourseWithTwa);
|
||||
@@ -298,13 +299,13 @@ public class TestORCPerformanceCurve {
|
||||
ORCPerformanceCurveCourse complexCourse = new ORCPerformanceCurveCourseImpl(list);
|
||||
|
||||
final double accuracy = 0.0001;
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER166844GER7323");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER140618GER5609");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER140755GER5555");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER141411GER6300");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER141432GER5564");
|
||||
ORCCertificate certificateWithSpecificBins=importerWithSpecificBins.getCertificateById("GRA00073GR317");
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER20040783");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER20041179");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER30010194");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER20040647");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER30010167");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER20040632");
|
||||
ORCCertificate certificateWithSpecificBins=importerWithSpecificBins.getCertificateById("N/A");
|
||||
ORCPerformanceCurve performanceCurveMoana = new ORCPerformanceCurveImpl(certificateMoana, complexCourse);
|
||||
ORCPerformanceCurve performanceCurveMilan = new ORCPerformanceCurveImpl(certificateMilan, complexCourse);
|
||||
ORCPerformanceCurve performanceCurveTutima = new ORCPerformanceCurveImpl(certificateTutima, complexCourse);
|
||||
@@ -333,13 +334,13 @@ public class TestORCPerformanceCurve {
|
||||
ORCPerformanceCurveCourse complexCourse = new ORCPerformanceCurveCourseImpl(list);
|
||||
|
||||
double accuracy = 0.00001;
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER140772GER5549");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER166844GER7323");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER140618GER5609");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER140755GER5555");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER141411GER6300");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER141432GER5564");
|
||||
ORCCertificate certificateWithSpecificBins=importerWithSpecificBins.getCertificateById("GRA00073GR317");
|
||||
ORCCertificate certificateMoana = importerLocal.getCertificateById("GER20040783");
|
||||
ORCCertificate certificateMilan = importerLocal.getCertificateById("GER20041179");
|
||||
ORCCertificate certificateTutima = importerLocal.getCertificateById("GER30010194");
|
||||
ORCCertificate certificateBank = importerLocal.getCertificateById("GER20040647");
|
||||
ORCCertificate certificateHaspa = importerLocal.getCertificateById("GER30010167");
|
||||
ORCCertificate certificateHalbtrocken = importerLocal.getCertificateById("GER20040632");
|
||||
ORCCertificate certificateWithSpecificBins=importerWithSpecificBins.getCertificateById("N/A");
|
||||
ORCPerformanceCurve performanceCurveMoana = new ORCPerformanceCurveImpl(certificateMoana, complexCourse);
|
||||
ORCPerformanceCurve performanceCurveMilan = new ORCPerformanceCurveImpl(certificateMilan, complexCourse);
|
||||
ORCPerformanceCurve performanceCurveTutima = new ORCPerformanceCurveImpl(certificateTutima, complexCourse);
|
||||
|
||||
-18
@@ -25,7 +25,6 @@ import com.sap.sse.common.Util;
|
||||
import com.sap.sse.common.impl.DegreeBearingImpl;
|
||||
|
||||
public class TestORCPerformanceCurveCourse {
|
||||
|
||||
@Test
|
||||
public void testSubcourseOfSimpleORCCourse() {
|
||||
double accuracy = 0.000000001;
|
||||
@@ -36,23 +35,18 @@ public class TestORCPerformanceCurveCourse {
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(1), new DegreeBearingImpl(180)));
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(1), new DegreeBearingImpl(0)));
|
||||
ORCPerformanceCurveCourse course = new ORCPerformanceCurveCourseImpl(legs);
|
||||
|
||||
// case 0: no leg finished, 40.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse0 = course.subcourse(0, 0.4);
|
||||
assertEquals(0.4, subcourse0.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 1: first leg finished, 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse1 = course.subcourse(1, 0);
|
||||
assertEquals(1, subcourse1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 2: first leg finished, 12.5% of current leg
|
||||
ORCPerformanceCurveCourse subcourse2 = course.subcourse(1, 0.125);
|
||||
assertEquals(1.125, subcourse2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// special case: didn't start, equals to no legs finished and 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourseSpecial1 = course.subcourse(0, 0);
|
||||
assertEquals(0, subcourseSpecial1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// special case: number of finished legs is higher then number of actual legs
|
||||
ORCPerformanceCurveCourse subcourseSpecial2 = course.subcourse(10,0);
|
||||
assertEquals(5, subcourseSpecial2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
@@ -68,23 +62,18 @@ public class TestORCPerformanceCurveCourse {
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(10.23), new DegreeBearingImpl(180)));
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(2.57), new DegreeBearingImpl(0)));
|
||||
ORCPerformanceCurveCourse course = new ORCPerformanceCurveCourseImpl(legs);
|
||||
|
||||
// case 0: no leg finished, 40.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse0 = course.subcourse(0, 0.4);
|
||||
assertEquals(1.512, subcourse0.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 1: first leg finished, 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse1 = course.subcourse(1, 0);
|
||||
assertEquals(3.78, subcourse1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 2: first leg finished, 12.5% of current leg
|
||||
ORCPerformanceCurveCourse subcourse2 = course.subcourse(1, 0.125);
|
||||
assertEquals(3.96125, subcourse2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// special case: didn't start, equals to no legs finished and 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourseSpecial1 = course.subcourse(0, 0);
|
||||
assertEquals(0, subcourseSpecial1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// special case: number of finished legs is higher then number of actual legs
|
||||
ORCPerformanceCurveCourse subcourseSpecial2 = course.subcourse(10,0);
|
||||
assertEquals(23.03, subcourseSpecial2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
@@ -99,26 +88,21 @@ public class TestORCPerformanceCurveCourse {
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(3), ORCPerformanceCurveLegTypes.CIRCULAR_RANDOM));
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(4), new DegreeBearingImpl(0)));
|
||||
ORCPerformanceCurveCourse course = new ORCPerformanceCurveCourseImpl(legs);
|
||||
|
||||
// case 0: no leg finished, 40.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse0 = course.subcourse(0, 0.4);
|
||||
assertEquals(0.4, subcourse0.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 1: first leg finished, 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse1 = course.subcourse(1, 0);
|
||||
assertEquals(1, subcourse1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 2: first leg finished, 12.5% of current leg
|
||||
ORCPerformanceCurveCourse subcourse2 = course.subcourse(1, 0.125);
|
||||
assertEquals(1.25, subcourse2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
assertEquals(ORCPerformanceCurveLegTypes.LONG_DISTANCE, Util.last(subcourse2.getLegs()).getType());
|
||||
assertEquals(0, subcourse2.getLegs().iterator().next().getTwa().getDegrees(), accuracy);
|
||||
|
||||
// special case: didn't start, equals to no legs finished and 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourseSpecial1 = course.subcourse(0, 0);
|
||||
assertEquals(0, subcourseSpecial1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
assertEquals(1, Util.size(subcourseSpecial1.getLegs()));
|
||||
|
||||
// special case: number of finished legs is higher then number of actual legs
|
||||
ORCPerformanceCurveCourse subcourseSpecial2 = course.subcourse(10, 0);
|
||||
assertEquals(10, subcourseSpecial2.getTotalLength().getNauticalMiles(), accuracy);
|
||||
@@ -135,11 +119,9 @@ public class TestORCPerformanceCurveCourse {
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(1), new DegreeBearingImpl(0)));
|
||||
legs.add(new ORCPerformanceCurveLegImpl(new NauticalMileDistance(2), new DegreeBearingImpl(0)));
|
||||
ORCPerformanceCurveCourse course = new ORCPerformanceCurveCourseImpl(legs);
|
||||
|
||||
// case 0: no leg finished, 40.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse0 = course.subcourse(0, 0.4);
|
||||
assertEquals(0.4, subcourse0.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
// case 1: first leg finished, 0.0% of current leg
|
||||
ORCPerformanceCurveCourse subcourse1 = subcourse0.subcourse(0, 0.1);
|
||||
assertEquals(0.04, subcourse1.getTotalLength().getNauticalMiles(), accuracy);
|
||||
|
||||
+137
-33
@@ -2,33 +2,93 @@ package com.sap.sailing.domain.orc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TimeZone;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sap.sailing.domain.base.impl.BoatClassImpl;
|
||||
import com.sap.sailing.domain.common.BoatClassMasterdata;
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.orc.ORCPublicCertificateDatabase.CertificateHandle;
|
||||
import com.sap.sailing.domain.orc.impl.ORCPublicCertificateDatabaseImpl;
|
||||
import com.sap.sse.common.Util;
|
||||
|
||||
public class TestORCPublicCertificateDatabase {
|
||||
private static final Logger logger = Logger.getLogger(TestORCPublicCertificateDatabase.class.getName());
|
||||
|
||||
private ORCPublicCertificateDatabase db;
|
||||
private Map<String, Date> dateComparisonMap = new LinkedHashMap<String, Date>();
|
||||
private List<String> dateFailureCases = Arrays.asList("2019-02-21T10:44GMT+2","2019-02-21T10:38+0800","2019-02-21T10:38+08:00",
|
||||
"2019-02-21T10:38-08","2019-02-21T10:38Z","2019-02-21T10z","2019-02-21T10:38z");
|
||||
|
||||
@Rule
|
||||
public FailIfNoValidOrcCertificateRule customIgnoreRule = new FailIfNoValidOrcCertificateRule();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
db = new ORCPublicCertificateDatabaseImpl();
|
||||
/**
|
||||
* By default GregorianCalendar month starts from 0 as January and so on. In below cases 1 specifies the date
|
||||
* month as February.
|
||||
*/
|
||||
dateComparisonMap.put("2019-02-21T10:38:59Z", Date.from(ZonedDateTime.parse("2019-02-21T10:38:59Z").toInstant()));
|
||||
// dateComparisonMap.put("2019-02-21T12:00:00.000GMT+2", Date.from(ZonedDateTime.of(2019, 2, 21, 10, 38, 59, 0, ZoneId.systemDefault()).toInstant()));
|
||||
// // dateComparisonMap.put("2019-02-21T15:00:00.000 GMT-2", Date.from(ZonedDateTime.of(2019, 2, 21, 10, 38, 59, 0, ZoneId.systemDefault()).toInstant()));
|
||||
dateComparisonMap.put("2019-02-21T10:38:55.000-0800",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:55.000-0800", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:32.000+08:00",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:32.000+08:00").toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:09.000-06",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:09.000-06", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSx")).toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:22.000Z",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:22.000Z").toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:00.000z",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:00.000z").toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:46z",
|
||||
Date.from(ZonedDateTime.parse("2019-02-21T10:38:46z").toInstant())
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:17",
|
||||
Date.from(LocalDateTime.parse("2019-02-21T10:38:17").toInstant(ZoneOffset.UTC))
|
||||
);
|
||||
dateComparisonMap.put(
|
||||
"2019-02-21T10:38:33.000",
|
||||
Date.from(LocalDateTime.parse("2019-02-21T10:38:33.000").toInstant(ZoneOffset.UTC))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -36,7 +96,7 @@ public class TestORCPublicCertificateDatabase {
|
||||
final String referenceNumber = "FRA00013881";
|
||||
final Iterable<CertificateHandle> result = db.search(/* country */ null, /* yearOfIssuance */ null,
|
||||
/* referenceNumber */ referenceNumber, /* yachtName */ null, /* sailNumber */ null,
|
||||
/* boatClassName */ null);
|
||||
/* boatClassName */ null, /* includeInvalid */ true);
|
||||
assertEquals(1, Util.size(result));
|
||||
assertSoulmate(referenceNumber, result.iterator().next());
|
||||
}
|
||||
@@ -46,7 +106,7 @@ public class TestORCPublicCertificateDatabase {
|
||||
final String referenceNumber = "FRA00013881";
|
||||
final Iterable<CertificateHandle> result = db.search(/* country */ null, /* yearOfIssuance */ 2019,
|
||||
/* referenceNumber */ null, /* yachtName */ "Soulmate", /* sailNumber */ "DEN- 13",
|
||||
/* boatClassName */ null);
|
||||
/* boatClassName */ null, /* includeInvalid */ true);
|
||||
assertEquals(1, Util.size(result));
|
||||
assertSoulmate(referenceNumber, result.iterator().next());
|
||||
}
|
||||
@@ -56,7 +116,7 @@ public class TestORCPublicCertificateDatabase {
|
||||
final String referenceNumber = "FRA00013881";
|
||||
final Iterable<CertificateHandle> result = db.search(/* country */ null, /* yearOfIssuance */ null,
|
||||
/* referenceNumber */ null, /* yachtName */ "Soulmate", /* sailNumber */ null,
|
||||
/* boatClassName */ null);
|
||||
/* boatClassName */ null, /* includeInvalid */ true);
|
||||
assertTrue(Util.size(result)>1);
|
||||
boolean found = false;
|
||||
for (final CertificateHandle handle : result) {
|
||||
@@ -75,42 +135,86 @@ public class TestORCPublicCertificateDatabase {
|
||||
assertSoulmate(referenceNumber, result);
|
||||
}
|
||||
|
||||
// TODO this test will probably break 2021 when 2020 certificates will no longer be returned as valid...
|
||||
@Test
|
||||
public void testGetCertificate() throws Exception {
|
||||
final String referenceNumber = "03360000CE8";
|
||||
public void testCertificateUpdate() throws Exception {
|
||||
final String referenceNumber = "FRA00013881";
|
||||
final CertificateHandle oldHandle = db.getCertificateHandle(referenceNumber);
|
||||
final ORCCertificate result = db.searchForUpdate(oldHandle);
|
||||
if (result != null) {
|
||||
assertEquals(oldHandle.getFileId(), result.getFileId());
|
||||
assertEquals(oldHandle.getIssuingCountry(), result.getIssuingCountry());
|
||||
assertFalse(oldHandle.getIssueDate().after(result.getIssueDate()));
|
||||
} else {
|
||||
logger.warning("Couldn't find an update to certificate with reference number "+referenceNumber+
|
||||
" anymore. Consider updating this test case to using a different certificate that still has a valid update.");
|
||||
}
|
||||
}
|
||||
|
||||
@FailIfNoValidOrcCertificates
|
||||
@Test
|
||||
public void testGetCertificate() throws Exception {
|
||||
Collection<ORCCertificate> certificates = customIgnoreRule.getAvailableCerts();
|
||||
final ORCCertificate cert = certificates.stream().findFirst().get();
|
||||
Iterable<CertificateHandle> certHandles = db.search(null, LocalDate.now().getYear(), null, cert.getBoatName(),
|
||||
cert.getSailNumber(), /*
|
||||
* boat class name; could be set to cert.getBoatClassName() but there are
|
||||
* deviations in ORC DBs and query API, so leaving null:
|
||||
*/ null, /* includeInvalid */ false);
|
||||
Optional<CertificateHandle> certificateHandle = Optional.ofNullable(certHandles.iterator().hasNext() ? certHandles.iterator().next() : null);
|
||||
assertTrue("No certificate found for handle "+certificateHandle+
|
||||
" extracted from certificates "+certificates, certificateHandle.isPresent());
|
||||
final String referenceNumber = certificateHandle.get().getReferenceNumber();
|
||||
final CertificateHandle handle = db.getCertificateHandle(referenceNumber);
|
||||
final ORCCertificate result = db.getCertificate(referenceNumber);
|
||||
assertNotNull("Unable to load certificate for reference number "+referenceNumber+" from handle "+certificateHandle);
|
||||
assertEquals(handle.getGPH(), result.getGPH().asSeconds(), 0.00001);
|
||||
assertTrue(handle.getIssueDate().until(result.getIssueDate()).abs().asSeconds() < 10);
|
||||
// Use some tolerance as we found differences as much as 5s between the dxtDate in the handle coming from the XML search result
|
||||
// and the IssueDate field in the JSON. Both suggest to report millisecond accuracy, but dxtDate always seems to have the
|
||||
// milliseconds as "000" explaining many sub-second differences. But in some cases differences were significantly bigger.
|
||||
assertEquals("Issue dates of certificate with reference number "+referenceNumber+
|
||||
" varies between current year result handle ("+handle.getIssueDate()+") and certificate ("+
|
||||
result.getIssueDate()+").", handle.getIssueDate().asMillis(), result.getIssueDate().asMillis(), 10000.0);
|
||||
assertEquals(handle.getSailNumber(), result.getSailNumber());
|
||||
}
|
||||
|
||||
@Ignore("Certificate used for testing no longer valid after 2019")
|
||||
@FailIfNoValidOrcCertificates
|
||||
@Test
|
||||
public void testParallelFuzzySearch() throws InterruptedException, ExecutionException {
|
||||
final Future<Set<ORCCertificate>> soulmateCertificatesFuture = db.search("Soulmate", "DEN13", new BoatClassImpl("ORC", BoatClassMasterdata.ORC));
|
||||
final Future<Set<ORCCertificate>> amarettoCertificatesFuture = db.search("Amaretto", "NED 6101", new BoatClassImpl("Beneteau First 40.7", /* starts upwind */ true));
|
||||
final Set<ORCCertificate> soulmateCertificates = soulmateCertificatesFuture.get();
|
||||
final Set<ORCCertificate> amarettoCertificates = amarettoCertificatesFuture.get();
|
||||
assertFoundYear(soulmateCertificates, 2019);
|
||||
assertFoundYear(amarettoCertificates, 2019);
|
||||
int year = LocalDate.now().getYear();
|
||||
ArrayList<Future<Set<ORCCertificate>>> futures = new ArrayList<Future<Set<ORCCertificate>>>();
|
||||
boolean isYearFound = false;
|
||||
for (ORCCertificate orcCertificate : customIgnoreRule.getAvailableCerts()) {
|
||||
futures.add(db.search(orcCertificate.getBoatName(), orcCertificate.getSailNumber(),
|
||||
new BoatClassImpl(orcCertificate.getBoatClassName(), true)));
|
||||
}
|
||||
for (Future<Set<ORCCertificate>> futureResult : futures) {
|
||||
isYearFound = isYearFound || assertFoundYear(futureResult.get(), year);
|
||||
}
|
||||
assertTrue(isYearFound);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseDateSuccessCases() {
|
||||
for (String date : dateComparisonMap.keySet()) {
|
||||
Date convertedDate = db.parseDate(date);
|
||||
assertEquals(convertedDate, dateComparisonMap.get(date));
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = DateTimeParseException.class)
|
||||
public void testShould() throws Exception {
|
||||
for (String dateString : dateFailureCases) {
|
||||
db.parseDate(dateString);
|
||||
Assert.fail(dateString + " is parsable");
|
||||
}
|
||||
}
|
||||
|
||||
private void assertFoundYear(final Set<ORCCertificate> certificates, int year) {
|
||||
boolean foundYear = false;
|
||||
for (final ORCCertificate certificate : certificates) {
|
||||
if (certificate.getIssueDate() != null) {
|
||||
final GregorianCalendar cal = new GregorianCalendar();
|
||||
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
cal.setTimeInMillis(certificate.getIssueDate().asMillis());
|
||||
if (cal.get(Calendar.YEAR) == year) {
|
||||
foundYear = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(foundYear);
|
||||
private boolean assertFoundYear(final Set<ORCCertificate> certificates, int year) {
|
||||
return certificates.stream().map(cert -> {
|
||||
LocalDate certDate = Instant.ofEpochMilli(cert.getIssueDate().asMillis()).atOffset(ZoneOffset.UTC)
|
||||
.toLocalDate();
|
||||
return certDate.getYear();
|
||||
}).anyMatch(cy -> cy == year);
|
||||
}
|
||||
|
||||
private void assertSoulmate(final String referenceNumber, CertificateHandle handle) {
|
||||
|
||||
+31
-7
@@ -1,6 +1,8 @@
|
||||
package com.sap.sailing.domain.orc;
|
||||
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Future;
|
||||
@@ -15,8 +17,14 @@ import com.sap.sse.common.Util;
|
||||
/**
|
||||
* An interface to {@code data.orc.org}, mostly the search functionality at
|
||||
* {@code https://data.orc.org/public/WPub.dll?action=SrchCert&xslp=scert.php}. It can search for certificates by a
|
||||
* number of criteria, among them the issuing country, sail number, ORC reference number, or boat name.
|
||||
* <p>
|
||||
* number of criteria, among them the issuing country, sail number, ORC reference number, or boat name. Those search
|
||||
* results are represented as {@link CertificateHandle} objects. Such handles can also be obtained for certificates that
|
||||
* are not currently valid. See the {@code includeInvalid} parameter of the
|
||||
* {@link #search(CountryCode, Integer, String, String, String, String, boolean)} method. However, handles for
|
||||
* {@link CertificateHandle#isValid() invalid} certificates cannot be resolved into {@link ORCCertificate} objects
|
||||
* through {@link #getCertificates(Iterable)} or {@link #getCertificates(CertificateHandle...)} because the database
|
||||
* returns full certificates only if they are valid.
|
||||
* <p>
|
||||
*
|
||||
* As the web site emits XML documents as search results, those can be parsed and turned into handles to certificates.
|
||||
* An example output (excerpt):
|
||||
@@ -78,8 +86,8 @@ import com.sap.sse.common.Util;
|
||||
</DATA>
|
||||
* </pre>
|
||||
*
|
||||
* This also shows that some query results do not provide a valid link to a downloadable copy of the certificate. Those are
|
||||
* automatically removed from the results here.
|
||||
* This also shows that some query results do not provide a valid link to a downloadable copy of the certificate. Those
|
||||
* are automatically removed from the results here.
|
||||
*
|
||||
* @author Axel Uhl (D043530)
|
||||
*
|
||||
@@ -95,6 +103,7 @@ public interface ORCPublicCertificateDatabase {
|
||||
*/
|
||||
public interface CertificateHandle {
|
||||
CountryCode getIssuingCountry();
|
||||
String getFileId();
|
||||
Double getGPH();
|
||||
String getSSSID();
|
||||
UUID getDatInGID();
|
||||
@@ -109,6 +118,7 @@ public interface ORCPublicCertificateDatabase {
|
||||
Integer getCertType();
|
||||
Boolean isOd();
|
||||
Boolean isProvisional();
|
||||
Boolean isValid();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,10 +127,18 @@ public interface ORCPublicCertificateDatabase {
|
||||
* {@code boatClassName} parameters.
|
||||
* <p>
|
||||
*
|
||||
* @return an always valid, never {@code null} object which may be {@link Util#isEmpty() empty}.
|
||||
* @param includeInvalid
|
||||
* If {@code true}, handles may have {@link CertificateHandle#isValid()}{@code == false}, meaning that
|
||||
* such a handle cannot be resolved to a {@link ORCCertificate} using any of
|
||||
* {@link #getCertificate(String)}, {@link #getCertificates(Iterable)} and
|
||||
* {@link #getCertificates(CertificateHandle...)}. If {@code false}, only valid certificate handles
|
||||
* will be returned that should all be resolvable into an {@link ORCCertificate} with any of the methods
|
||||
* listed above.
|
||||
*
|
||||
* @return never {@code null}; an object which may be {@link Util#isEmpty() empty}.
|
||||
*/
|
||||
Iterable<CertificateHandle> search(CountryCode country, Integer yearOfIssuance, String referenceNumber,
|
||||
String yachtName, String sailNumber, String boatClassName) throws Exception;
|
||||
String yachtName, String sailNumber, String boatClassName, boolean includeInvalid) throws Exception;
|
||||
|
||||
default Iterable<ORCCertificate> getCertificates(Iterable<CertificateHandle> handles) throws Exception {
|
||||
return Util.map(handles, handle->{
|
||||
@@ -137,9 +155,13 @@ public interface ORCPublicCertificateDatabase {
|
||||
}
|
||||
|
||||
default CertificateHandle getCertificateHandle(String referenceNumber) throws Exception {
|
||||
return search(null, null, referenceNumber, null, null, null).iterator().next();
|
||||
return search(null, null, referenceNumber, null, null, null, /* includeInvalid */ true).iterator().next();
|
||||
}
|
||||
|
||||
ORCCertificate searchForUpdate(ORCCertificate certificate) throws Exception;
|
||||
|
||||
ORCCertificate searchForUpdate(CertificateHandle certificate) throws Exception;
|
||||
|
||||
ORCCertificate getCertificate(String referenceNumber) throws Exception;
|
||||
|
||||
/**
|
||||
@@ -166,4 +188,6 @@ public interface ORCPublicCertificateDatabase {
|
||||
* parameters.
|
||||
*/
|
||||
Future<Set<ORCCertificate>> search(String yachtName, String sailNumber, BoatClass boatClass);
|
||||
|
||||
Date parseDate(final String dateString) throws DateTimeParseException;
|
||||
}
|
||||
+4
@@ -24,6 +24,10 @@ public abstract class AbstractORCCertificatesCollection implements ORCCertificat
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String canonicalizeId(String certificateId) {
|
||||
return certificateId.replaceAll(" ", "").replaceAll("\t", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<ORCCertificate> getCertificates() {
|
||||
|
||||
+169
-152
@@ -21,6 +21,7 @@ import com.sap.sailing.domain.common.impl.MeterDistance;
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCodeFactory;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
@@ -52,16 +53,15 @@ public class ORCCertificatesCollectionJSON extends AbstractORCCertificatesCollec
|
||||
private static final String YACHT_NAME = "YachtName";
|
||||
private static final String LOA = "LOA";
|
||||
private static final String SAIL_NO = "SailNo";
|
||||
private static final String CERT_NO = "CertNo";
|
||||
private static final String BIN = "BIN";
|
||||
private static final String NAT_AUTH = "NatAuth";
|
||||
private static final String REFERENCE_NUMBER = "RefNo";
|
||||
private static final String RUN = "Run";
|
||||
private static final String BEAT = "Beat";
|
||||
private static final String WINDWARD_LEEWARD = "WL";
|
||||
private static final String LONG_DISTANCE = "OC";
|
||||
private static final String CIRCULAR_RANDOM = "CR";
|
||||
private static final String NON_SPINNAKER = "NS";
|
||||
private static final String EMPTY_CERT_NO = " ";
|
||||
private static final String WIND_SPEEDS = "WindSpeeds";
|
||||
|
||||
/**
|
||||
@@ -70,6 +70,9 @@ public class ORCCertificatesCollectionJSON extends AbstractORCCertificatesCollec
|
||||
*/
|
||||
private static final Pattern twaPattern = Pattern.compile("R(\\d+(\\.\\d+)?)");
|
||||
|
||||
/**
|
||||
* Keys are canonicalized through {@link #canonicalizeId(String)}).
|
||||
*/
|
||||
private Map<String, JSONObject> certificateJsonObjectsByCertificateId;
|
||||
|
||||
/**
|
||||
@@ -79,7 +82,7 @@ public class ORCCertificatesCollectionJSON extends AbstractORCCertificatesCollec
|
||||
public ORCCertificatesCollectionJSON(Iterable<JSONObject> data) {
|
||||
this.certificateJsonObjectsByCertificateId = new HashMap<>();
|
||||
for (final JSONObject o : data) {
|
||||
if (this.certificateJsonObjectsByCertificateId.put(getId(o), o) != null) {
|
||||
if (this.certificateJsonObjectsByCertificateId.put(canonicalizeId(getId(o)), o) != null) {
|
||||
throw new IllegalArgumentException("Certificate ID in collection not unique: " + getId(o));
|
||||
}
|
||||
}
|
||||
@@ -88,9 +91,17 @@ public class ORCCertificatesCollectionJSON extends AbstractORCCertificatesCollec
|
||||
/**
|
||||
* Returns an {@link ORCCertificateImpl} object for a given {@link String} key. If there is no map value for the
|
||||
* given key, the method returns {@link null}.
|
||||
*
|
||||
* @param certificateId
|
||||
* internally, the ID is "canonicalized" by removing all whitespace from it, so, e.g., "FIN11826L11826"
|
||||
* is considered equivalent to "FIN11826 L11826". This helps iron out some subtle differences in how RMS
|
||||
* files, JSON files and XML-based search results represent certificate IDs.
|
||||
*/
|
||||
@Override
|
||||
public ORCCertificate getCertificateById(String certificateId) {
|
||||
String refNo = null;
|
||||
String natAuth = null;
|
||||
String fileId = null;
|
||||
String boatName = null;
|
||||
String boatclass = null;
|
||||
Distance length = null;
|
||||
@@ -105,165 +116,171 @@ public class ORCCertificatesCollectionJSON extends AbstractORCCertificatesCollec
|
||||
final Map<Double, Speed> trueWindSpeedMap = new TreeMap<Double,Speed>(); // Using TreeMap implementation to save the TrueWindSpeed
|
||||
// so that it first sorts the entries as well as avoids duplicates
|
||||
final Map<Double, Bearing> trueWindAngleMap = new TreeMap<Double,Bearing>(); // Same like trueWindSpeedMap
|
||||
final JSONObject object = certificateJsonObjectsByCertificateId.get(certificateId);
|
||||
final JSONObject object = certificateJsonObjectsByCertificateId.get(canonicalizeId(certificateId));
|
||||
final ORCCertificate result;
|
||||
if (object == null) {
|
||||
// TODO Throw Exception for certificate by id not found. InvalidArgumentException?
|
||||
return null;
|
||||
}
|
||||
String sailNumber = null;
|
||||
for (Entry<Object, Object> entry : object.entrySet()) {
|
||||
switch ((String) entry.getKey()) {
|
||||
case SAIL_NO:
|
||||
sailNumber = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case LOA:
|
||||
length = new MeterDistance(((Number) entry.getValue()).doubleValue());
|
||||
break;
|
||||
case YACHT_NAME:
|
||||
boatName = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case CLASS:
|
||||
boatclass = (String) entry.getValue();
|
||||
break;
|
||||
case GPH2:
|
||||
gph = new SecondsDurationImpl(((Number) entry.getValue()).doubleValue());
|
||||
break;
|
||||
case CDL2:
|
||||
cdl = ((Number) entry.getValue()).doubleValue();
|
||||
break;
|
||||
case ISSUE_DATE:
|
||||
Date date = DatatypeConverter.parseDateTime((String) entry.getValue()).getTime();
|
||||
issueDate = new MillisecondsTimePoint(date);
|
||||
break;
|
||||
case ALLOWANCES:
|
||||
final JSONObject allowances = (JSONObject) object.get(ALLOWANCES);
|
||||
// calculating the TWA and TWS before calculating the other dependent values in allowances object
|
||||
final Object windSpeedsObject = allowances.get(WIND_SPEEDS);
|
||||
if (windSpeedsObject != null) {
|
||||
final JSONArray twsArray = (JSONArray) windSpeedsObject;
|
||||
for (final Object twsObject : twsArray) {
|
||||
Double twsValue = ((Number) twsObject).doubleValue();
|
||||
trueWindSpeedMap.put(twsValue, new KnotSpeedImpl(twsValue));
|
||||
result = null;
|
||||
} else {
|
||||
String sailNumber = null;
|
||||
for (Entry<Object, Object> entry : object.entrySet()) {
|
||||
switch ((String) entry.getKey()) {
|
||||
case REFERENCE_NUMBER:
|
||||
refNo = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case NAT_AUTH:
|
||||
natAuth = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case BIN:
|
||||
fileId = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case SAIL_NO:
|
||||
sailNumber = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case LOA:
|
||||
length = new MeterDistance(((Number) entry.getValue()).doubleValue());
|
||||
break;
|
||||
case YACHT_NAME:
|
||||
boatName = entry.getValue() == null ? null : entry.getValue().toString();
|
||||
break;
|
||||
case CLASS:
|
||||
boatclass = (String) entry.getValue();
|
||||
break;
|
||||
case GPH2:
|
||||
gph = new SecondsDurationImpl(((Number) entry.getValue()).doubleValue());
|
||||
break;
|
||||
case CDL2:
|
||||
cdl = ((Number) entry.getValue()).doubleValue();
|
||||
break;
|
||||
case ISSUE_DATE:
|
||||
Date date = DatatypeConverter.parseDateTime((String) entry.getValue()).getTime();
|
||||
issueDate = new MillisecondsTimePoint(date);
|
||||
break;
|
||||
case ALLOWANCES:
|
||||
final JSONObject allowances = (JSONObject) object.get(ALLOWANCES);
|
||||
// calculating the TWA and TWS before calculating the other dependent values in allowances object
|
||||
final Object windSpeedsObject = allowances.get(WIND_SPEEDS);
|
||||
if (windSpeedsObject != null) {
|
||||
final JSONArray twsArray = (JSONArray) windSpeedsObject;
|
||||
for (final Object twsObject : twsArray) {
|
||||
Double twsValue = ((Number) twsObject).doubleValue();
|
||||
trueWindSpeedMap.put(twsValue, new KnotSpeedImpl(twsValue));
|
||||
}
|
||||
} else {
|
||||
for (Speed speed : ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS) {
|
||||
trueWindSpeedMap.put(speed.getKnots(), speed);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (Speed speed : ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS) {
|
||||
trueWindSpeedMap.put(speed.getKnots(), speed);
|
||||
final Double [] trueWindSpeedArray = new Double[trueWindSpeedMap.size()];
|
||||
trueWindSpeedMap.keySet().toArray(trueWindSpeedArray);
|
||||
for (final Object aKey : allowances.keySet()) {
|
||||
String keyString = (String) aKey;
|
||||
final Matcher matcher = twaPattern.matcher(keyString);
|
||||
if (matcher.lookingAt()) {
|
||||
final JSONArray array = (JSONArray) allowances.get(keyString);
|
||||
final Map<Speed, Duration> twsMap = new HashMap<>();
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
final Double allowanceValue = ((Number) array.get(i)).doubleValue();
|
||||
twsMap.put(trueWindSpeedMap.get(trueWindSpeedArray[i]), new SecondsDurationImpl(allowanceValue));
|
||||
}
|
||||
final Double trueWindAngleValue = Double.parseDouble(matcher.group(1));
|
||||
trueWindAngleMap.put(trueWindAngleValue, new DegreeBearingImpl(trueWindAngleValue));
|
||||
allowanceDurationsPerTrueWindAngleAndSpeed.put(trueWindAngleMap.get(trueWindAngleValue), twsMap);
|
||||
}
|
||||
}
|
||||
// Now read the various allowances, assuming we find values for the TWS "bins" identified above
|
||||
for (final Object aKey : allowances.keySet()) {
|
||||
final JSONArray array = (JSONArray) allowances.get(aKey);
|
||||
if (((String) aKey).equals(BEAT_ANGLE)) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
beatAngles.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new DegreeBearingImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (((String) aKey).equals(GYBE_ANGLE)) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
gybeAngles.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new DegreeBearingImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Map<Speed, Duration> twsMap = new HashMap<>();
|
||||
// ignore true wind angles key
|
||||
if (!twaPattern.matcher((String) aKey).lookingAt()) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
twsMap.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new SecondsDurationImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
}
|
||||
switch ((String) aKey) {
|
||||
case BEAT:
|
||||
case RUN:
|
||||
predefinedAllowanceDurationsPerTrueWindSpeed.put((String) aKey, twsMap);
|
||||
break;
|
||||
default:
|
||||
predefinedAllowanceDurationsPerTrueWindSpeed.put((String) aKey, twsMap);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
final Double [] trueWindSpeedArray = new Double[trueWindSpeedMap.size()];
|
||||
trueWindSpeedMap.keySet().toArray(trueWindSpeedArray);
|
||||
for (final Object aKey : allowances.keySet()) {
|
||||
String keyString = (String) aKey;
|
||||
final Matcher matcher = twaPattern.matcher(keyString);
|
||||
if (matcher.lookingAt()) {
|
||||
final JSONArray array = (JSONArray) allowances.get(keyString);
|
||||
final Map<Speed, Duration> twsMap = new HashMap<>();
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
final Double allowanceValue = ((Number) array.get(i)).doubleValue();
|
||||
twsMap.put(trueWindSpeedMap.get(trueWindSpeedArray[i]), new SecondsDurationImpl(allowanceValue));
|
||||
}
|
||||
final Double trueWindAngleValue = Double.parseDouble(matcher.group(1));
|
||||
trueWindAngleMap.put(trueWindAngleValue, new DegreeBearingImpl(trueWindAngleValue));
|
||||
allowanceDurationsPerTrueWindAngleAndSpeed.put(trueWindAngleMap.get(trueWindAngleValue), twsMap);
|
||||
}
|
||||
}
|
||||
// Now read the various allowances, assuming we find values for the TWS "bins" identified above
|
||||
for (final Object aKey : allowances.keySet()) {
|
||||
final JSONArray array = (JSONArray) allowances.get(aKey);
|
||||
if (((String) aKey).equals(BEAT_ANGLE)) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
beatAngles.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new DegreeBearingImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (((String) aKey).equals(GYBE_ANGLE)) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
gybeAngles.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new DegreeBearingImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Map<Speed, Duration> twsMap = new HashMap<>();
|
||||
//ignore true wind angles key
|
||||
if (!twaPattern.matcher((String) aKey).lookingAt()) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
twsMap.put(new KnotSpeedImpl(trueWindSpeedArray[i]),
|
||||
new SecondsDurationImpl(((Number) array.get(i)).doubleValue()));
|
||||
}
|
||||
}
|
||||
switch ((String) aKey) {
|
||||
case BEAT:
|
||||
case RUN:
|
||||
predefinedAllowanceDurationsPerTrueWindSpeed.put((String) aKey, twsMap);
|
||||
break;
|
||||
default:
|
||||
predefinedAllowanceDurationsPerTrueWindSpeed.put((String) aKey, twsMap);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
trueWindSpeedMap.values().forEach(tws -> velocityPredictionPerTrueWindSpeedAndAngle.put(tws, new HashMap<>()));
|
||||
for (final Bearing keyTWA : allowanceDurationsPerTrueWindAngleAndSpeed.keySet()) {
|
||||
for (final Speed keyTWS : allowanceDurationsPerTrueWindAngleAndSpeed.get(keyTWA).keySet()) {
|
||||
velocityPredictionPerTrueWindSpeedAndAngle.get(keyTWS).put(keyTWA, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(allowanceDurationsPerTrueWindAngleAndSpeed.get(keyTWA).get(keyTWS)));
|
||||
trueWindSpeedMap.values().forEach(tws -> velocityPredictionPerTrueWindSpeedAndAngle.put(tws, new HashMap<>()));
|
||||
for (final Bearing keyTWA : allowanceDurationsPerTrueWindAngleAndSpeed.keySet()) {
|
||||
for (final Speed keyTWS : allowanceDurationsPerTrueWindAngleAndSpeed.get(keyTWA).keySet()) {
|
||||
velocityPredictionPerTrueWindSpeedAndAngle.get(keyTWS).put(keyTWA, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(allowanceDurationsPerTrueWindAngleAndSpeed.get(keyTWA).get(keyTWS)));
|
||||
}
|
||||
}
|
||||
final Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> beatAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> runAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> windwardLeewardSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> longDistanceSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> circularRandomSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> nonSpinnakerSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
for (final Speed tws : velocityPredictionPerTrueWindSpeedAndAngle.keySet()) {
|
||||
beatVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(BEAT).get(tws)));
|
||||
beatAllowancePerTrueWindSpeed.put(tws, predefinedAllowanceDurationsPerTrueWindSpeed.get(BEAT).get(tws));
|
||||
runVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(RUN).get(tws)));
|
||||
runAllowancePerTrueWindSpeed.put(tws, predefinedAllowanceDurationsPerTrueWindSpeed.get(RUN).get(tws));
|
||||
windwardLeewardSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(WINDWARD_LEEWARD).get(tws)));
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(LONG_DISTANCE).get(tws)));
|
||||
circularRandomSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(CIRCULAR_RANDOM).get(tws)));
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(NON_SPINNAKER).get(tws)));
|
||||
}
|
||||
final Bearing[] dynamicAllowancesTrueWindAngles = trueWindAngleMap.values().toArray(new Bearing[trueWindAngleMap.values().size()]);
|
||||
final Speed[] dynamicAllowancesTrueWindSpeeds = trueWindSpeedMap.values().toArray(new Speed[trueWindSpeedMap.values().size()]);
|
||||
// replace array by the default arrays if they match; this will save the space for the dynamically-parsed arrays
|
||||
result = new ORCCertificateImpl(
|
||||
Arrays.equals(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS, dynamicAllowancesTrueWindSpeeds)
|
||||
? ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS
|
||||
: dynamicAllowancesTrueWindSpeeds,
|
||||
Arrays.equals(ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES, dynamicAllowancesTrueWindAngles)
|
||||
? ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES
|
||||
: dynamicAllowancesTrueWindAngles,
|
||||
refNo, fileId, sailNumber, boatName, boatclass, length, gph, cdl,
|
||||
issueDate, CountryCodeFactory.INSTANCE.getFromThreeLetterIOCName(natAuth),
|
||||
velocityPredictionPerTrueWindSpeedAndAngle, beatAngles, beatVMGPredictionPerTrueWindSpeed,
|
||||
beatAllowancePerTrueWindSpeed, gybeAngles, runVMGPredictionPerTrueWindSpeed,
|
||||
runAllowancePerTrueWindSpeed, windwardLeewardSpeedPredictionPerTrueWindSpeed,
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed, circularRandomSpeedPredictionPerTrueWindSpeed,
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
}
|
||||
final Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> beatAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> runAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> windwardLeewardSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> longDistanceSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> circularRandomSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> nonSpinnakerSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
for (final Speed tws : velocityPredictionPerTrueWindSpeedAndAngle.keySet()) {
|
||||
beatVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(BEAT).get(tws)));
|
||||
beatAllowancePerTrueWindSpeed.put(tws, predefinedAllowanceDurationsPerTrueWindSpeed.get(BEAT).get(tws));
|
||||
runVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(RUN).get(tws)));
|
||||
runAllowancePerTrueWindSpeed.put(tws, predefinedAllowanceDurationsPerTrueWindSpeed.get(RUN).get(tws));
|
||||
windwardLeewardSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(WINDWARD_LEEWARD).get(tws)));
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(LONG_DISTANCE).get(tws)));
|
||||
circularRandomSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(CIRCULAR_RANDOM).get(tws)));
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE
|
||||
.inTime(predefinedAllowanceDurationsPerTrueWindSpeed.get(NON_SPINNAKER).get(tws)));
|
||||
}
|
||||
final Bearing[] dynamicAllowancesTrueWindAngles = trueWindAngleMap.values().toArray(new Bearing[trueWindAngleMap.values().size()]);
|
||||
final Speed[] dynamicAllowancesTrueWindSpeeds = trueWindSpeedMap.values().toArray(new Speed[trueWindSpeedMap.values().size()]);
|
||||
// replace array by the default arrays if they match; this will save the space for the dynamically-parsed arrays
|
||||
return new ORCCertificateImpl(
|
||||
Arrays.equals(ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS, dynamicAllowancesTrueWindSpeeds)
|
||||
? ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS
|
||||
: dynamicAllowancesTrueWindSpeeds,
|
||||
Arrays.equals(ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES, dynamicAllowancesTrueWindAngles)
|
||||
? ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES
|
||||
: dynamicAllowancesTrueWindAngles,
|
||||
getId(object), sailNumber, boatName, boatclass, length, gph, cdl, issueDate,
|
||||
velocityPredictionPerTrueWindSpeedAndAngle, beatAngles, beatVMGPredictionPerTrueWindSpeed,
|
||||
beatAllowancePerTrueWindSpeed, gybeAngles, runVMGPredictionPerTrueWindSpeed,
|
||||
runAllowancePerTrueWindSpeed, windwardLeewardSpeedPredictionPerTrueWindSpeed,
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed, circularRandomSpeedPredictionPerTrueWindSpeed,
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
return result;
|
||||
}
|
||||
|
||||
private String getId(JSONObject certificateAsJson) {
|
||||
return getIdFromFields(certificateAsJson.get(NAT_AUTH).toString(),
|
||||
certificateAsJson.get(CERT_NO) == null ? EMPTY_CERT_NO : certificateAsJson.get(CERT_NO).toString(),
|
||||
certificateAsJson.get(BIN).toString());
|
||||
}
|
||||
|
||||
private String getIdFromFields(final String natAuth, final String certNo, final String bin) {
|
||||
return natAuth + certNo + bin;
|
||||
return certificateAsJson.get(REFERENCE_NUMBER).toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+98
-65
@@ -14,10 +14,13 @@ import com.sap.sailing.domain.common.impl.MeterDistance;
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.CountryCodeFactory;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
import com.sap.sse.common.TimePoint;
|
||||
import com.sap.sse.common.Util.Triple;
|
||||
import com.sap.sse.common.impl.DegreeBearingImpl;
|
||||
import com.sap.sse.common.impl.MillisecondsTimePoint;
|
||||
import com.sap.sse.common.impl.SecondsDurationImpl;
|
||||
@@ -52,6 +55,7 @@ public class ORCCertificatesCollectionRMS extends AbstractORCCertificatesCollect
|
||||
private static final String SAILNUMBER = "SAILNUMB";
|
||||
private static final String BOATCLASS = "TYPE";
|
||||
static final String ISSUEDATE = "DD_MM_yyYY";
|
||||
static final String LOA = "LOA";
|
||||
private static final String ISSUETIME = "HH:MM:SS";
|
||||
private static final String RUN_ALLOWANCE = "D";
|
||||
private static final String RUN_ANGLE = "DA";
|
||||
@@ -61,17 +65,29 @@ public class ORCCertificatesCollectionRMS extends AbstractORCCertificatesCollect
|
||||
private static final String LONG_DISTANCE = "OC";
|
||||
private static final String CIRCULAR_RANDOM = "CR";
|
||||
private static final String NON_SPINNAKER = "NSP";
|
||||
private static final String NATCERTN_FILE_ID = "NATCERTN.FILE_ID";
|
||||
private static final String ISSUING_NATIONAL_AUTHORITY = "NAT";
|
||||
private static final String CERTIFICATE_NUMBER = "CERTN";
|
||||
private static final String NATCERTN = ISSUING_NATIONAL_AUTHORITY+CERTIFICATE_NUMBER;
|
||||
private static final String FILE_ID = "FILE_ID";
|
||||
private static final String NATCERTN_FILE_ID = NATCERTN+"."+FILE_ID;
|
||||
static final String REFERENCE_NUMBER = "ReferenceNo";
|
||||
private static final DateFormat timestampFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ssZ");
|
||||
|
||||
/**
|
||||
* Keys are canonicalized through {@link #canonicalizeId(String)}.
|
||||
*/
|
||||
private final Map<String, Map<String, String>> certificateValuesByCertificateId;
|
||||
|
||||
|
||||
public class ORCCertificateValues {
|
||||
/**
|
||||
* Canonicalized through {@link AbstractORCCertificatesCollection#canonicalizeId(String)}
|
||||
*/
|
||||
private final String certificateId;
|
||||
|
||||
public ORCCertificateValues(String certificateId) {
|
||||
super();
|
||||
this.certificateId = certificateId;
|
||||
this.certificateId = canonicalizeId(certificateId);
|
||||
}
|
||||
|
||||
public String getValue(String columnName) {
|
||||
@@ -82,7 +98,7 @@ public class ORCCertificatesCollectionRMS extends AbstractORCCertificatesCollect
|
||||
public ORCCertificatesCollectionRMS(Map<String, Map<String, String>> certificateValuesByCertificateId) throws IOException {
|
||||
this.certificateValuesByCertificateId = new HashMap<>();
|
||||
for (final Entry<String, Map<String, String>> e : certificateValuesByCertificateId.entrySet()) {
|
||||
this.certificateValuesByCertificateId.put(e.getKey(), e.getValue());
|
||||
this.certificateValuesByCertificateId.put(canonicalizeId(e.getKey()), e.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,74 +107,91 @@ public class ORCCertificatesCollectionRMS extends AbstractORCCertificatesCollect
|
||||
}
|
||||
|
||||
private ORCCertificateValues getValuesForCertificateId(String certificateId) {
|
||||
return certificateValuesByCertificateId.containsKey(certificateId) ? new ORCCertificateValues(certificateId) : null;
|
||||
return certificateValuesByCertificateId.containsKey(canonicalizeId(certificateId)) ? new ORCCertificateValues(certificateId) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ORCCertificate getCertificateById(String certificateId) {
|
||||
ORCCertificateValues certificateValues = getValuesForCertificateId(certificateId);
|
||||
final String sailNumber = certificateValues.getValue(SAILNUMBER);
|
||||
final String boatclass = certificateValues.getValue(BOATCLASS);
|
||||
final String boatName = certificateValues.getValue(BOATNAME);
|
||||
final Distance length = new MeterDistance(Double.parseDouble(certificateValues.getValue(LENGTH)));
|
||||
final Duration gph = new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(GPH)));
|
||||
final Double cdl = Double.parseDouble(certificateValues.getValue(CDL));
|
||||
String dateString = certificateValues.getValue(ISSUEDATE);
|
||||
String timeString = certificateValues.getValue(ISSUETIME);
|
||||
TimePoint issueDate;
|
||||
try {
|
||||
issueDate = new MillisecondsTimePoint(timestampFormat.parse(dateString+" "+timeString+"+0000")); // assume UTC
|
||||
} catch (ParseException e) {
|
||||
issueDate = null;
|
||||
}
|
||||
final Map<Speed, Map<Bearing, Speed>> velocityPredictionsPerTrueWindSpeedAndAngle = new HashMap<>();
|
||||
final Map<Speed, Bearing> beatAngles = new HashMap<>();
|
||||
final Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> beatAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Bearing> runAngles = new HashMap<>();
|
||||
final Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> runAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> windwardLeewardSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> longDistanceSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> circularRandomSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> nonSpinnakerSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
for (Speed tws : ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS) {
|
||||
String windSpeed = Integer.toString((int) tws.getKnots());
|
||||
String beatAngleKey = BEAT_ANGLE + windSpeed;
|
||||
String beatAllowanceKey = BEAT_ALLOWANCE + windSpeed;
|
||||
String runAngleKey = RUN_ANGLE + windSpeed;
|
||||
String runAllowanceKey = RUN_ALLOWANCE + windSpeed;
|
||||
String windwardLeewardKey = WINDWARD_LEEWARD + windSpeed;
|
||||
String longDistanceKey = LONG_DISTANCE + windSpeed;
|
||||
String circularRandomKey = CIRCULAR_RANDOM + windSpeed;
|
||||
String nonSpinnakerKey = NON_SPINNAKER + windSpeed;
|
||||
beatAngles.put(tws, new DegreeBearingImpl(Double.parseDouble(certificateValues.getValue(beatAngleKey))));
|
||||
beatAllowancePerTrueWindSpeed.put(tws, new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(beatAllowanceKey))));
|
||||
beatVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(beatAllowancePerTrueWindSpeed.get(tws)));
|
||||
runAngles.put(tws, new DegreeBearingImpl(Double.parseDouble(certificateValues.getValue(runAngleKey))));
|
||||
runAllowancePerTrueWindSpeed.put(tws, new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(runAllowanceKey))));
|
||||
runVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(runAllowancePerTrueWindSpeed.get(tws)));
|
||||
windwardLeewardSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(windwardLeewardKey)))));
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(longDistanceKey)))));
|
||||
circularRandomSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(circularRandomKey)))));
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(nonSpinnakerKey)))));
|
||||
Map<Bearing, Speed> velocityPredictionPerTrueWindAngle = new HashMap<>();
|
||||
for (Bearing twa : ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES ) {
|
||||
String twaCoursesKey = TWA_COURSES + Integer.toString((int) twa.getDegrees()) + windSpeed;
|
||||
velocityPredictionPerTrueWindAngle.put(twa, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(twaCoursesKey)))));
|
||||
final ORCCertificateValues certificateValues = getValuesForCertificateId(certificateId);
|
||||
final ORCCertificate result;
|
||||
if (certificateValues == null) {
|
||||
result = null;
|
||||
} else {
|
||||
final String refNo = certificateValues.getValue(REFERENCE_NUMBER);
|
||||
final String sailNumber = certificateValues.getValue(SAILNUMBER);
|
||||
final String boatclass = certificateValues.getValue(BOATCLASS);
|
||||
final String boatName = certificateValues.getValue(BOATNAME);
|
||||
final Distance length = new MeterDistance(Double.parseDouble(certificateValues.getValue(LENGTH)));
|
||||
final Duration gph = new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(GPH)));
|
||||
final Double cdl = Double.parseDouble(certificateValues.getValue(CDL));
|
||||
String dateString = certificateValues.getValue(ISSUEDATE);
|
||||
String timeString = certificateValues.getValue(ISSUETIME);
|
||||
TimePoint issueDate;
|
||||
try {
|
||||
issueDate = new MillisecondsTimePoint(timestampFormat.parse(dateString+" "+timeString+"+0000")); // assume UTC
|
||||
} catch (ParseException e) {
|
||||
issueDate = null;
|
||||
}
|
||||
velocityPredictionsPerTrueWindSpeedAndAngle.put(tws, velocityPredictionPerTrueWindAngle);
|
||||
final Map<Speed, Map<Bearing, Speed>> velocityPredictionsPerTrueWindSpeedAndAngle = new HashMap<>();
|
||||
final Map<Speed, Bearing> beatAngles = new HashMap<>();
|
||||
final Map<Speed, Speed> beatVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> beatAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Bearing> runAngles = new HashMap<>();
|
||||
final Map<Speed, Speed> runVMGPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Duration> runAllowancePerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> windwardLeewardSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> longDistanceSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> circularRandomSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
final Map<Speed, Speed> nonSpinnakerSpeedPredictionPerTrueWindSpeed = new HashMap<>();
|
||||
for (Speed tws : ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS) {
|
||||
String windSpeed = Integer.toString((int) tws.getKnots());
|
||||
String beatAngleKey = BEAT_ANGLE + windSpeed;
|
||||
String beatAllowanceKey = BEAT_ALLOWANCE + windSpeed;
|
||||
String runAngleKey = RUN_ANGLE + windSpeed;
|
||||
String runAllowanceKey = RUN_ALLOWANCE + windSpeed;
|
||||
String windwardLeewardKey = WINDWARD_LEEWARD + windSpeed;
|
||||
String longDistanceKey = LONG_DISTANCE + windSpeed;
|
||||
String circularRandomKey = CIRCULAR_RANDOM + windSpeed;
|
||||
String nonSpinnakerKey = NON_SPINNAKER + windSpeed;
|
||||
beatAngles.put(tws, new DegreeBearingImpl(Double.parseDouble(certificateValues.getValue(beatAngleKey))));
|
||||
beatAllowancePerTrueWindSpeed.put(tws, new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(beatAllowanceKey))));
|
||||
beatVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(beatAllowancePerTrueWindSpeed.get(tws)));
|
||||
runAngles.put(tws, new DegreeBearingImpl(Double.parseDouble(certificateValues.getValue(runAngleKey))));
|
||||
runAllowancePerTrueWindSpeed.put(tws, new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(runAllowanceKey))));
|
||||
runVMGPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(runAllowancePerTrueWindSpeed.get(tws)));
|
||||
windwardLeewardSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(windwardLeewardKey)))));
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(longDistanceKey)))));
|
||||
circularRandomSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(circularRandomKey)))));
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed.put(tws, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(nonSpinnakerKey)))));
|
||||
Map<Bearing, Speed> velocityPredictionPerTrueWindAngle = new HashMap<>();
|
||||
for (Bearing twa : ORCCertificate.ALLOWANCES_TRUE_WIND_ANGLES ) {
|
||||
String twaCoursesKey = TWA_COURSES + Integer.toString((int) twa.getDegrees()) + windSpeed;
|
||||
velocityPredictionPerTrueWindAngle.put(twa, ORCCertificateImpl.NAUTICAL_MILE.inTime(
|
||||
new SecondsDurationImpl(Double.parseDouble(certificateValues.getValue(twaCoursesKey)))));
|
||||
}
|
||||
velocityPredictionsPerTrueWindSpeedAndAngle.put(tws, velocityPredictionPerTrueWindAngle);
|
||||
}
|
||||
final Triple<CountryCode, String, String> natCertNoFileId = getIssuingNationalityCertificateNumberAndFileId(certificateValues.getValue(NATCERTN_FILE_ID));
|
||||
result = new ORCCertificateImpl(refNo, natCertNoFileId.getC(), sailNumber, boatName, boatclass, length, gph,
|
||||
cdl, issueDate, natCertNoFileId.getA(), velocityPredictionsPerTrueWindSpeedAndAngle, beatAngles,
|
||||
beatVMGPredictionPerTrueWindSpeed, beatAllowancePerTrueWindSpeed, runAngles, runVMGPredictionPerTrueWindSpeed,
|
||||
runAllowancePerTrueWindSpeed, windwardLeewardSpeedPredictionPerTrueWindSpeed,
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed, circularRandomSpeedPredictionPerTrueWindSpeed,
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
}
|
||||
return new ORCCertificateImpl(certificateValues.getValue(NATCERTN_FILE_ID), sailNumber, boatName, boatclass,
|
||||
length, gph, cdl, issueDate, velocityPredictionsPerTrueWindSpeedAndAngle, beatAngles, beatVMGPredictionPerTrueWindSpeed,
|
||||
beatAllowancePerTrueWindSpeed, runAngles, runVMGPredictionPerTrueWindSpeed,
|
||||
runAllowancePerTrueWindSpeed, windwardLeewardSpeedPredictionPerTrueWindSpeed,
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed, circularRandomSpeedPredictionPerTrueWindSpeed, nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Triple<CountryCode, String, String> getIssuingNationalityCertificateNumberAndFileId(String natCertFileId) {
|
||||
final CountryCode nationalityIOCCode = CountryCodeFactory.INSTANCE
|
||||
.getFromThreeLetterIOCName(natCertFileId.substring(0, ISSUING_NATIONAL_AUTHORITY.length()));
|
||||
final String certNo = natCertFileId.substring(ISSUING_NATIONAL_AUTHORITY.length(), ISSUING_NATIONAL_AUTHORITY.length()+CERTIFICATE_NUMBER.length()).trim();
|
||||
final String fileId = natCertFileId.substring(NATCERTN.length()+".".length()).trim();
|
||||
return new Triple<>(nationalityIOCCode, certNo, fileId);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+75
-37
@@ -5,7 +5,6 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
@@ -13,16 +12,27 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sse.common.Util.Pair;
|
||||
|
||||
/**
|
||||
* Represents a file in format {@code .rms} which is a simple ASCII file format, column-based, with fixed-width columns,
|
||||
* defined by a header line that defines the names and for the first columns up to the column labeled
|
||||
* {@link #NAME_OF_LAST_LEFT_ALIGNED_COLUMN_HEADER} also the width of the columns. The header uses column names that do
|
||||
* not contain spaces, separated by one or more spaces. For the columns up to and including the column
|
||||
* {@link #NAME_OF_LAST_LEFT_ALIGNED_COLUMN_HEADER} the column names are formatted left-aligned. For subsequent columns
|
||||
* which contain all numeric values without spaces the column names may also be centered. For those columns parsing can
|
||||
* simply split by space characters.
|
||||
* <p>
|
||||
* Represents a file in format {@code .rms} which is a strange ASCII file format, column-based, with fixed-width columns,
|
||||
* "defined" by a header line that gives the names and for the first columns up to the column labeled
|
||||
* {@link #NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD} also the width of the columns. Starting with the column following
|
||||
* {@link #NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD}, field names may be "centered" over their character columns; for example,
|
||||
* the "LOA" field is represented as " LOA " with the last space marking the separating space to the next column,
|
||||
* and the values are placed somewhere within those first six "payload" columns; they may appear centered, left-aligned
|
||||
* or right-aligned, and there doesn't seem to be a recognizable pattern to it.<p>
|
||||
*
|
||||
* To make matters worse, some columns do not contain values at all. In this case, no alternation between space and non-space
|
||||
* characters can be used to determine field boundaries. At least, after the {@link #NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD} no
|
||||
* columns can contain space characters unless they are entirely empty. And in all cases do those column values after
|
||||
* {@link #NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD} have a non-space character in at least one of the columns used by the corresponding
|
||||
* field name in the header, unless the field value is left blank.<p>
|
||||
*
|
||||
* Therefore, a good strategy seems to look for non-space characters in the columns used for the field name in the header.
|
||||
* If none are found, the field is assumed to be left empty. Otherwise, from the first non-blank character found in the columns
|
||||
* used by the field name in the header, all characters to the left and to the right that are no space are added to the
|
||||
* field value.<p>
|
||||
*
|
||||
* The result of successfully parsing a {@code .rms} file is a map keyed by the sailnumber, with values being
|
||||
* equal-sized maps from the column names to the {@link String} values. Additionally, the column names corresponding to
|
||||
@@ -35,19 +45,18 @@ import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
*/
|
||||
|
||||
public class ORCCertificatesRmsImporter extends AbstractORCCertificatesImporter {
|
||||
private static final String NAME_OF_LAST_LEFT_ALIGNED_COLUMN_HEADER = ORCCertificatesCollectionRMS.ISSUEDATE;
|
||||
private static final String NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD = ORCCertificatesCollectionRMS.ISSUEDATE;
|
||||
|
||||
public ORCCertificatesCollectionRMS read(Reader reader) throws IOException {
|
||||
final BufferedReader br = new BufferedReader(reader);
|
||||
final LinkedHashMap<String, Integer> columnNamesAndWidths = readColumnWidthsFromFirstLine(br.readLine());
|
||||
final Iterator<String> i = columnNamesAndWidths.keySet().iterator();
|
||||
final String certificateIdColumnName = i.next();
|
||||
final String header = br.readLine();
|
||||
final LinkedHashMap<String, Pair<Integer, Integer>> columnNamesAndFieldNameStartInHeader = readColumnHeaderFieldNameStartColumnsAndLengthFromFirstLine(header);
|
||||
final Map<String, Map<String, String>> certificateValuesByCertificateId = new HashMap<>();
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (!line.trim().isEmpty()) {
|
||||
final Map<String, String> parsedLine = parseLine(line, columnNamesAndWidths);
|
||||
certificateValuesByCertificateId.put(parsedLine.get(certificateIdColumnName), parsedLine);
|
||||
final Map<String, String> parsedLine = parseLine(line, columnNamesAndFieldNameStartInHeader);
|
||||
certificateValuesByCertificateId.put(parsedLine.get(ORCCertificatesCollectionRMS.REFERENCE_NUMBER), parsedLine);
|
||||
}
|
||||
}
|
||||
return new ORCCertificatesCollectionRMS(certificateValuesByCertificateId);
|
||||
@@ -57,41 +66,70 @@ public class ORCCertificatesRmsImporter extends AbstractORCCertificatesImporter
|
||||
return read(getReaderForInputStream(in));
|
||||
}
|
||||
|
||||
private Map<String, String> parseLine(final String line, LinkedHashMap<String, Integer> columnNamesAndWidths) {
|
||||
assert columnNamesAndWidths != null;
|
||||
private Map<String, String> parseLine(final String line, LinkedHashMap<String, Pair<Integer, Integer>> columnNamesAndFieldNameStartAndLengthInHeader) {
|
||||
assert columnNamesAndFieldNameStartAndLengthInHeader != null;
|
||||
final Map<String, String> result = new LinkedHashMap<>();
|
||||
int start=0;
|
||||
boolean splitBySpaceMode = false; // start using column names; switch to splitting by spaces when NAME_OF_LAST_LEFT_ALIGNED_COLUMN_HEADER has been found
|
||||
for (final Entry<String, Integer> columnNameAndWidth : columnNamesAndWidths.entrySet()) {
|
||||
boolean leftAligned = true;
|
||||
for (final Entry<String, Pair<Integer, Integer>> columnNameAndFieldNameStartInHeader : columnNamesAndFieldNameStartAndLengthInHeader.entrySet()) {
|
||||
final int start = columnNameAndFieldNameStartInHeader.getValue().getA();
|
||||
final int end;
|
||||
if (splitBySpaceMode) {
|
||||
boolean foundSpace = false;
|
||||
int i;
|
||||
for (i=start; i<line.length() && (!foundSpace || line.charAt(i) == ' '); i++) {
|
||||
if (!foundSpace) {
|
||||
foundSpace = line.charAt(i) == ' ';
|
||||
}
|
||||
}
|
||||
end = i;
|
||||
final String value;
|
||||
if (leftAligned) {
|
||||
end = start+columnNameAndFieldNameStartInHeader.getValue().getB();
|
||||
value = line.substring(start, end).trim();
|
||||
} else {
|
||||
end = start+columnNameAndWidth.getValue();
|
||||
end = start+columnNameAndFieldNameStartInHeader.getKey().length();
|
||||
value = expandFromNonSpaceCharacterInRange(line, start, end);
|
||||
}
|
||||
result.put(columnNameAndWidth.getKey(), line.substring(start, end).trim());
|
||||
if (columnNameAndWidth.getKey().equals(NAME_OF_LAST_LEFT_ALIGNED_COLUMN_HEADER)) {
|
||||
splitBySpaceMode = true;
|
||||
result.put(columnNameAndFieldNameStartInHeader.getKey(), value);
|
||||
if (columnNameAndFieldNameStartInHeader.getKey().equals(NAME_OF_COLUMN_HEADER_WHERE_THINGS_GET_WEIRD)) {
|
||||
leftAligned = false;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private LinkedHashMap<String, Integer> readColumnWidthsFromFirstLine(final String readLine) {
|
||||
final LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
|
||||
/**
|
||||
* If only space characters are found in {@code line} starting at index {@code start} and ending before index {@code end},
|
||||
* the result is {@code null}. Otherwise, starting at any non-space character in the range, expansion to the left and right is
|
||||
* performed, collecting all contiguous non-space characters.
|
||||
*/
|
||||
private String expandFromNonSpaceCharacterInRange(String line, int start, int end) {
|
||||
final String result;
|
||||
if (start >= line.length()) {
|
||||
result = null;
|
||||
} else {
|
||||
int left = start;
|
||||
// search for first non-whitespace from start looking right:
|
||||
while (left<line.length() && left < end && left < line.length() && Character.isWhitespace(line.charAt(left))) {
|
||||
left++;
|
||||
}
|
||||
if (left >= end) {
|
||||
result = null;
|
||||
} else {
|
||||
int right = left+1;
|
||||
// expand left:
|
||||
while (left > 0 && Character.isWhitespace(line.charAt(left-1))) {
|
||||
left--;
|
||||
}
|
||||
// expand right:
|
||||
while (right < line.length() && !Character.isWhitespace(line.charAt(right))) {
|
||||
right++;
|
||||
}
|
||||
result = line.substring(left, right);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private LinkedHashMap<String, Pair<Integer, Integer>> readColumnHeaderFieldNameStartColumnsAndLengthFromFirstLine(final String readLine) {
|
||||
final LinkedHashMap<String, Pair<Integer, Integer>> result = new LinkedHashMap<>();
|
||||
final Pattern p = Pattern.compile("([^ ]+ *)");
|
||||
final Matcher m = p.matcher(readLine);
|
||||
int start = 0;
|
||||
while (m.find(start)) {
|
||||
result.put(m.group(1).trim(), m.group(1).length());
|
||||
final String fieldNameTrimmed = m.group(1).trim();
|
||||
result.put(fieldNameTrimmed, new Pair<>(m.start(1), m.group(1).length()));
|
||||
start += m.group(1).length();
|
||||
}
|
||||
return result;
|
||||
|
||||
+143
-28
@@ -1,10 +1,15 @@
|
||||
package com.sap.sailing.domain.orc.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
@@ -15,6 +20,7 @@ import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Future;
|
||||
@@ -29,6 +35,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.apache.http.HttpMessage;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
@@ -69,10 +76,25 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
private static final NameValuePair ACTION_PARAM = new BasicNameValuePair(ACTION_PARAM_NAME, ACTION_PARAM_VALUE_LIST_CERT);
|
||||
private static final NameValuePair XSLP_PARAM = new BasicNameValuePair(XSLP_PARAM_NAME, XSLP_PARAM_VALUE_LIST_CERT);
|
||||
private static final String SEARCH_URL = "http://data.orc.org/public/WPub.dll";
|
||||
private static final String SINGLE_CERTIFICATE_DOWNLOAD_URL = "http://data.orc.org/public/WPub.dll?action=DownBoatRMS";
|
||||
private static final String ROOT_ELEMENT = "ROOT";
|
||||
private static final String DATA_ELEMENT = "DATA";
|
||||
private static final String ROW_ELEMENT = "ROW";
|
||||
private static final DateFormat isoTimestampFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
private static final String DXT_SUFFIX = ".dxt";
|
||||
|
||||
private static final DateTimeFormatter[] DATE_FORMATTERS =
|
||||
new DateTimeFormatter[] {
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
|
||||
};
|
||||
private static final DateTimeFormatter[] DATE_FORMATTERS_WITH_ZONE =
|
||||
new DateTimeFormatter[] {
|
||||
DateTimeFormatter.ISO_INSTANT,
|
||||
DateTimeFormatter.ISO_DATE_TIME,
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")
|
||||
};
|
||||
|
||||
/**
|
||||
* Hash code and equality as based on {@link #getReferenceNumber() the reference number field} only.
|
||||
@@ -82,6 +104,7 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
*/
|
||||
private static class CertificateHandleImpl implements CertificateHandle {
|
||||
private final CountryCode issuingCountry;
|
||||
private final String fileId;
|
||||
private final String sssid;
|
||||
private final Double gph;
|
||||
private final UUID datInGID;
|
||||
@@ -96,12 +119,15 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
private final Integer certType;
|
||||
private final Boolean isOneDesign;
|
||||
private final Boolean isProvisional;
|
||||
private final Boolean isValid;
|
||||
|
||||
public CertificateHandleImpl(CountryCode issuingCountry, Double gph, String sssid, UUID datInGID,
|
||||
String referenceNumber, String yachtName, String sailNumber, String boatClassName, String designer,
|
||||
String builder, Integer yearBuilt, TimePoint issueDate, Integer certType, Boolean oneDesign, Boolean isProvisional) {
|
||||
public CertificateHandleImpl(CountryCode issuingCountry, String fileId, Double gph, String sssid,
|
||||
UUID datInGID, String referenceNumber, String yachtName, String sailNumber, String boatClassName,
|
||||
String designer, String builder, Integer yearBuilt, TimePoint issueDate, Integer certType,
|
||||
Boolean oneDesign, Boolean isProvisional, Boolean isValid) {
|
||||
super();
|
||||
this.issuingCountry = issuingCountry;
|
||||
this.fileId = fileId;
|
||||
this.gph = gph;
|
||||
this.sssid = sssid;
|
||||
this.datInGID = datInGID;
|
||||
@@ -116,6 +142,7 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
this.certType = certType;
|
||||
this.isOneDesign = oneDesign;
|
||||
this.isProvisional = isProvisional;
|
||||
this.isValid = isValid;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -148,6 +175,11 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
return issuingCountry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFileId() {
|
||||
return fileId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Double getGPH() {
|
||||
return gph;
|
||||
@@ -217,6 +249,11 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
public Boolean isOd() {
|
||||
return isOneDesign;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean isValid() {
|
||||
return isValid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
@@ -224,13 +261,14 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
+ ", datInGID=" + datInGID + ", referenceNumber=" + referenceNumber + ", yachtName=" + yachtName
|
||||
+ ", sailNumber=" + sailNumber + ", boatClassName=" + boatClassName + ", designer=" + designer
|
||||
+ ", builder=" + builder + ", yearBuilt=" + yearBuilt + ", issueDate=" + issueDate + ", certType="
|
||||
+ certType + ", isOneDesign=" + isOneDesign + ", isProvisional=" + isProvisional + "]";
|
||||
+ certType + ", isOneDesign=" + isOneDesign + ", isProvisional=" + isProvisional +
|
||||
", isValid=" + isValid + "]";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterable<CertificateHandle> search(CountryCode issuingCountry, Integer yearOfIssuance, String referenceNumber,
|
||||
String yachtName, String sailNumber, String boatClassName) throws Exception {
|
||||
String yachtName, String sailNumber, String boatClassName, boolean includeInvalid) throws Exception {
|
||||
final Set<ORCPublicCertificateDatabase.CertificateHandle> result = new HashSet<>();
|
||||
final HttpClient client = new SystemDefaultHttpClient();
|
||||
final List<NameValuePair> params = new ArrayList<>();
|
||||
@@ -267,7 +305,11 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
for (int rowNodeIndex=0; rowNodeIndex<rowNodes.getLength(); rowNodeIndex++) {
|
||||
final Node rowNode = rowNodes.item(rowNodeIndex);
|
||||
if (rowNode.getNodeName().equals(ROW_ELEMENT)) {
|
||||
result.add(parseHandle(rowNode));
|
||||
final CertificateHandle certificateHandle = parseHandle(rowNode);
|
||||
// certificates can only be obtained if they are currently valid, so ignore expired ones
|
||||
if (includeInvalid || certificateHandle.isValid()) {
|
||||
result.add(certificateHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -283,6 +325,7 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
private CertificateHandle parseHandle(Node rowNode) throws DOMException, ParseException {
|
||||
assert rowNode.getNodeName().equals(ROW_ELEMENT);
|
||||
CountryCode issuingCountry = null;
|
||||
String fileId = null;
|
||||
String sssid = null;
|
||||
Double gph = null;
|
||||
UUID datInGID = null;
|
||||
@@ -297,6 +340,7 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
TimePoint issueDate = null;
|
||||
Boolean isOneDesign = null;
|
||||
Boolean isProvisional = null;
|
||||
Boolean isValid = null;
|
||||
for (int i=0; i<rowNode.getChildNodes().getLength(); i++) {
|
||||
final Node child = rowNode.getChildNodes().item(i);
|
||||
switch (child.getNodeName()) {
|
||||
@@ -333,6 +377,12 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
case "dxtDate":
|
||||
issueDate = new MillisecondsTimePoint(parseDate(child.getTextContent())); // assume UTC
|
||||
break;
|
||||
case "dxtName":
|
||||
final String fileIdWithOptionalDxtSuffix = child.getTextContent();
|
||||
fileId = fileIdWithOptionalDxtSuffix.toLowerCase().endsWith(DXT_SUFFIX) ?
|
||||
fileIdWithOptionalDxtSuffix.substring(0, fileIdWithOptionalDxtSuffix.length()-DXT_SUFFIX.length()) :
|
||||
fileIdWithOptionalDxtSuffix;
|
||||
break;
|
||||
case "CertType":
|
||||
certType = Integer.valueOf(child.getTextContent().trim());
|
||||
break;
|
||||
@@ -345,39 +395,104 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
case "Provisional":
|
||||
isProvisional = Boolean.valueOf(child.getTextContent());
|
||||
break;
|
||||
case "CanSelect":
|
||||
isValid = Boolean.valueOf(child.getTextContent());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new CertificateHandleImpl(issuingCountry, gph, sssid, datInGID, referenceNumber, yachtName,
|
||||
sailNumber, boatClassName, designer, builder, yearBuilt, issueDate, certType, isOneDesign, isProvisional);
|
||||
return new CertificateHandleImpl(issuingCountry, fileId, gph, sssid, datInGID, referenceNumber,
|
||||
yachtName, sailNumber, boatClassName, designer, builder, yearBuilt, issueDate, certType, isOneDesign, isProvisional, isValid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date parseDate(final String dateString) throws DateTimeParseException {
|
||||
Optional<LocalDateTime> parsedDateWithoutZone = Arrays.asList(DATE_FORMATTERS).stream()
|
||||
.map(f -> {
|
||||
try {
|
||||
return LocalDateTime.parse(dateString, f);
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(out -> out != null)
|
||||
.findAny();
|
||||
Optional<ZonedDateTime> parsedDateWithZone = Arrays.asList(DATE_FORMATTERS_WITH_ZONE).stream()
|
||||
.map(f -> {
|
||||
try {
|
||||
return ZonedDateTime.parse(dateString, f);
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(out -> out != null)
|
||||
.findAny();
|
||||
if (parsedDateWithoutZone.isPresent()) {
|
||||
LocalDateTime localDateTime = parsedDateWithoutZone.get();
|
||||
return Date.from(localDateTime.toInstant(ZoneOffset.UTC));
|
||||
}
|
||||
if (parsedDateWithZone.isPresent()) {
|
||||
ZonedDateTime zonedDateTime = parsedDateWithZone.get();
|
||||
return Date.from(zonedDateTime.toInstant());
|
||||
}
|
||||
logger.fine("Date is not parsable by any of the format :" + dateString);
|
||||
throw new DateTimeParseException("Date is not parsable by any of the format", dateString, 0);
|
||||
}
|
||||
|
||||
private Date parseDate(String dateString) throws ParseException {
|
||||
StringBuilder stringBuilder = new StringBuilder(dateString);
|
||||
char timeZoneCharacter = stringBuilder.charAt(stringBuilder.length()-1);
|
||||
if(timeZoneCharacter== 'z' || timeZoneCharacter == 'Z'|| timeZoneCharacter == 'X') {
|
||||
stringBuilder.deleteCharAt(stringBuilder.length()-1);
|
||||
}
|
||||
if(false == stringBuilder.toString().contains("+")) {
|
||||
stringBuilder.append("+0000");
|
||||
}
|
||||
@Override
|
||||
public ORCCertificate searchForUpdate(CertificateHandle certificateHandle)
|
||||
throws ClientProtocolException, IOException, org.json.simple.parser.ParseException {
|
||||
return searchForUpdate(certificateHandle.getIssuingCountry(), certificateHandle.getFileId(), certificateHandle.getReferenceNumber());
|
||||
}
|
||||
|
||||
return isoTimestampFormat.parse(stringBuilder.toString());
|
||||
@Override
|
||||
public ORCCertificate searchForUpdate(ORCCertificate certificate)
|
||||
throws ClientProtocolException, IOException, org.json.simple.parser.ParseException {
|
||||
return searchForUpdate(certificate.getIssuingCountry(), certificate.getFileId(), certificate.getReferenceNumber());
|
||||
}
|
||||
|
||||
private ORCCertificate searchForUpdate(final CountryCode issuingCountry, final String fileId,
|
||||
final String existingCertificateRefNo)
|
||||
throws IOException, org.json.simple.parser.ParseException, ClientProtocolException {
|
||||
logger.fine("Looking for update of certificate with reference number "+existingCertificateRefNo);
|
||||
final String queryParameters = "ext=json&CountryId=" + issuingCountry.getThreeLetterIOCCode()+
|
||||
"&dxtName="+fileId+".dxt";
|
||||
final ORCCertificate result = getSingleCertificate(queryParameters);
|
||||
if (result == null) {
|
||||
logger.info("Couldn't find any valid certificate for that boat");
|
||||
} else {
|
||||
if (result.getReferenceNumber().equals(existingCertificateRefNo)) {
|
||||
logger.info("Found no new certificate; the one with reference number "+existingCertificateRefNo+
|
||||
" is still valid.");
|
||||
} else {
|
||||
logger.info("Found update for "+existingCertificateRefNo+": "+result);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ORCCertificate getCertificate(String referenceNumber) throws Exception {
|
||||
final HttpClient client = new SystemDefaultHttpClient();
|
||||
final HttpGet getRequest = new HttpGet("http://data.orc.org/public/WPub.dll?action=DownBoatRMS&RefNo="+referenceNumber);
|
||||
addAuthorizationHeader(getRequest);
|
||||
final String queryParameters = "ext=json&RefNo="+referenceNumber;
|
||||
logger.fine("Obtaining certificate for reference number "+referenceNumber);
|
||||
final Iterable<ORCCertificate> certificates = new ORCCertificatesRmsImporter().read(client.execute(getRequest).getEntity().getContent())
|
||||
final ORCCertificate result = getSingleCertificate(queryParameters);
|
||||
if (result == null) {
|
||||
logger.info("Couldn't find ORC certificate with reference number "+referenceNumber);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ORCCertificate getSingleCertificate(final String queryParameters)
|
||||
throws IOException, org.json.simple.parser.ParseException, ClientProtocolException {
|
||||
final HttpGet getRequest = new HttpGet(SINGLE_CERTIFICATE_DOWNLOAD_URL+"&"+queryParameters);
|
||||
final HttpClient client = new SystemDefaultHttpClient();
|
||||
addAuthorizationHeader(getRequest);
|
||||
final Iterable<ORCCertificate> certificates = new ORCCertificatesJsonImporter().read(client.execute(getRequest).getEntity().getContent())
|
||||
.getCertificates();
|
||||
final ORCCertificate result;
|
||||
if (certificates.iterator().hasNext()) {
|
||||
result = certificates.iterator().next();
|
||||
} else {
|
||||
result = null;
|
||||
logger.info("Couldn't find ORC certificate with reference number "+referenceNumber);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -485,13 +600,13 @@ public class ORCPublicCertificateDatabaseImpl implements ORCPublicCertificateDat
|
||||
*/
|
||||
private Iterable<CertificateHandle> fuzzySearchVaryingBoatClassName(final String yachtName, final String sailNumber, final BoatClass boatClass) throws Exception {
|
||||
String successfulBoatClassName = boatClass==null?null:boatClass.getName();
|
||||
Iterable<CertificateHandle> certificateHandles = search(/* issuingCountry */ null, /* yearOfIssuance */ null, /* referenceNumber */ null, yachtName, sailNumber, successfulBoatClassName);
|
||||
Iterable<CertificateHandle> certificateHandles = search(/* issuingCountry */ null, /* yearOfIssuance */ null, /* referenceNumber */ null, yachtName, sailNumber, successfulBoatClassName, /* includeInvalid */ false);
|
||||
if (!containsHandleForCurrentYear(certificateHandles) && successfulBoatClassName != null) {
|
||||
if (yachtName != null || sailNumber != null) {
|
||||
logger.fine(()->"Nothing found; removing boat class name restriction "+boatClass.getName());
|
||||
// try without boat class restriction
|
||||
successfulBoatClassName = null;
|
||||
certificateHandles = search(/* issuingCountry */ null, /* yearOfIssuance */ null, /* referenceNumber */ null, yachtName, sailNumber, successfulBoatClassName);
|
||||
certificateHandles = search(/* issuingCountry */ null, /* yearOfIssuance */ null, /* referenceNumber */ null, yachtName, sailNumber, successfulBoatClassName, /* includeInvalid */ false);
|
||||
} else {
|
||||
logger.fine(()->"No current certificates found for boat class "+boatClass.getName()+
|
||||
" but yacht name and sail number are not specified either; giving up.");
|
||||
|
||||
+12
-7
@@ -12,6 +12,7 @@ import com.google.gwt.user.client.rpc.SerializationStreamWriter;
|
||||
import com.sap.sailing.domain.common.orc.ORCCertificate;
|
||||
import com.sap.sailing.domain.common.orc.impl.ORCCertificateImpl;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
@@ -27,7 +28,9 @@ public class ORCCertificateImpl_CustomFieldSerializer extends CustomFieldSeriali
|
||||
|
||||
public static void serialize(SerializationStreamWriter streamWriter, ORCCertificateImpl instance)
|
||||
throws SerializationException {
|
||||
streamWriter.writeString(instance.getId());
|
||||
streamWriter.writeString(instance.getReferenceNumber());
|
||||
streamWriter.writeString(instance.getFileId());
|
||||
streamWriter.writeObject(instance.getIssuingCountry());
|
||||
streamWriter.writeString(instance.getSailNumber());
|
||||
streamWriter.writeString(instance.getBoatName());
|
||||
streamWriter.writeString(instance.getBoatClassName());
|
||||
@@ -65,7 +68,9 @@ public class ORCCertificateImpl_CustomFieldSerializer extends CustomFieldSeriali
|
||||
|
||||
public static ORCCertificateImpl instantiate(SerializationStreamReader streamReader)
|
||||
throws SerializationException {
|
||||
final String idConsistingOfNatAuthCertNoAndBIN = streamReader.readString();
|
||||
final String referenceNumber = streamReader.readString();
|
||||
final String fileId = streamReader.readString();
|
||||
final CountryCode issuingCountry = (CountryCode) streamReader.readObject();
|
||||
final String sailnumber = streamReader.readString();
|
||||
final String boatName = streamReader.readString();
|
||||
final String boatclass = streamReader.readString();
|
||||
@@ -101,12 +106,12 @@ public class ORCCertificateImpl_CustomFieldSerializer extends CustomFieldSeriali
|
||||
@SuppressWarnings("unchecked")
|
||||
final List<Speed> readTWSs = (List<Speed>) streamReader.readObject();
|
||||
final Speed[] trueWindSpeeds = readTWSs == null ? ORCCertificate.ALLOWANCES_TRUE_WIND_SPEEDS : readTWSs.toArray(new Speed[readTWSs.size()]);
|
||||
return new ORCCertificateImpl(trueWindSpeeds,trueWindAngles,idConsistingOfNatAuthCertNoAndBIN, sailnumber, boatName, boatclass, length, gph,
|
||||
cdl, issueDate, velocityPredictionsPerTrueWindSpeedAndAngle, beatAngles,
|
||||
beatVMGPredictionPerTrueWindSpeed, beatAllowancePerTrueWindSpeed, runAngles,
|
||||
return new ORCCertificateImpl(trueWindSpeeds,trueWindAngles,referenceNumber, fileId, sailnumber, boatName, boatclass, length,
|
||||
gph, cdl, issueDate, issuingCountry,
|
||||
velocityPredictionsPerTrueWindSpeedAndAngle, beatAngles, beatVMGPredictionPerTrueWindSpeed,
|
||||
beatAllowancePerTrueWindSpeed, runAngles,
|
||||
runVMGPredictionPerTrueWindSpeed, runAllowancePerTrueWindSpeed,
|
||||
windwardLeewardSpeedPredictionsPerTrueWindSpeed, longDistanceSpeedPredictionsPerTrueWindSpeed,
|
||||
circularRandomSpeedPredictionsPerTrueWindSpeed, nonSpinnakerSpeedPredictionsPerTrueWindSpeed);
|
||||
windwardLeewardSpeedPredictionsPerTrueWindSpeed, longDistanceSpeedPredictionsPerTrueWindSpeed, circularRandomSpeedPredictionsPerTrueWindSpeed, nonSpinnakerSpeedPredictionsPerTrueWindSpeed);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
@@ -175,6 +175,7 @@ public class CertificatesTableWrapper<S extends RefreshableSelectionModel<ORCCer
|
||||
}
|
||||
|
||||
protected void showCertificate(ORCCertificate certificate) {
|
||||
// TODO embed <a href=\"http://data.orc.org/public/WPub.dll/CC/"+certificate.getReferenceNumber()+"\"> to link to the certificate PDF
|
||||
Window.confirm("Certificate: "+certificate);
|
||||
// TODO Implement CertificatesTableWrapper.showCertificate(...)
|
||||
}
|
||||
|
||||
+1
-1
@@ -9981,7 +9981,7 @@ public class SailingServiceImpl extends ResultCachingProxiedRemoteServiceServlet
|
||||
String referenceNumber, String yachtName, String sailNumber, String boatClassName) throws Exception {
|
||||
final ORCPublicCertificateDatabase db = ORCPublicCertificateDatabase.INSTANCE;
|
||||
final Set<ORCCertificate> result = new HashSet<>();
|
||||
final Iterable<CertificateHandle> searchResult = db.search(country, yearOfIssuance, referenceNumber, yachtName, sailNumber, boatClassName);
|
||||
final Iterable<CertificateHandle> searchResult = db.search(country, yearOfIssuance, referenceNumber, yachtName, sailNumber, boatClassName, /* includeInvalid */ false);
|
||||
Util.addAll(
|
||||
db.getCertificates(searchResult),
|
||||
result);
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class TestStoringAndLoadingRegattaORCCertificateAssignmentEvent extends A
|
||||
@Test
|
||||
public void test() throws JsonDeserializationException, ParseException {
|
||||
RaceLogORCCertificateAssignmentEvent expectedEvent = new RaceLogORCCertificateAssignmentEventImpl(MillisecondsTimePoint.now(), expectedEventTime, author,
|
||||
expectedId, expectedPassId, importer.getCertificateById("GER140772GER5549"), competitor);
|
||||
expectedId, expectedPassId, importer.getCertificateById("GER20040783"), competitor);
|
||||
|
||||
Document dbObject = mongoFactory.storeRaceLogEntry(logIdentifier, expectedEvent);
|
||||
RaceLogORCCertificateAssignmentEvent actualEvent = loadEvent(dbObject);
|
||||
|
||||
+13
-7
@@ -17,6 +17,8 @@ import com.sap.sailing.server.gateway.deserialization.JsonDeserializationExcepti
|
||||
import com.sap.sailing.server.gateway.deserialization.JsonDeserializer;
|
||||
import com.sap.sailing.server.gateway.serialization.racelog.impl.ORCCertificateJsonSerializer;
|
||||
import com.sap.sse.common.Bearing;
|
||||
import com.sap.sse.common.CountryCode;
|
||||
import com.sap.sse.common.CountryCodeFactory;
|
||||
import com.sap.sse.common.Distance;
|
||||
import com.sap.sse.common.Duration;
|
||||
import com.sap.sse.common.Speed;
|
||||
@@ -29,6 +31,9 @@ public class ORCCertificateJsonDeserializer implements JsonDeserializer<ORCCerti
|
||||
|
||||
@Override
|
||||
public ORCCertificate deserialize(JSONObject json) throws JsonDeserializationException {
|
||||
String fileId = (String) json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_FILE_ID);
|
||||
CountryCode issuingCountry = CountryCodeFactory.INSTANCE.getFromThreeLetterIOCName(
|
||||
((String) json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_ISSUING_COUNTRY_IOC)));
|
||||
String sailnumber = (String) json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_SAILNUMBER);
|
||||
String boatName = (String) json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_BOATNAME);
|
||||
String boatclass = (String) json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_BOATCLASS);
|
||||
@@ -103,13 +108,14 @@ public class ORCCertificateJsonDeserializer implements JsonDeserializer<ORCCerti
|
||||
velocityPredictionsPerTrueWindSpeedAndAngle.put(tws,
|
||||
velocityPredictionAtCurrentTrueWindSpeedPerTrueWindAngle);
|
||||
}
|
||||
final String idConsistingOfNatAuthCertNoAndBIN = json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_ID).toString();
|
||||
final ORCCertificate certificate = new ORCCertificateImpl(trueWindSpeeds,trueWindAngles,idConsistingOfNatAuthCertNoAndBIN, sailnumber,
|
||||
boatName, boatclass, length, gph, cdl, issueDate, velocityPredictionsPerTrueWindSpeedAndAngle,
|
||||
beatAngles, beatVMGPredictionPerTrueWindSpeed, beatAllowancePerTrueWindSpeed, runAngles,
|
||||
runVMGPredictionPerTrueWindSpeed, runAllowancePerTrueWindSpeed,
|
||||
windwardLeewardSpeedPredictionPerTrueWindSpeed, longDistanceSpeedPredictionPerTrueWindSpeed,
|
||||
circularRandomSpeedPredictionPerTrueWindSpeed, nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
final String referenceNumber = json.get(ORCCertificateJsonSerializer.ORC_CERTIFICATE_ID).toString();
|
||||
final ORCCertificate certificate = new ORCCertificateImpl(trueWindSpeeds, trueWindAngles, referenceNumber,
|
||||
fileId, sailnumber, boatName, boatclass, length, gph, cdl, issueDate, issuingCountry,
|
||||
velocityPredictionsPerTrueWindSpeedAndAngle, beatAngles, beatVMGPredictionPerTrueWindSpeed,
|
||||
beatAllowancePerTrueWindSpeed, runAngles, runVMGPredictionPerTrueWindSpeed,
|
||||
runAllowancePerTrueWindSpeed, windwardLeewardSpeedPredictionPerTrueWindSpeed,
|
||||
longDistanceSpeedPredictionPerTrueWindSpeed, circularRandomSpeedPredictionPerTrueWindSpeed,
|
||||
nonSpinnakerSpeedPredictionPerTrueWindSpeed);
|
||||
return certificate;
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -23,6 +23,8 @@ public class ORCCertificateJsonSerializer implements JsonSerializer<ORCCertifica
|
||||
public static final String ORC_CERTIFICATE_CIRCULAR_RANDOM_SPEED_PREDICTIONS = "circularRandomSpeedPredictions";
|
||||
public static final String ORC_CERTIFICATE_NON_SPINNAKER_SPEED_PREDICTIONS = "nonSpinnakerSpeedPredictions";
|
||||
public static final String ORC_CERTIFICATE_TWA_SPEED_PREDICTIONS = "twaSpeedPredictions";
|
||||
public static final String ORC_CERTIFICATE_FILE_ID = "fileId";
|
||||
public static final String ORC_CERTIFICATE_ISSUING_COUNTRY_IOC = "issuingCountryIOC";
|
||||
public static final String ORC_CERTIFICATE_SAILNUMBER = "sailNumber";
|
||||
public static final String ORC_CERTIFICATE_BOATNAME = "boatName";
|
||||
public static final String ORC_CERTIFICATE_BOATCLASS = "boatClass";
|
||||
@@ -55,7 +57,9 @@ public class ORCCertificateJsonSerializer implements JsonSerializer<ORCCertifica
|
||||
@Override
|
||||
public JSONObject serialize(ORCCertificate certificate) {
|
||||
JSONObject result = new JSONObject();
|
||||
result.put(ORC_CERTIFICATE_ID, certificate.getId());
|
||||
result.put(ORC_CERTIFICATE_ID, certificate.getReferenceNumber());
|
||||
result.put(ORC_CERTIFICATE_ISSUING_COUNTRY_IOC, certificate.getIssuingCountry()==null?null:certificate.getIssuingCountry().getThreeLetterIOCCode());
|
||||
result.put(ORC_CERTIFICATE_FILE_ID, certificate.getFileId());
|
||||
result.put(ORC_CERTIFICATE_SAILNUMBER, certificate.getSailNumber());
|
||||
result.put(ORC_CERTIFICATE_BOATNAME, certificate.getBoatName());
|
||||
result.put(ORC_CERTIFICATE_BOATCLASS, certificate.getBoatClassName());
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"rms":[
|
||||
{
|
||||
"NatAuth":"GR",
|
||||
"NatAuth":"GRE",
|
||||
"BIN":"GR317",
|
||||
"CertNo":"A00073",
|
||||
"RefNo":"N\/A",
|
||||
|
||||
@@ -7,8 +7,14 @@ public interface CountryCodeFactory {
|
||||
|
||||
Iterable<CountryCode> getAll();
|
||||
|
||||
/**
|
||||
* @param threeLetterIOCName if {@code null} then {@code null} will be returned
|
||||
*/
|
||||
CountryCode getFromThreeLetterIOCName(String threeLetterIOCName);
|
||||
|
||||
/**
|
||||
* @param twoLetterISOName if {@code null} then {@code null} will be returned
|
||||
*/
|
||||
CountryCode getFromTwoLetterISOName(String twoLetterISOName);
|
||||
|
||||
/**
|
||||
@@ -16,11 +22,19 @@ public interface CountryCodeFactory {
|
||||
* <pre>
|
||||
* getFromThreeLetterISOName(Locale.GERMANY.getISO3Country().toUpperCase())
|
||||
* </pre>
|
||||
*
|
||||
* @param threeLetterISOName if {@code null} then {@code null} will be returned
|
||||
*/
|
||||
CountryCode getFromThreeLetterISOName(String threeLetterISOName);
|
||||
|
||||
/**
|
||||
* @param ianaInternet if {@code null} then {@code null} will be returned
|
||||
*/
|
||||
CountryCode getFromIANAInternet(String ianaInternet);
|
||||
|
||||
/**
|
||||
* @param unVehicle if {@code null} then {@code null} will be returned
|
||||
*/
|
||||
CountryCode getFromUNVehicle(String unVehicle);
|
||||
|
||||
}
|
||||
@@ -306,27 +306,27 @@ public class CountryCodeFactoryImpl implements CountryCodeFactory {
|
||||
|
||||
@Override
|
||||
public CountryCode getFromIANAInternet(String ianaInternet) {
|
||||
return byIanaInternet.get(ianaInternet.toLowerCase());
|
||||
return ianaInternet==null?null:byIanaInternet.get(ianaInternet.toLowerCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountryCode getFromUNVehicle(String unVehicle) {
|
||||
return byUNVehicle.get(unVehicle.toUpperCase());
|
||||
return unVehicle==null?null:byUNVehicle.get(unVehicle.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountryCode getFromThreeLetterISOName(String threeLetterISOName) {
|
||||
return byThreeLetterISOName.get(threeLetterISOName.toUpperCase());
|
||||
return threeLetterISOName==null?null:byThreeLetterISOName.get(threeLetterISOName.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountryCode getFromThreeLetterIOCName(String threeLetterIOCName) {
|
||||
return byThreeLetterIOCName.get(threeLetterIOCName.toUpperCase());
|
||||
return threeLetterIOCName==null?null:byThreeLetterIOCName.get(threeLetterIOCName.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountryCode getFromTwoLetterISOName(String twoLetterISOName) {
|
||||
return byTwoLetterISOName.get(twoLetterISOName.toUpperCase());
|
||||
return twoLetterISOName==null?null:byTwoLetterISOName.get(twoLetterISOName.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
Reference in new issue
Block a user