index
int64
repo_id
string
file_path
string
content
string
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/SelectedAltitudeSource.java
package aero.t2s.modes.constants; public enum SelectedAltitudeSource { /** * 00 = Unknown - no information on the source of the information is available. */ UNKNOWN, /** * 01 = Aircraft Altitude - could indicate the aircraft is not equipped with an autopilot or the flight directors * are disabled, manual flying. */ AIRCRAFT, /** * 10 = MCP/FCU managed altitude - the aircraft is controlling the selected altitude through the MCP/FCU on the autopilot */ MCP, /** * 11 = FMS managed selected altitude - The FMS is control of the selected altitude */ FMS, ; public static SelectedAltitudeSource find(int source) { switch (source) { case 0: return UNKNOWN; case 1: return AIRCRAFT; case 2: return MCP; case 3: return FMS; default: throw new IllegalArgumentException("Unsupported value " + source); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/SourceIntegrityLevel.java
package aero.t2s.modes.constants; public enum SourceIntegrityLevel { UNKNOWN("Unknown or >1 x 10e-3"), LESS_THEN_ONE_PER_THOUSAND("<=1 x 10e-3"), LESS_THEN_ONE_PER_HUNDRED_THOUSAND("<=1 x 10e-5"), LESS_THEN_ONE_PER_TEN_MILLION("<=1 x 10e-7"), ; private String probability; SourceIntegrityLevel(String probability) { this.probability = probability; } public static SourceIntegrityLevel from(int code) { switch (code) { case 0: return UNKNOWN; case 1: return LESS_THEN_ONE_PER_THOUSAND; case 2: return LESS_THEN_ONE_PER_HUNDRED_THOUSAND; case 3: return LESS_THEN_ONE_PER_TEN_MILLION; default: throw new IllegalArgumentException("Sil supplement " + code + " is not valid"); } } @Override public String toString() { return probability; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/SourceIntegrityLevelSupplement.java
package aero.t2s.modes.constants; public enum SourceIntegrityLevelSupplement { PER_HOUR, PER_SAMPLE, ; public static SourceIntegrityLevelSupplement from(int code) { switch (code) { case 0: return PER_HOUR; case 1: return PER_SAMPLE; default: throw new IllegalArgumentException("Sil supplement " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/Speed.java
package aero.t2s.modes.constants; public enum Speed { KTS, KMH, IAS, TAS, GS, ; }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/SurveillanceStatus.java
package aero.t2s.modes.constants; public enum SurveillanceStatus { NO_CONDITION, PERMANENT_ALERT, TEMPORARY_ALERT, SPI, ; public static SurveillanceStatus from(int code) { switch (code) { case 0: return NO_CONDITION; case 1: return PERMANENT_ALERT; case 2: return TEMPORARY_ALERT; case 3: return SPI; default: throw new IllegalArgumentException("Surveillance Status " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/TargetAltitudeCapability.java
package aero.t2s.modes.constants; public enum TargetAltitudeCapability { ALTITUDE_HOLD, ALTITUDE_HOLD_OR_MCP, ALTITUDE_HOLD_OR_MCP_OR_FMS_RNAV, RESERVED, ; public static TargetAltitudeCapability from(int code) { switch (code) { case 0: return ALTITUDE_HOLD; case 1: return ALTITUDE_HOLD_OR_MCP; case 2: return ALTITUDE_HOLD_OR_MCP_OR_FMS_RNAV; case 3: return RESERVED; default: throw new IllegalArgumentException("Target Altitude Capability " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/TargetAltitudeType.java
package aero.t2s.modes.constants; public enum TargetAltitudeType { FL, MSL, ; public static TargetAltitudeType from(int code) { switch (code) { case 0: return FL; case 1: return MSL; default: throw new IllegalArgumentException("Target Altitude Type " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/TargetChangeReportCapability.java
package aero.t2s.modes.constants; public enum TargetChangeReportCapability { NO_CAPABILITY, SUPPORT_TC_PLUS_ZERO, SUPPORT_MULTIPLE_TC, RESERVED ; public static TargetChangeReportCapability from(int code) { switch (code) { case 0: return NO_CAPABILITY; case 1: return SUPPORT_TC_PLUS_ZERO; case 2: return SUPPORT_MULTIPLE_TC; case 3: return RESERVED; default: throw new IllegalArgumentException("Target Change Report Capability " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/ThreatTypeIndicator.java
package aero.t2s.modes.constants; public enum ThreatTypeIndicator { NO_ID, MODES, ALT_BRG_DIST, NOT_ASSIGNED, ; public static ThreatTypeIndicator from(int code) { switch (code) { case 0: return NO_ID; case 1: return MODES; case 2: return ALT_BRG_DIST; case 3: return NOT_ASSIGNED; default: throw new IllegalArgumentException("Threat Type Indicator " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/Version.java
package aero.t2s.modes.constants; public enum Version { VERSION0, VERSION1, VERSION2, ; public static Version from(int version) { if (version > values().length || version < 0) { return VERSION0; } return values()[version]; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/VerticalDataAvailable.java
package aero.t2s.modes.constants; public enum VerticalDataAvailable { NOT_VALID, AUTOPILOT, HOLDING_ALTITUDE, FMS_RNAV, ; public static VerticalDataAvailable from(int code) { switch (code) { case 0: return NOT_VALID; case 1: return AUTOPILOT; case 2: return HOLDING_ALTITUDE; case 3: return FMS_RNAV; default: throw new IllegalArgumentException("Vertical Data Available " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/VerticalModeIndicator.java
package aero.t2s.modes.constants; public enum VerticalModeIndicator { UNKNOWN, ACQUIRE, CAPTURE_MAINTAIN, RESERVED, ; public static VerticalModeIndicator from(int code) { switch (code) { case 0: return UNKNOWN; case 1: return ACQUIRE; case 2: return CAPTURE_MAINTAIN; case 3: return RESERVED; default: throw new IllegalArgumentException("Vertical Mode Indicator " + code + " is not valid"); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/constants/VerticalStatus.java
package aero.t2s.modes.constants; public enum VerticalStatus { /** * 0 - The aircraft is airborne */ AIRBORNE, /** * 1 - The aircraft is on the ground */ GROUND, ; public static VerticalStatus from(int status) { if (status > values().length || status < 0) { return null; } return values()[status]; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/database/AircraftTypeDatabase.java
package aero.t2s.modes.database; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AircraftTypeDatabase { private Map<String, Aircraft> aircraft = new HashMap<>(); public AircraftTypeDatabase() {} public AircraftTypeDatabase(Path csvFile) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(csvFile.toUri().toURL().openStream()))) { // Skip first line if (reader.ready()) { reader.readLine(); } while (reader.ready()) { String line = reader.readLine().replace("\"", ""); String[] parts = line.split(","); if (parts.length >= 8) { aircraft.put(parts[2], new Aircraft(parts[2], parts[7])); } } } catch (IOException e) { LoggerFactory.getLogger(getClass()).error("[ADS-B] Failed to read aircraft database", e); } LoggerFactory.getLogger(getClass()).info("[ADS-B] Aircraft database loaded {} aircraft", aircraft.size()); } public Aircraft find(String icao) { return aircraft.get(icao); } public static class Aircraft { public String icao; public String wtc; public Aircraft(String icao, String wtc) { this.icao = icao; this.wtc = wtc; } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/database/ModeSDatabase.java
package aero.t2s.modes.database; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class ModeSDatabase { private final Map<String, ModeSAircraft> modes = new HashMap<>(); private final AircraftTypeDatabase atypDatbase; public ModeSDatabase() { atypDatbase = new AircraftTypeDatabase(); } public ModeSDatabase(Path modeSFile, Path atypeFile) { this.atypDatbase = new AircraftTypeDatabase(atypeFile); loadModeS(modeSFile); } public static ModeSDatabase createDatabase() { return new ModeSDatabase(); } private void loadModeS(Path modeSFile) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(modeSFile.toUri().toURL().openStream()))) { // Skip first line if (reader.ready()) { reader.readLine(); } while (reader.ready()) { String line = reader.readLine().replace("\"", ""); String[] parts = line.split(","); if (parts.length >= 9) { modes.put(parts[0].toUpperCase(), new ModeSAircraft(parts[0].toUpperCase(), parts[1], parts[9], atypDatbase.find(parts[5]))); } } } catch (IOException e) { LoggerFactory.getLogger(getClass()).error("[ADS-B] Failed to read mode-s database", e); } LoggerFactory.getLogger(getClass()).info("[ADS-B] Mode-S database loaded {} mode-s addresses", modes.size()); } public ModeSAircraft find(String modes) { return this.modes.get(modes); } public static class ModeSAircraft { public String modes; public String registration; public String operator; public String atyp; public String wtc; public ModeSAircraft(String modes, String registration, String operator, AircraftTypeDatabase.Aircraft aircraft) { this.modes = modes; this.registration = registration; this.operator = operator; if (aircraft != null) { this.atyp = aircraft.icao; this.wtc = aircraft.wtc; } } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/AltitudeEncoding.java
package aero.t2s.modes.decoder; import aero.t2s.modes.Altitude; public class AltitudeEncoding { public static Altitude decode(int encoded) { if (encoded == 0) { return new Altitude(); } boolean mBit = (encoded & 0x40) != 0; boolean qBit = (encoded & 0x10) != 0; if (!mBit && !qBit) { return decodeModeC(encoded); } if (mBit) { return decodeMetric(encoded); } return decodeFeet(encoded); } private static Altitude decodeFeet(int encoded) { int n = ((encoded & 0b1111110000000) >>> 2) | (encoded & 0b11111); int altitude = (25 * n) - 1000; return new Altitude(altitude, false, 25); } private static Altitude decodeMetric(int encoded) { int altitude = ((encoded >>> 7) << 6) | (encoded & 0xFF); return new Altitude(altitude, true, 0); } /** * Decode mode C altitude using appendix chapter three of ICAO Annex 10 Volume 9. * Using SSR Automtic pressure altitude transmission code (pulse position assignment) table. * <p> * Oh yes this is using a lengthy table. * * @param encoded 13 bit encoded altitude with mbit/qbit * @return encoded altitude with 100ft accuracy */ public static Altitude decodeModeC(int encoded) { int c1 = (encoded >>> 12) & 0x1; int a1 = (encoded >>> 11) & 0x1; int c2 = (encoded >>> 10) & 0x1; int a2 = (encoded >>> 9) & 0x1; int c4 = (encoded >>> 8) & 0x1; int a4 = (encoded >>> 7) & 0x1; int b1 = (encoded >>> 5) & 0x1; int b2 = (encoded >>> 3) & 0x1; int d2 = (encoded >>> 2) & 0x1; int b4 = (encoded >>> 1) & 0x1; int d4 = encoded & 0x1; int n500 = grayToBin(d2 << 7 | d4 << 6 | a1 << 5 | a2 << 4 | a4 << 3 | b1 << 2 | b2 << 1 | b4, 8); int n100 = grayToBin(c1 << 2 | c2 << 1 | c4, 3) - 1; if (n100 == 6) { n100 = 4; } if (n500 % 2 != 0) { n100 = 4 - n100; } int altitude = -1200 + n500 * 500 + n100 * 100; return new Altitude(altitude, false, 100); } private static int grayToBin(int gray, int bitSize) { int result = 0; for (int i = bitSize - 1; i >= 0; --i) { result = result | ((((0x1 << (i + 1)) & result) >>> 1) ^ ((1 << i) & gray)); } return result; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/Common.java
package aero.t2s.modes.decoder; import java.util.Arrays; public class Common { private static final String chars = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ#####_###############0123456789######"; private static final char[] haxChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static final short[] CRC_POLYNOMIAL = {0xFF, 0xF4, 0x09}; public static String icao(String hex) { if (hex.length() < 9) { return null; } return hex.substring(3, 9); } public static String charToString(int character) { if (character > chars.length()) { return "#"; } return chars.substring(character, character + 1); } public static String toHexString(short[] data) { final int length = data.length; final char[] out = new char[length << 1]; for (int i = 0, j = 0; i < length; i++) { out[j++] = haxChars[(0xF0 & data[i]) >>> 4]; out[j++] = haxChars[0x0F & data[i]]; } return new String(out); } /** * @param short1 first short * @param short2 second short * @return short1 xor short2 (bitwise) */ public static short xor(short short1, short short2) { return (short)(0xff&(short1^short2)); } /** * @param array1 first array * @param array2 second array * @return array1 xor array2 (bitwise) */ public static short[] xor(short[] array1, short[] array2) { assert(array1.length == array2.length); short[] res = new short[array1.length]; for (int i=0; i<array1.length; ++i) res[i] = xor(array1[i], array2[i]); return res; } public static String getIcaoAddressFromParity(short[] data) { short[] payload = Arrays.copyOfRange(data, 0, data.length - 3); short[] parity = Arrays.copyOfRange(data, data.length - 3, data.length); return getIcaoAddress(payload, parity); } public static String getIcaoAddress(short[] data, short[] messageParity) { short[] calculatedParity = getParity(data); return Common.toHexString(xor(calculatedParity, messageParity)); } public static short[] getParity(short[] data) { short[] parity = Arrays.copyOf(data, CRC_POLYNOMIAL.length); boolean invert; int index; int shift; for (int i = 0; i < data.length * 8; ++i) { // bit by bit invert = ((parity[0] & 0x80) != 0); parity[0] <<= 1; for (int b = 1; b < CRC_POLYNOMIAL.length; ++b) { parity[b - 1] |= (parity[b] >>> 7) & 0x1; parity[b] <<= 1; } index = ((CRC_POLYNOMIAL.length * 8) + i) / 8; shift = 7 - (i % 8); if (index < data.length) { parity[parity.length - 1] |= (data[index] >>> shift) & 0x1; } // xor if (invert) { for (int b = 0; b < CRC_POLYNOMIAL.length; ++b) { parity[b] ^= CRC_POLYNOMIAL[b]; } } } return Arrays.copyOf(parity, CRC_POLYNOMIAL.length); } public static boolean isNotValid(short[] data) { // fixes negative length bug where data is only 2 bytes (16bit Mode A/C replies, ACAS, ...) // examples: *21D2; *0200; *0101; <- only the 2 bytes are in data variable if(data.length < 3) { return true; } short[] payload = Arrays.copyOfRange(data, 0, data.length - 3); short[] parity = Arrays.copyOfRange(data, data.length - 3, data.length); return areEqual(getParity(payload), parity); } public static boolean areEqual(short[] array1, short[] array2) { if (array1.length != array2.length) return false; for (int i=0; i<array1.length; ++i) if (array1[i] != array2[i]) return false; return true; } public static boolean isFlightStatusAlert(int fs) { return fs >= 2 && fs <= 4; } public static boolean isFlightStatusSpi(int fs) { return fs == 4 || fs == 5; } public static int modeA(int encoded) { int c1 = (encoded >>> 12) & 0x1; int a1 = (encoded >>> 11) & 0x1; int c2 = (encoded >>> 10) & 0x1; int a2 = (encoded >>> 9) & 0x1; int c4 = (encoded >>> 8) & 0x1; int a4 = (encoded >>> 7) & 0x1; int x = (encoded >>> 6) & 0x1; int b1 = (encoded >>> 5) & 0x1; int d1 = (encoded >>> 4) & 0x1; int b2 = (encoded >>> 3) & 0x1; int d2 = (encoded >>> 2) & 0x1; int b4 = (encoded >>> 1) & 0x1; int d4 = encoded & 0x1; int n1 = ((a4 << 2) | (a2 << 1) | a1) * 1000; int n2 = ((b4 << 2) | (b2 << 1) | b1) * 100; int n3 = ((c4 << 2) | (c2 << 1) | c1) * 10; int n4 = ((d4 << 2) | (d2 << 1) | d1); return n1 + n2 + n3 + n4; } public static double tidr(int encodedDistance) { if (encodedDistance == 0) { return -1; } return (encodedDistance - 1.0) / 10.0; } public static int tidb(int encodedBearing) { if (encodedBearing == 0) { return -1; } return 6 * (encodedBearing - 1); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/Decoder.java
package aero.t2s.modes.decoder; import aero.t2s.modes.Track; import aero.t2s.modes.database.ModeSDatabase; import aero.t2s.modes.decoder.df.*; import java.util.Map; public class Decoder { private final double originLat; private final double originLon; private final ModeSDatabase modeSDatabase; private final Map<String, Track> tracks; public Decoder(Map<String, Track> tracks, double originLat, double originLon, ModeSDatabase database) { this.tracks = tracks; this.originLat = originLat; this.originLon = originLon; this.modeSDatabase = database == null ? ModeSDatabase.createDatabase() : database; } public DownlinkFormat decode(short[] data) throws UnknownDownlinkFormatException { if (Common.isNotValid(data)) { return null; } int downlinkFormat = data[0] >>> 3; // Remaining bits are used by the data object if (downlinkFormat >= 24) { downlinkFormat = 24; } DownlinkFormat df; switch (downlinkFormat) { case 0: df = new DF0(data); break; case 4: df = new DF4(data); break; case 5: df = new DF5(data); break; case 11: df = new DF11(data); break; case 16: df = new DF16(data); break; case 17: df = new DF17(data, originLat, originLon); break; case 18: df = new DF18(data); break; case 20: df = new DF20(data); break; case 21: df = new DF21(data); break; case 22: df = new DF22(data); break; case 24: df = new DF24(data); break; default: throw new UnknownDownlinkFormatException(downlinkFormat, data); } return df.decode(); } public Track getTrack(String icao) { Track track = tracks.get(icao); if (track == null) { track = new Track(icao); tracks.putIfAbsent(icao, track); ModeSDatabase.ModeSAircraft modeSAircraft = modeSDatabase.find(icao); if (modeSAircraft != null) { track.setWtc(modeSAircraft.wtc); track.setAtype(modeSAircraft.atyp); track.setOperator(modeSAircraft.operator); track.setRegistration(modeSAircraft.registration); } } else { track.setWasJustCreated(false); } return track; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/UnknownDownlinkFormatException.java
package aero.t2s.modes.decoder; import aero.t2s.modes.DownlinkException; public class UnknownDownlinkFormatException extends Exception implements DownlinkException { public UnknownDownlinkFormatException(int downlinkFormat, short[] data) { super(String.format("Unknown Mode S Packet: %d => %s", downlinkFormat, Common.toHexString(data))); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF0.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Acas; import aero.t2s.modes.Altitude; import aero.t2s.modes.Track; import aero.t2s.modes.constants.AcasReplyInformation; import aero.t2s.modes.constants.AcasSensitivity; import aero.t2s.modes.constants.CrossLinkCapability; import aero.t2s.modes.constants.VerticalStatus; import aero.t2s.modes.decoder.AltitudeEncoding; /** * Short Air-Air Surveillance * * <pre> * LSB |1----|6-|7-|-|9--|--|14--|--|20-----------|33----------------------| * | DF |VS|CC|-| SL| | RI | | AC | AP | * MSB |----5|-6|-7|-|-11|--|--17|--|-----------32|----------------------56| * * DF Downlink format - 5 bits * VS Vertical status - 1 bit * CS Cross-link capability - 1 bit * spare - 1 bit * SL Sensitivity level, ACAS - 3 bits * spare - 2 bits * AC Altitude code - 12 bits * AP Address/Parity - 24 bits * </pre> * * <ul> * <li>DF Downlink Format {@link DownlinkFormat}</li> * <li>Vertical Status {@link VerticalStatus#from(int)} for details</li> * <li>Cross-link capability {@link CrossLinkCapability}</li> * <li>Reply information, air-air {@link AcasReplyInformation#from(int)}</li> * <li>Sensitivity Level {@link AcasSensitivity#from(int)}</li> * <li>Altitude code {@link AltitudeEncoding#decode(int)}</li> * </ul> */ public class DF0 extends DownlinkFormat { private VerticalStatus verticalStatus; private CrossLinkCapability crossLinkCapability; private AcasSensitivity sensitivity; private AcasReplyInformation replyInformation; private Altitude altitude; public DF0(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF0 decode() { verticalStatus = VerticalStatus.from((data[0] >>> 2) & 0x1); crossLinkCapability = CrossLinkCapability.from((data[0] >>> 1) & 0x1); sensitivity = AcasSensitivity.from(data[1] >>> 5); replyInformation = AcasReplyInformation.from(((data[1] & 0x7) << 1) | ((data[2] >> 7) & 0x1)); altitude = AltitudeEncoding.decode((((data[2] << 8) | data[3])) & 0x1FFF); return this; } @Override public void apply(Track track) { Acas acas = track.getAcas(); acas.setVerticalStatus(verticalStatus); acas.setCrossLinkCapability(crossLinkCapability); acas.setSensitivity(sensitivity); acas.setReplyInformation(replyInformation); acas.setAltitude(altitude); track.setAltitude(altitude); } public VerticalStatus getVerticalStatus() { return verticalStatus; } public CrossLinkCapability getCrossLinkCapability() { return crossLinkCapability; } public AcasSensitivity getSensitivity() { return sensitivity; } public AcasReplyInformation getReplyInformation() { return replyInformation; } public Altitude getAltitude() { return altitude; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF11.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Track; import aero.t2s.modes.constants.Capability; import aero.t2s.modes.decoder.Common; public class DF11 extends DownlinkFormat { private Capability capability; private String address; public DF11(short[] data) { super(data, IcaoAddress.FROM_MESSAGE); } @Override public DF11 decode() { capability = Capability.from(data[0] & 0b00000111); address = Common.toHexString(new short[] { data[1], data[2], data[3], data[4], }); return this; } @Override public void apply(Track track) { } public Capability getCapability() { return capability; } public String getAddress() { return address; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF16.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Acas; import aero.t2s.modes.Altitude; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; import aero.t2s.modes.decoder.AltitudeEncoding; public class DF16 extends DownlinkFormat { private VerticalStatus verticalStatus; private CrossLinkCapability crossLinkCapability; private AcasSensitivity sensitivity; private AcasReplyInformation replyInformation; private Altitude altitude; private ResolutionAdvisory resolutionAdvisory; private boolean multipleThreats; private boolean RANotPassBelow; private boolean RANotPassAbove; private boolean RANotTurnLeft; private boolean RANotTurnRight; public DF16(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF16 decode() { verticalStatus = VerticalStatus.from((data[0] >>> 2) & 0x1); crossLinkCapability = CrossLinkCapability.from((data[0] >>> 1) & 0x1); sensitivity = AcasSensitivity.from(data[1] >>> 5); replyInformation = AcasReplyInformation.from(((data[1] & 0x7) << 1) | ((data[2] >> 7) & 0x1)); altitude = AltitudeEncoding.decode((((data[2] << 8) | data[3])) & 0x1FFF); int vds1 = data[4] >>> 4; int vds2 = data[4] & 0xF; int ara = (data[5] << 5) | (data[6] >>> 3); int rac = ((data[5] & 0x3) << 2) | data[6] >>> 6; int rat = (data[6] >>> 5) & 0x1; multipleThreats = ((data[6] >>> 4) & 0x1) == 1; if (vds1 == 3 && vds2 == 0) { resolutionAdvisory = new ResolutionAdvisory(ara); RANotPassBelow = rac >>> 3 == 1; RANotPassAbove = ((rac >>> 2) & 0x1) == 1; RANotTurnLeft = ((rac >>> 1) & 0x1) == 1; RANotTurnLeft = (rac & 0x1) == 1; } if (rat == 1 || resolutionAdvisory == null) { resolutionAdvisory = new ResolutionAdvisory(); RANotPassBelow = false; RANotPassAbove = false; RANotTurnLeft = false; RANotTurnRight = false; multipleThreats = false; } return this; } @Override public void apply(Track track) { Acas acas = track.getAcas(); acas.setVerticalStatus(verticalStatus); acas.setCrossLinkCapability(crossLinkCapability); acas.setSensitivity(sensitivity); acas.setReplyInformation(replyInformation); acas.setAltitude(altitude); acas.getResolutionAdvisory().update(resolutionAdvisory); acas.setRANotPassBelow(RANotPassBelow); acas.setRANotPassAbove(RANotPassAbove); acas.setRANotTurnLeft(RANotTurnLeft); acas.setRANotTurnRight(RANotTurnRight); acas.setMultipleThreats(multipleThreats); } public VerticalStatus getVerticalStatus() { return verticalStatus; } public CrossLinkCapability getCrossLinkCapability() { return crossLinkCapability; } public AcasSensitivity getSensitivity() { return sensitivity; } public AcasReplyInformation getReplyInformation() { return replyInformation; } public Altitude getAltitude() { return altitude; } public ResolutionAdvisory getResolutionAdvisory() { return resolutionAdvisory; } public boolean isMultipleThreats() { return multipleThreats; } public boolean isRANotPassBelow() { return RANotPassBelow; } public boolean isRANotPassAbove() { return RANotPassAbove; } public boolean isRANotTurnLeft() { return RANotTurnLeft; } public boolean isRANotTurnRight() { return RANotTurnRight; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF17.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.df.df17.*; public class DF17 extends DownlinkFormat { private final double originLat; private final double originLon; private ExtendedSquitter extendedSquitter; public DF17(short[] data, double originLat, double originLon) { super(data, IcaoAddress.FROM_MESSAGE); this.originLat = originLat; this.originLon = originLon; } @Override public DF17 decode() { int typeCode = data[4] >>> 3; switch (typeCode) { case 0: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 20: case 21: case 22: extendedSquitter = new AirbornePosition(data, originLat, originLon); break; case 1: case 2: case 3: case 4: extendedSquitter = new AircraftIdentification(data); break; case 5: case 6: case 7: case 8: extendedSquitter = new SurfacePosition(data); break; case 19: extendedSquitter = new AirborneVelocity(data); break; case 23: extendedSquitter = new TestMessage(data); break; case 24: extendedSquitter = new SurfaceSystemStatus(data); break; case 25: case 26: case 27: case 30: extendedSquitter = new ReservedMessage(data); break; case 28: extendedSquitter = new AircraftStatusMessage(data); break; case 29: extendedSquitter = new TargetStatusMessage(data); break; case 31: extendedSquitter = new AircraftOperationalStatusMessage(data); break; default: logger.warn("Mode-S: No parser found for DF-17 type code {}. Packet ignored", typeCode); throw new InvalidExtendedSquitterTypeCodeException(typeCode); } extendedSquitter = extendedSquitter.decode(); return this; } @Override public void apply(Track track) { extendedSquitter.apply(track); } public ExtendedSquitter getExtendedSquitter() { return extendedSquitter; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF18.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.df.df17.*; public class DF18 extends DownlinkFormat { private ExtendedSquitter extendedSquitter; public DF18(short[] data) { super(data, IcaoAddress.FROM_MESSAGE); } @Override public DF18 decode() { int typeCode = data[4] >>> 3; switch (typeCode) { case 1: case 2: case 3: case 4: extendedSquitter = new AircraftIdentification(data); break; case 5: case 6: case 7: case 8: extendedSquitter = new SurfacePosition(data); break; case 19: extendedSquitter = new AirborneVelocity(data); break; case 23: extendedSquitter = new TestMessage(data); break; case 24: extendedSquitter = new SurfaceSystemStatus(data); break; case 25: case 26: case 27: case 30: extendedSquitter = new ReservedMessage(data); break; case 28: extendedSquitter = new AircraftStatusMessage(data); break; case 29: extendedSquitter = new TargetStatusMessage(data); break; case 31: extendedSquitter = new AircraftOperationalStatusMessage(data); break; default: logger.warn("Mode-S: No parser found for DF-18 type code {}. Packet ignored", typeCode); throw new InvalidExtendedSquitterTypeCodeException(typeCode); } extendedSquitter = extendedSquitter.decode(); return this; } @Override public void apply(Track track) { extendedSquitter.apply(track); } public ExtendedSquitter getExtendedSquitter() { return extendedSquitter; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF20.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Altitude; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.AltitudeEncoding; import aero.t2s.modes.decoder.Common; import aero.t2s.modes.decoder.df.bds.Bds; import aero.t2s.modes.decoder.df.bds.BdsDecoder; import aero.t2s.modes.EmptyMessageException; import aero.t2s.modes.decoder.df.bds.MultipleBdsMatchesFoundException; import java.util.List; public class DF20 extends DownlinkFormat { private Bds bds; private boolean alert; private boolean spi; private Altitude altitude; private boolean valid; private boolean multipleMatches; private List<Bds> matches; public DF20(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF20 decode() { int flightStatus = data[0] & 0x3; alert = Common.isFlightStatusAlert(flightStatus); spi = Common.isFlightStatusSpi(flightStatus); altitude = AltitudeEncoding.decode((data[2] & 0x1F) << 8 | data[3]); try { bds = new BdsDecoder(data).decode(); valid = true; } catch (EmptyMessageException e) { valid = false; } catch (MultipleBdsMatchesFoundException e) { matches = e.getMatches(); multipleMatches = true; valid = false; logger.debug("Multiple matches BDS matches found {}", matches.stream().map(bds -> bds.getClass().getSimpleName()).reduce((a, b) -> String.join(", ", a, b))); } catch (NotImplementedException e) { throw new NotImplementedException("ADS-B: DF-20 received but could not determine BDS code " + Common.toHexString(data)); } return this; } @Override public void apply(Track track) { track.getFlightStatus().setAlert(alert); track.getFlightStatus().setSpi(spi); track.setAltitude(altitude); if (valid) { bds.apply(track); } } public Bds getBds() { return bds; } public boolean isAlert() { return alert; } public boolean isSpi() { return spi; } public boolean isValid() { return valid; } public boolean isMultipleMatches() { return multipleMatches; } public List<Bds> getMatches() { return matches; } public Altitude getAltitude() { return altitude; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF21.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; import aero.t2s.modes.decoder.df.bds.Bds; import aero.t2s.modes.decoder.df.bds.BdsDecoder; import aero.t2s.modes.EmptyMessageException; import aero.t2s.modes.decoder.df.bds.MultipleBdsMatchesFoundException; import java.util.List; public class DF21 extends DownlinkFormat { private Bds bds; private boolean alert; private boolean spi; private int modeA; private boolean valid; private boolean multipleMatches; private List<Bds> matches; public DF21(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF21 decode() { int flightStatus = data[0] & 0x3; alert = Common.isFlightStatusAlert(flightStatus); spi = Common.isFlightStatusSpi(flightStatus); modeA = Common.modeA((data[2] & 0x1F) << 8 | data[3]); try { bds = new BdsDecoder(data).decode(); valid = true; } catch (EmptyMessageException e) { valid = false; } catch (MultipleBdsMatchesFoundException e) { matches = e.getMatches(); multipleMatches = true; valid = false; logger.debug("Multiple matches BDS matches found {}", matches.stream().map(bds -> bds.getClass().getSimpleName()).reduce((a, b) -> String.join(", ", a, b))); } catch (NotImplementedException e) { throw new NotImplementedException("ADS-B: DF-21 received but could not determine BDS code " + Common.toHexString(data)); } return this; } @Override public void apply(Track track) { track.getFlightStatus().setAlert(alert); track.getFlightStatus().setSpi(spi); track.setModeA(modeA); if (valid) { bds.apply(track); } } public Bds getBds() { return bds; } public boolean isAlert() { return alert; } public boolean isSpi() { return spi; } public int getModeA() { return modeA; } public boolean isValid() { return valid; } public boolean isMultipleMatches() { return multipleMatches; } public List<Bds> getMatches() { return matches; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF22.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class DF22 extends DownlinkFormat { public DF22(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF22 decode() { throw new NotImplementedException(getClass().getSimpleName() + ": Not implemented"); } @Override public void apply(Track track) { // } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF24.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class DF24 extends DownlinkFormat { public DF24(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF24 decode() { throw new NotImplementedException(getClass().getSimpleName() + ": Not implemented"); } @Override public void apply(Track track) { // } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF4.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Altitude; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.AltitudeEncoding; import aero.t2s.modes.decoder.Common; public class DF4 extends DownlinkFormat { private boolean alert; private boolean spi; private Altitude altitude; public DF4(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF4 decode() { int fs = data[0] & 0x7; alert = Common.isFlightStatusAlert(fs); spi = Common.isFlightStatusSpi(fs); altitude = AltitudeEncoding.decode((((data[2] << 8) | data[3])) & 0x1FFF); return this; } @Override public void apply(Track track) { track.getFlightStatus().setAlert(alert); track.getFlightStatus().setSpi(spi); track.setAltitude(altitude); } public boolean isAlert() { return alert; } public boolean isSpi() { return spi; } public Altitude getAltitude() { return altitude; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DF5.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; import aero.t2s.modes.decoder.Decoder; import org.slf4j.LoggerFactory; public class DF5 extends DownlinkFormat { private boolean alert; private boolean spi; private int modeA; public DF5(short[] data) { super(data, IcaoAddress.FROM_PARITY); } @Override public DF5 decode() { int fs = data[0] & 0x7; alert = Common.isFlightStatusAlert(fs); spi = Common.isFlightStatusSpi(fs); modeA = Common.modeA((((data[2] << 8) | data[3])) & 0x1FFF); return this; } @Override public void apply(Track track) { track.getFlightStatus().setAlert(alert); track.getFlightStatus().setSpi(spi); track.setModeA(modeA); } public boolean isAlert() { return alert; } public boolean isSpi() { return spi; } public int getModeA() { return modeA; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/DownlinkFormat.java
package aero.t2s.modes.decoder.df; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; public abstract class DownlinkFormat { protected static final Logger logger = LoggerFactory.getLogger(DownlinkFormat.class); protected final short[] data; private final String icao; public DownlinkFormat(short[] data, IcaoAddress icaoAddressFrom) { this.data = data; if (icaoAddressFrom == IcaoAddress.FROM_PARITY) { this.icao = Common.getIcaoAddressFromParity(data); } else { this.icao = Common.toHexString(Arrays.copyOfRange(data, 1, 4)); } } public abstract DownlinkFormat decode(); public abstract void apply(Track track); public String getIcao() { return this.icao; } public short[] getData() { return data; } protected enum IcaoAddress { FROM_MESSAGE, FROM_PARITY, } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; public abstract class Bds { private final short[] data; private boolean valid = true; public Bds(short[] data) { this.data = data; } public abstract void apply(Track track); protected void invalidate() { this.valid = false; reset(); } protected abstract void reset(); public boolean isValid() { return valid; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds10.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; public class Bds10 extends Bds { public Bds10(short[] data) { super(data); if (data[4] >>> 4 != 1 || (data[4] & 0xF) != 0) { invalidate(); return; } if (((data[5] >>> 2) & 0x1F) == 0) { return; } invalidate(); } @Override public void apply(Track track) { } @Override protected void reset() { } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds17.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; public class Bds17 extends Bds { private boolean bds05; private boolean bds06; private boolean bds07; private boolean bds08; private boolean bds09; private boolean bds0A; private boolean bds20; private boolean bds21; private boolean bds40; private boolean bds41; private boolean bds42; private boolean bds43; private boolean bds44; private boolean bds45; private boolean bds48; private boolean bds50; private boolean bds51; private boolean bds52; private boolean bds53; private boolean bds54; private boolean bds55; private boolean bds56; private boolean bds5F; private boolean bds60; public Bds17(short[] data) { super(data); // 2,0 Aircraft identification shall always be present if ((data[4] & 0b00000010) == 0) { invalidate(); return; } // F,1 Mil reserved use if (data[7] != 0 || data[8] != 0 || data[9] != 0 || data[10] != 0) { invalidate(); return; } bds05 = (data[4] & 0b10000000) != 0; bds06 = (data[4] & 0b01000000) != 0; bds07 = (data[4] & 0b00100000) != 0; bds08 = (data[4] & 0b00010000) != 0; bds09 = (data[4] & 0b00001000) != 0; bds0A = (data[4] & 0b00000100) != 0; bds20 = (data[4] & 0b00000010) != 0; bds21 = (data[4] & 0b00000001) != 0; bds40 = (data[5] & 0b10000000) != 0; bds41 = (data[5] & 0b01000000) != 0; bds42 = (data[5] & 0b00100000) != 0; bds43 = (data[5] & 0b00010000) != 0; bds44 = (data[5] & 0b00001000) != 0; bds45 = (data[5] & 0b00000100) != 0; bds48 = (data[5] & 0b00000010) != 0; bds50 = (data[5] & 0b00000001) != 0; bds51 = (data[6] & 0b10000000) != 0; bds52 = (data[6] & 0b01000000) != 0; bds53 = (data[6] & 0b00100000) != 0; bds54 = (data[6] & 0b00010000) != 0; bds55 = (data[6] & 0b00001000) != 0; bds56 = (data[6] & 0b00000100) != 0; bds5F = (data[6] & 0b00000010) != 0; bds60 = (data[6] & 0b00000001) != 0; } @Override public void apply(Track track) { track.getCapabilityReport().update(this); } @Override protected void reset() { bds05 = false; bds06 = false; bds07 = false; bds08 = false; bds09 = false; bds0A = false; bds20 = false; bds21 = false; bds40 = false; bds41 = false; bds42 = false; bds43 = false; bds44 = false; bds45 = false; bds48 = false; bds50 = false; bds51 = false; bds52 = false; bds53 = false; bds54 = false; bds55 = false; bds56 = false; bds5F = false; bds60 = false; } public boolean isBds05() { return bds05; } public boolean isBds06() { return bds06; } public boolean isBds07() { return bds07; } public boolean isBds08() { return bds08; } public boolean isBds09() { return bds09; } public boolean isBds0A() { return bds0A; } public boolean isBds20() { return bds20; } public boolean isBds21() { return bds21; } public boolean isBds40() { return bds40; } public boolean isBds41() { return bds41; } public boolean isBds42() { return bds42; } public boolean isBds43() { return bds43; } public boolean isBds44() { return bds44; } public boolean isBds45() { return bds45; } public boolean isBds48() { return bds48; } public boolean isBds50() { return bds50; } public boolean isBds51() { return bds51; } public boolean isBds52() { return bds52; } public boolean isBds53() { return bds53; } public boolean isBds54() { return bds54; } public boolean isBds55() { return bds55; } public boolean isBds56() { return bds56; } public boolean isBds5F() { return bds5F; } public boolean isBds60() { return bds60; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds20.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; public class Bds20 extends Bds { private String acid; public Bds20(short[] data) { super(data); if (data[4] >>> 4 != 2 || (data[4] & 0xF) != 0) { invalidate(); return; } acid = Common.charToString(data[5] >>> 2) + Common.charToString(((data[5] & 0x3) << 4) | (data[6] >>> 4)) + Common.charToString(((data[6] & 0xF) << 2) | (data[7] >>> 6)) + Common.charToString(data[7] & 0x3F) + Common.charToString(data[8] >>> 2) + Common.charToString(((data[8] & 0x3) << 4) | (data[9] >>> 4)) + Common.charToString(((data[9] & 0xF) << 2) | (data[10] >>> 6)) + Common.charToString(data[10] & 0x3F); acid = acid.replace("_", ""); } @Override public void apply(Track track) { track.setCallsign(acid); } @Override protected void reset() { acid = null; } public String getAcid() { return acid; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds21.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; public class Bds21 extends Bds { private boolean statusAircraftRegistration; private boolean statusAirlineRegistration; private String registration; private String airline; public Bds21(short[] data) { super(data); statusAircraftRegistration = (data[4] & 0b10000000) != 0; statusAirlineRegistration = (data[9] & 0b00010000) != 0; if (!statusAircraftRegistration && (data[4] | data[5] | data[6] | data[7] | data[8] | data[9] >>> 5) != 0) { invalidate(); return; } if (!statusAirlineRegistration && ((data[9] & 0b00001111) | data[10]) != 0) { invalidate(); return; } if (data[4] != 0b00100000) { invalidate(); return; } if (statusAircraftRegistration) { // Char 7 registration = Common.charToString((data[4] & 0b01111110) >>> 1) // Char 1 + Common.charToString(((data[4] & 0b00000001) << 5) | (data[5] >>> 3)) // Char 2 + Common.charToString(((data[5] & 0b00000111) << 3) | (data[6] >>> 5)) // Char 3 + Common.charToString(((data[6] & 0b00011111) << 1) | (data[7] >>> 7)) // Char 4 + Common.charToString((data[7] & 0b01111110) >>> 1) // Char 5 + Common.charToString(((data[7] & 0b00000001) << 5) | (data[8] >>> 3)) // Char 6 + Common.charToString(((data[8] & 0b00000111) << 3) | (data[9] >>> 3)); if (registration.contains("#")) { invalidate(); return; } registration = registration.replace("_", ""); } if (statusAirlineRegistration) { airline = Common.charToString(((data[9] & 0b00001111) << 2 | (data[10] >>> 6))) + Common.charToString(data[10] & 0b00111111); if (airline.contains("_") || airline.contains("#")) { invalidate(); return; } } } @Override public void apply(Track track) { if (statusAircraftRegistration) { track.setRegistration(registration); } if (statusAirlineRegistration) { track.setOperator(airline); } } @Override protected void reset() { statusAircraftRegistration = false; statusAirlineRegistration = false; registration = null; airline = null; } public boolean isStatusAircraftRegistration() { return statusAircraftRegistration; } public boolean isStatusAirlineRegistration() { return statusAirlineRegistration; } public String getRegistration() { return registration; } public String getAirline() { return airline; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds30.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; public class Bds30 extends Bds { public Bds30(short[] data) { super(data); if (data[4] >>> 4 != 3 || (data[4] & 0xF) != 0) { invalidate(); return; } } @Override public void apply(Track track) { } @Override protected void reset() { } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds40.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; import aero.t2s.modes.constants.SelectedAltitudeSource; /** * 56-bit MB Field is structured in the following format * <pre> * * LSB |1-------|2----------|14------|15---------|27------|28---------|40--------|48------|49----|50---|51---|52--------|54------|55------| * | STATUS | MCP ALT | STATUS | FMS ALT | STATUS | BARO | RESERVED | STATUS | VNAV | ALT | APP | RESERVED | STATUS | SOURCE | * MSB |-------1|---------13|------14|---------26|------27|---------39|--------47|------48|----49|---50|---51|--------53|------54|------56| * </pre> * * <b>Status flags</b> * <ul> * <li>MCP/FCU Status - (bit 1) indicates if MCP/FCU Selected altitude is available</li> * <li>FMS Status - (bit 14) indicates if FMS Selected altitude is available</li> * <li>Baro Status - (bit 27) indicates if barometric pressure setting is valid</li> * <li>MCP/FCU Mode Status - (bit 48) indicates if MCP/FCU mode bits are available</li> * <li> * Target source altitude - (bit 54) indicates if the selected altitude source is available. * This is not the same as the information stored in bit 1 see information below on MCP/FCU Altitude * </li> * </ul> * * <h2>MCP/FCU Selected altitude</h2> * * <p> * This information which represents the real “aircraft intent,” when available, * represented by the altitude control panel selected altitude, * the flight management system selected altitude, * or the current aircraft altitude according to the aircraft’s mode of flight * (the intent may not be available at all when the pilot is flying the aircraft). * </p> * * <p> * Source is determined using Target Altitude Source (bit 55-56) and is only available if status bit (bit 54) is set to 1. * See {@link SelectedAltitudeSource} for more details * </p> * * <i>Note: LSB (1 bit) = 16feet with a range 0 - 65520 feet, this class considers altitudes above 50000ft as invalid / error.</i> * * <h2>FMS Selected altitude</h2> * * <p> * This field when available indicates the FMS selected altitude. * This field could differ when selects a different altitude on the MCP/FCU panel * </p> * * <p> * Example: FMS has VNAV altitude set at 32000ft, the aircraft is at 26000ft and instructed to climb to 30000ft. * At this moment the pilot selects 30000ft on the MCP/FCU which is transmitted in the MCP/FCU field. * The FMS selected altitude field is transmitting 32000ft, the Target Altitude Source flag is set to MCP. * </p> * * <i>Note: LSB (1 bit) = 16feet with a range 0 - 65520 feet, this class considers altitudes above 50000ft as invalid / error.</i> * * <h2>Barometric Pressure Setting</h2> * * <p>When status flag (bit 27) is set to false indicates the information is valid and van be used</p> * * <i>Note: LSB (1 bit) = 0.1mb with a range 0 - 410mb. You need to add 800mb to receive the real baro steting</i> * * <h2>MCP/FCU Mode bits</h2> * <p> * Only available if Status (bit 48) is set. * * <ul> * <li>VNAV Mode (bit 49) - Indicates if VNAV navigation is engaged</li> * <li>ALT Hold Mode (bit 50) - Indicates if altitude hold is enabled</li> * <li>APP Mode (bit 51) - Indicates if Apprach mode is selected</li> * </ul> */ public class Bds40 extends Bds { private boolean statusMcp; private boolean statusFms; private boolean statusBaro; private boolean statusMcpMode; private boolean statusTargetSource; private SelectedAltitudeSource selectedAltitudeSource; private int selectedAltitude; private int fmsAltitude; private double baro; private boolean autopilotVnav; private boolean autopilotAltitudeHold; private boolean autopilotApproach; public Bds40(short[] data) { super(data); statusMcp = (data[4] & 0b10000000) != 0; statusFms = (data[5] & 0b00000100) != 0; statusBaro = (data[7] & 0b00100000) != 0; statusMcpMode = (data[9] & 0b00000001) != 0; statusTargetSource = (data[10] & 0b00000100) != 0; boolean reservedZeroA = ((data[8] & 0x1) | (data[9] >>> 1)) == 0; boolean reservedZeroB = ((data[10] >>> 3) & 0x3) == 0; if (!reservedZeroA) { invalidate(); return; } if (!reservedZeroB) { invalidate(); return; } selectedAltitude = (((data[4] & 0b01111111) << 5) | (data[5] & 0b11111000) >>> 3) * 16; if (statusMcp) { if (selectedAltitude > 50000) { invalidate(); return; } } else { if (selectedAltitude != 0) { invalidate(); return; } } fmsAltitude = (((data[5] & 0x3) << 10) | (data[6] << 2) | ((data[7] >>> 6) & 0x3)) * 16; if (statusFms) { if (fmsAltitude <= 0 || fmsAltitude > 50000) { invalidate(); return; } } else { if (fmsAltitude != 0) { invalidate(); return; } } baro = ((((data[7] & 0x1F) << 7) | (data[8] >>> 1)) * 0.1) + 800.0; if (statusBaro) { if (baro < 850 || baro > 1100) { invalidate(); return; } } else { if (baro != 800) { invalidate(); return; } } autopilotVnav = (data[10] & 0b10000000) != 0; autopilotAltitudeHold = (data[10] & 0b01000000) != 0; autopilotApproach = (data[10] & 0b00100000) != 0; if (!statusMcpMode) { if (autopilotAltitudeHold || autopilotVnav || autopilotApproach) { invalidate(); return; } } int selectedSource = data[10] & 0b00000011; if (statusTargetSource) { selectedAltitudeSource = SelectedAltitudeSource.find(selectedSource); } else { if (selectedSource != 0) { invalidate(); return; } } } @Override public void apply(Track track) { if (statusMcp) track.setSelectedAltitude(selectedAltitude); if (statusFms) track.setFmsSelectedAltitude(fmsAltitude); if (statusBaro) track.setBaroSetting(baro); if (statusMcpMode) { track.setVnav(autopilotVnav); track.setAltitudeHold(autopilotAltitudeHold); track.setApproachMode(autopilotApproach); } if (statusTargetSource) { track.setSelectedAltitudeSource(selectedAltitudeSource); } } @Override protected void reset() { statusMcp = false; statusFms = false; statusBaro = false; statusMcpMode = false; statusTargetSource = false; selectedAltitudeSource = null; selectedAltitude = 0; fmsAltitude = 0; baro = 0; autopilotVnav = false; autopilotAltitudeHold = false; autopilotApproach = false; } public boolean isStatusMcp() { return statusMcp; } public boolean isStatusFms() { return statusFms; } public boolean isStatusBaro() { return statusBaro; } public boolean isStatusMcpMode() { return statusMcpMode; } public boolean isStatusTargetSource() { return statusTargetSource; } public SelectedAltitudeSource getSelectedAltitudeSource() { return selectedAltitudeSource; } public int getSelectedAltitude() { return selectedAltitude; } public int getFmsAltitude() { return fmsAltitude; } public double getBaro() { return baro; } public boolean isAutopilotVnav() { return autopilotVnav; } public boolean isAutopilotAltitudeHold() { return autopilotAltitudeHold; } public boolean isAutopilotApproach() { return autopilotApproach; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds44.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Meteo; import aero.t2s.modes.Track; import aero.t2s.modes.constants.Hazard; import aero.t2s.modes.constants.MeteoSource; public class Bds44 extends Bds { private static final double WIND_DIRECTION_ACCURACY = 180d / 256d; private static final double SAT_ACCURACY = 0.25; private static final double HUMIDITY_ACCURACY = 100d / 64d; private MeteoSource source; private int windSpeed; private boolean statusWindSpeed; private double windDirection; private double humidity; private boolean statusHumidity; private boolean statusTurbulence; private Hazard turbulence; private int averageStaticPressure; private boolean statusAverageStaticPressure; private double staticAirTemperature; public Bds44(short[] data) { super(data); source = MeteoSource.find(data[4] >>> 4); if (source == MeteoSource.INVALID || source == MeteoSource.RESERVED) { invalidate(); return; } statusWindSpeed = (data[4] & 0b00001000) != 0; windSpeed = (data[4] & 0b00000111) << 6 | data[5] >> 2; windDirection = ((data[5] & 0b00000011) << 7 | data[6] >> 1) * WIND_DIRECTION_ACCURACY; if (!statusWindSpeed && windSpeed != 0) { invalidate(); return; } // According to Annex 3 wind speed is range 0, 250 if (statusWindSpeed && windSpeed > 250) { invalidate(); return; } boolean isSatNegative = (data[6] & 0b00000001) == 1; staticAirTemperature = (data[7] << 2 | data[8] >>> 6) * SAT_ACCURACY * (isSatNegative ? -1 : 1); if (staticAirTemperature > 60 || staticAirTemperature < -80) { invalidate(); return; } statusAverageStaticPressure = (data[8] & 0b00100000) != 0; averageStaticPressure = ((data[8] & 0b00011111) << 6) | data[9] >> 2; if (!statusAverageStaticPressure && averageStaticPressure != 0) { invalidate(); return; } statusTurbulence = (data[9] & 0b00000010) != 0; turbulence = Hazard.find(((data[9] & 0b00000001) << 1) | data[10] >>> 7); if (!statusTurbulence && turbulence != Hazard.NIL) { invalidate(); return; } statusHumidity = (data[10] & 0b01000000) != 0; humidity = (data[10] & 0b00111111) * HUMIDITY_ACCURACY; if (!statusHumidity && humidity != 0) { invalidate(); return; } } @Override public void apply(Track track) { Meteo meteo = track.getMeteo(); if (statusWindSpeed) { meteo.setWindSpeed(windSpeed); meteo.setWindDirection(windDirection); } if (statusAverageStaticPressure) meteo.setAverageStaticPressure(averageStaticPressure); if (statusTurbulence) meteo.setTurbulence(turbulence); meteo.setStaticAirTemperature(staticAirTemperature); if (statusHumidity) meteo.setHumidity(humidity); } @Override protected void reset() { statusAverageStaticPressure = false; statusWindSpeed = false; statusHumidity = false; statusTurbulence = false; source = null; windSpeed = 0; windDirection = 0; humidity = 0; turbulence = null; averageStaticPressure = 0; staticAirTemperature = 0; } public MeteoSource getSource() { return source; } public int getWindSpeed() { return windSpeed; } public boolean isStatusWindSpeed() { return statusWindSpeed; } public double getWindDirection() { return windDirection; } public double getHumidity() { return humidity; } public boolean isStatusHumidity() { return statusHumidity; } public boolean isStatusTurbulence() { return statusTurbulence; } public Hazard getTurbulence() { return turbulence; } public int getAverageStaticPressure() { return averageStaticPressure; } public boolean isStatusAverageStaticPressure() { return statusAverageStaticPressure; } public double getStaticAirTemperature() { return staticAirTemperature; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds45.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Meteo; import aero.t2s.modes.Track; import aero.t2s.modes.constants.Hazard; public class Bds45 extends Bds { private static final double SAT_ACCURACY = 0.25d; private static final int RADIO_HEIGHT_ACCURACY = 16; private boolean statusTurbulence; private boolean statusWindShear; private boolean statusMicroBurst; private boolean statusIcing; private boolean statusWake; private boolean statusSat; private boolean statusAverageStaticPressure; private boolean statusRadioHeight; private Hazard turbulence; private Hazard windShear; private Hazard microBurst; private Hazard icing; private Hazard wake; private double sat; private int averageStaticPressure; private int radioHeight; public Bds45(short[] data) { super(data); statusTurbulence = data[4] >>> 7 == 1; statusWindShear = ((data[4] & 0b00010000) >>> 4) == 1; statusMicroBurst = ((data[4] & 0b00000010) >>> 1) == 1; statusIcing = ((data[5] & 0b01000000) >>> 6) == 1; statusWake = ((data[5] & 0b00001000) >>> 3) == 1; statusSat = (data[5] & 0b00000001) == 1; statusAverageStaticPressure = ((data[7] & 0b00100000) >>> 5) == 1; statusRadioHeight = ((data[8] & 0b00000010) >>> 1) == 1; // Reserved if ((data[10] & 0b00011111) != 0) { invalidate(); return; } if (! (statusTurbulence || statusWindShear || statusMicroBurst || statusIcing || statusWake || statusSat || statusAverageStaticPressure || statusRadioHeight)) { invalidate(); return; } turbulence = Hazard.find((data[4] & 0b01100000) >>> 5); if (!statusTurbulence && turbulence != Hazard.NIL) { invalidate(); return; } windShear = Hazard.find((data[4] & 0b00001100) >>> 2); if (!statusWindShear && windShear != Hazard.NIL) { invalidate(); return; } microBurst = Hazard.find((data[4] & 0b00000001) << 1 | data[5] >> 7); if (!statusMicroBurst && microBurst != Hazard.NIL) { invalidate(); return; } icing = Hazard.find((data[5] & 0b00110000) >>> 4); if (!statusIcing && icing != Hazard.NIL) { invalidate(); return; } wake = Hazard.find((data[5] & 0b00000110) >>> 1); if (!statusWake && wake != Hazard.NIL) { invalidate(); return; } boolean isSatNegative = data[6] >>> 7 == 1; sat = (((data[6] & 0b01111111) << 2) | data[7] >>> 6) * SAT_ACCURACY * (isSatNegative ? -1 : 1); if (!statusSat && sat != 0) { invalidate(); return; } if (statusSat && (sat > 60 || sat < -80)) { invalidate(); return; } averageStaticPressure = ((data[7] & 0b00011111) << 6) | data[8] >>> 2; if (!statusAverageStaticPressure && averageStaticPressure != 0) { invalidate(); return; } if (statusAverageStaticPressure && averageStaticPressure >= 1050) { invalidate(); return; } radioHeight = (((data[8] & 0b00000001) << 11) | (data[9] << 3) | data[10] >>> 5) * RADIO_HEIGHT_ACCURACY; if (!statusRadioHeight && radioHeight != 0) { invalidate(); return; } } @Override public void apply(Track track) { Meteo meteo = track.getMeteo(); if (statusTurbulence) meteo.setTurbulence(turbulence); if (statusWindShear) meteo.setWindShear(windShear); if (statusMicroBurst) meteo.setMicroBurst(microBurst); if (statusIcing) meteo.setIcing(icing); if (statusWake) meteo.setWake(wake); if (statusSat) meteo.setStaticAirTemperature(sat); if (statusAverageStaticPressure) meteo.setAverageStaticPressure(averageStaticPressure); if (statusRadioHeight) meteo.setRadioHeight(radioHeight); } @Override protected void reset() { statusTurbulence = false; statusWindShear = false; statusMicroBurst = false; statusIcing = false; statusWake = false; statusSat = false; statusAverageStaticPressure = false; statusRadioHeight = false; turbulence = null; windShear = null; microBurst = null; icing = null; wake = null; sat = 0; averageStaticPressure = 0; radioHeight = 0; } public boolean isStatusTurbulence() { return statusTurbulence; } public boolean isStatusWindShear() { return statusWindShear; } public boolean isStatusMicroBurst() { return statusMicroBurst; } public boolean isStatusIcing() { return statusIcing; } public boolean isStatusWake() { return statusWake; } public boolean isStatusSat() { return statusSat; } public boolean isStatusAverageStaticPressure() { return statusAverageStaticPressure; } public boolean isStatusRadioHeight() { return statusRadioHeight; } public Hazard getTurbulence() { return turbulence; } public Hazard getWindShear() { return windShear; } public Hazard getMicroBurst() { return microBurst; } public Hazard getIcing() { return icing; } public Hazard getWake() { return wake; } public double getSat() { return sat; } public int getAverageStaticPressure() { return averageStaticPressure; } public int getRadioHeight() { return radioHeight; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds50.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; /** * 56-bit MB Field is structured in the following format * <pre> * Bit | * 01 | Status * 02 | Sign (Left wing down) * 03 | MSB Roll angle (45 degrees) * 04 | Roll angle cont. * 05 | Roll angle cont. * 06 | Roll angle cont. * 07 | Roll angle cont. * 08 | Roll angle cont. * --------------------------------------- * 09 | Roll angle cont. * 10 | Roll angle cont. * 11 | LSB roll angle (45/256 degrees) * 12 | Status * 13 | Sign (West) * 14 | MSB True track angle (90 degrees) * 15 | True Track Angle cont. * 16 | True Track Angle cont. * --------------------------------------- * 17 | True Track Angle cont. * 18 | True Track Angle cont. * 19 | True Track Angle cont. * 20 | True Track Angle cont. * 21 | True Track Angle cont. * 22 | True Track Angle cont. * 23 | LSB True Track Angle (90/512 degrees) * 24 | Status * --------------------------------------- * 25 | MSB Ground Speed (1024kt) * 26 | Ground Speed cont. * 27 | Ground Speed cont. * 28 | Ground Speed cont. * 29 | Ground Speed cont. * 30 | Ground Speed cont. * 31 | Ground Speed cont. * 32 | Ground Speed cont. * --------------------------------------- * 33 | Ground Speed cont. * 34 | LSB Ground Speed (2kt) * 35 | Status * 36 | Sign (Minus) * 37 | MSB Track Angle Rate (8 degrees / second) * 38 | Track Angle Rate cont. * 39 | Track Angle Rate cont. * 40 | Track Angle Rate cont. * --------------------------------------- * 41 | Track Angle Rate cont. * 42 | Track Angle Rate cont. * 43 | Track Angle Rate cont. * 44 | Track Angle Rate cont. * 45 | LSB Track Angle Rate (8/256 degrees / second) * 46 | Status * 47 | MSB True Airspeed (1024kt) * 48 | True Airspeed cont. * --------------------------------------- * 49 | True Airspeed cont. * 50 | True Airspeed cont. * 51 | True Airspeed cont. * 52 | True Airspeed cont. * 53 | True Airspeed cont. * 54 | True Airspeed cont. * 55 | True Airspeed cont. * 56 | LSB True Airspeed (2kt) * </pre> * * <b>Status flags</b> * <ul> * <li>Roll Angle (bit 1) - Indicates if Roll Angle is available/valid</li> * <li>True Track Angle (bit 12) - Indicates if true track angle is available/valid</li> * <li>Ground Speed (bit 24) - Indicates if ground speed available/valid</li> * <li>Track Angle Rate (bit 35) - Indicates if ground speed available/valid</li> * <li>True Airspeed (bit 46) - Indicates if true airspeed is available/valid</li> * </ul> * * <h2>Roll Angle</h2> * * <p>Roll angle or bank angle tells you if the aircraft is banking to the left or to the right and how many degrees.</p> * * <p> * Sign (bit 2) determines if the aircraft is banking left (1) or right (0). * When the aircraft is flying straight sign may either set to 1 or 0 with zero angle. * </p> * * <i> * NOTE: If the status flag (bit 1) is not enabled ALL bits (2 through 11) need to be actively set to zero. * </i> * * <i> * NOTE2: LSB shows resolution of 45/256degrees, the total range of the field roll angle is 0-90. * </i> * * <h2>True Track Angle</h2> * * <p>Is the direction the aircraft is flying relative to the ground and true north.</p> * * <i> * NOTE: Sign flag (bit 13) determines West (1) and East (0). Sign is 1 then 315 degrees is transmitted as 45degrees. * Or to get the direction 0-360 range you need to add 180 degrees when west is set to 1. * </i> * * <i> * NOTE2: If the status flag (bit 1) is not enabled ALL bits (2 through 11) need to be actively set to zero. * </i> * * <i> * NOTE3: LSB shows resolution of 45/256degrees, the total range of the field roll angle is 0-90. * </i> * <h2>Ground Speed</h2> * <h2>Track Angle Rate</h2> * <h2>True Airspeed</h2> */ public class Bds50 extends Bds { private static final double ROLL_ACCURACY = 45.0 / 256.0; private static final double TRUE_TRACK_ANGLE_ACCURACY = 90.0 / 512.0; private static final double SPEED_ACCURACY = 2; private static final double TRUE_TRACK_RATE_ACCURACY = 8.0 / 256.0; private boolean statusRollAngle; private boolean statusTrackAngle; private boolean statusGs; private boolean statusTrueAngleRate; private boolean statusTas; private double gs; private double trackAngleRate; private double trueTrack; private double tas; private double rollAngle; public Bds50(short[] data) { super(data); statusRollAngle = ((data[4] >>> 7) & 0x1) == 1; statusTrackAngle = ((data[5] >>> 4) & 0x1) == 1; statusGs = (data[6] & 0x1) == 1; statusTrueAngleRate = ((data[8] >>> 5) & 0x1) == 1; statusTas = ((data[9] >>> 2) & 0x1) == 1; boolean isLeftWingDown = ((data[4] >>> 6) & 0x1) == 1; rollAngle = ((((data[4] & 0b00111111) << 3) | (data[5] >>> 5)) - (isLeftWingDown ? 512 : 0)) * ROLL_ACCURACY; if (!statusRollAngle && (isLeftWingDown || rollAngle != 0)) { invalidate(); return; } if (statusRollAngle) { if (Math.abs(rollAngle) > 50) { invalidate(); rollAngle = 0; return; } } else { rollAngle = 0; } boolean isWest = (data[5] & 0b00001000) != 0; trueTrack = (((data[5] & 0x7) << 7) | (data[6] >>> 1)); if (!statusTrackAngle && (isWest || trueTrack != 0)) { invalidate(); return; } trueTrack = trueTrack * TRUE_TRACK_ANGLE_ACCURACY + (isWest ? 180d : 0d); gs = ((data[7] << 2) | ((data[8] >>> 6) & 0x3)) * SPEED_ACCURACY; if (statusGs) { if (gs > 600) { invalidate(); return; } } else { if (gs != 0) { invalidate(); return; } } boolean isTrackAngleRateNegative = (data[8] & 0b00010000) != 0; trackAngleRate = ((data[8] & 0xF) << 5) | data[9] >>> 3; if (!statusTrueAngleRate && (isTrackAngleRateNegative || trackAngleRate != 0)) { invalidate(); return; } if (statusTrueAngleRate && trackAngleRate == 0b11111111) { invalidate(); return; } trackAngleRate = (trackAngleRate + (isTrackAngleRateNegative ? -512d : 0)) * TRUE_TRACK_RATE_ACCURACY; tas = (((data[9] & 0x3) << 8) | data[10]) * SPEED_ACCURACY; if (!statusTas && tas != 0) { invalidate(); return; } if (statusGs && statusTas && Math.abs((tas - gs)) > 200) { invalidate(); return; } } @Override public void apply(Track track) { if (statusRollAngle) track.setRollAngle(rollAngle); if (statusTrackAngle) track.setTrueHeading(trueTrack); if (statusGs) track.setGs(gs); if (statusTrueAngleRate) track.setTrackAngleRate(trackAngleRate); if (statusTas) { track.setTas(tas); } } @Override protected void reset() { statusRollAngle = false; statusTrackAngle = false; statusGs = false; statusTrueAngleRate = false; statusTas = false; gs = 0; trackAngleRate = 0; trueTrack = 0; tas = 0; rollAngle = 0; } public boolean isStatusRollAngle() { return statusRollAngle; } public boolean isStatusTrackAngle() { return statusTrackAngle; } public boolean isStatusGs() { return statusGs; } public boolean isStatusTrueAngleRate() { return statusTrueAngleRate; } public boolean isStatusTas() { return statusTas; } public double getGs() { return gs; } public double getTrackAngleRate() { return trackAngleRate; } public double getTrueTrack() { return trueTrack; } public double getTas() { return tas; } public double getRollAngle() { return rollAngle; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds53.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; public class Bds53 extends Bds { private static final double HEADING_ACCURACY = 90d / 512d; private static final double MACH_ACCURACY = 0.008d; private static final double TAS_ACCURACY = 0.5d; private static final int VS_ACCURACY = 64; private boolean statusRocd; private boolean statusTas; private boolean statusMach; private boolean statusIas; private boolean statusMagneticHeading; private double magneticHeading; private int rocd; private double tas; private double mach; private int ias; public Bds53(short[] data) { super(data); statusMagneticHeading = (data[4] & 0b10000000) == 0b10000000; statusIas = (data[5] & 0b00001000) == 0b00001000; statusMach = (data[6] & 0b00000001) == 0b00000001; statusTas = (data[8] & 0b01000000) == 0b01000000; statusRocd = (data[9] & 0b00000010) == 0b00000010; boolean isMagHdgNegative = (data[4] & 0b01000000) == 0b01000000; magneticHeading = ((((data[4] & 0b00111111) << 4) | ((data[5] & 0b11110000))) * HEADING_ACCURACY + (isMagHdgNegative ? 180 : 0)); if ((!statusMagneticHeading && magneticHeading != 0) || magneticHeading > 360) { invalidate(); return; } ias = ((data[5] & 0b00000111) << 7) | ((data[6] & 0b11111110) >>> 1); if (!statusIas && ias != 0) { invalidate(); return; } if (statusIas && ias > 500) { invalidate(); return; } mach = ((data[7] << 1) | (data[8] >>> 7)) * MACH_ACCURACY; if (!statusMach && mach != 0) { invalidate(); return; } tas = (((data[8] & 0b00111111) << 6) | ((data[9] & 0b11111100) >>> 2)) * TAS_ACCURACY; if (!statusTas && tas != 0) { invalidate(); return; } if (statusTas && tas > 500) { invalidate(); return; } boolean isRocdNegative = (data[9] & 0b00000001) == 0b00000001; rocd = data[10] * VS_ACCURACY * (isRocdNegative ? -1 : 1); if (!statusRocd && rocd != 0) { invalidate(); return; } } @Override public void apply(Track track) { if (statusMagneticHeading) track.setMagneticHeading(magneticHeading); if (statusIas) track.setIas(ias); if (statusMach) track.setMach(mach); if (statusTas) track.setTas(tas); if (statusRocd) track.setRocd(rocd); } @Override protected void reset() { statusRocd = false; statusTas = false; statusMach = false; statusIas = false; statusMagneticHeading = false; magneticHeading = 0; rocd = 0; tas = 0; mach = 0; ias = 0; } public double getMagneticHeading() { return magneticHeading; } public boolean isStatusRocd() { return statusRocd; } public boolean isStatusTas() { return statusTas; } public boolean isStatusMach() { return statusMach; } public boolean isStatusIas() { return statusIas; } public boolean isStatusMagneticHeading() { return statusMagneticHeading; } public int getRocd() { return rocd; } public double getTas() { return tas; } public double getMach() { return mach; } public int getIas() { return ias; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/Bds60.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.AltitudeEncoding; public class Bds60 extends Bds { private static final double MAG_ACCURACY = 90.0 / 512.0; private static final double MACH_ACCURACY = 2048.0 / 512.0; private static final double ROCD_ACCURCY = 8192.0 / 256.0; private boolean statusMagneticHeading; private boolean statusIas; private boolean statusMach; private boolean statusBaroRocd; private boolean statusIrsRocd; private double mach; private double magneticHeading; private int ias; private double baroRocd; private double irsRocd; public Bds60(short[] data) { super(data); statusMagneticHeading = (data[4] & 0b10000000) != 0; statusIas = (data[5] & 0b00001000) != 0; statusMach = (data[6] & 0b00000001) != 0; statusBaroRocd = (data[8] & 0b00100000) != 0; statusIrsRocd = (data[9] & 0b00000100) != 0; if (!(statusMagneticHeading || statusIas || statusMach || statusBaroRocd || statusIrsRocd)) { invalidate(); return; } double hdgSign = ((data[4] >>> 6) & 0x1) == 1 ? -1024d : 0d; magneticHeading = ((((data[4] & 0b00111111) << 4) | (data[5] >>> 4)) + hdgSign) * MAG_ACCURACY; if (magneticHeading < 0) { magneticHeading += 360d; } if (statusMagneticHeading) { if (magneticHeading < 0 || magneticHeading > 360.0) { invalidate(); return; } } else { if (magneticHeading != 0) { invalidate(); return; } } ias = ((data[5] & 0x7) << 7) | data[6] >>> 1; if (statusIas) { if (ias <= 0 || ias > 512) { invalidate(); return; } } else { if (ias != 0) { invalidate(); return; } } mach = ((data[7] << 2) | data[8] >> 6) * MACH_ACCURACY; mach /= 1000.0; if (statusMach) { if (mach <= 0 || mach > 1) { invalidate(); return; } } else { if (mach != 0) { invalidate(); return; } } double baroSign = ((data[8] >>> 4) & 0x1) == 1 ? -512.0 : 0.0; baroRocd = ((((data[8] & 0b00001111) << 5) | (data[9] >>> 3)) + baroSign) * ROCD_ACCURCY; if (statusBaroRocd) { if (baroRocd < -8000 || baroRocd > 8000) { invalidate(); return; } } else { if (baroRocd != 0) { invalidate(); return; } } double irsSign = ((data[9] >> 1) & 0x1) == 1 ? -512.0 : 0.0; irsRocd = (((data[9] & 0x1) << 8 | data[10]) + irsSign) * ROCD_ACCURCY; if (statusIrsRocd) { if (irsRocd < -8000 || irsRocd > 6000) { invalidate(); return; } } else { if (irsRocd != 0) { invalidate(); return; } } if (statusMach && statusIas && data[0] >>> 3 == 20) { double altitude = AltitudeEncoding.decode((data[2] & 0x1F) << 8 | data[3]).getAltitude(); if (altitude > 0) { double cas = machToCas(altitude * 0.3048) / 0.514444; if (Math.abs(cas - ias) > 20) { invalidate(); return; } } } } private double machToCas(double altitude) { return tasToCas(machToTas(altitude), altitude); } private double tasToCas(double tas, double altitude) { double rho0 = 1.225; double T = Math.max(288.15 - 0.0065 * altitude, 216.65); double rhotrop = 1.225 * Math.pow((T / 288.15), 4.256848030018761); double dhstrat = Math.max(0.0, altitude - 11000.0); double rho = rhotrop * Math.exp(-dhstrat / 6341.552161); double R = 287.05287; // m2/(s2 x K), gas constant, sea level ISA double p = rho * R * T; double p0 = 101325.0; // Pa, air pressure, sea level ISA double qdyn = p * (Math.pow((1.0 + rho * tas * tas / (7.0 * p)), 3.5) - 1.0); return Math.sqrt(7.0 * p0 / rho0 * (Math.pow((qdyn / p0 + 1.0), (2.0 / 7.0)) - 1.0)); } private double machToTas(double altitude) { double T = Math.max(288.15 - 0.0065 * altitude, 216.65); double R = 287.05287; // m2/(s2 x K), gas constant, sea level ISA double gamma = 1.40; // cp/cv for air double a = Math.sqrt(gamma * R * T); return mach * a; } @Override public void apply(Track track) { track.setMagneticHeading(magneticHeading); track.setIas(ias); track.setMach(mach); track.setBaroRocd(baroRocd); track.setRocd((int) irsRocd); track.setRocdAvailable(true); track.setRocdSourceBaro(!statusIrsRocd); } @Override protected void reset() { statusMagneticHeading = false; statusIas = false; statusMach = false; statusBaroRocd = false; statusIrsRocd = false; mach = 0; magneticHeading = 0; ias = 0; baroRocd = 0; irsRocd = 0; } public boolean isStatusMagneticHeading() { return statusMagneticHeading; } public boolean isStatusIas() { return statusIas; } public boolean isStatusMach() { return statusMach; } public boolean isStatusBaroRocd() { return statusBaroRocd; } public boolean isStatusIrsRocd() { return statusIrsRocd; } public double getMach() { return mach; } public double getMagneticHeading() { return magneticHeading; } public int getIas() { return ias; } public double getBaroRocd() { return baroRocd; } public double getIrsRocd() { return irsRocd; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/BdsDecoder.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.EmptyMessageException; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.decoder.Common; import java.util.LinkedList; import java.util.List; public class BdsDecoder { private final short[] data; private final List<Bds> bdsMessages = new LinkedList<>(); private final List<Bds> valid = new LinkedList<>(); public BdsDecoder(short[] data) { this.data = data; bdsMessages.add(new Bds10(data)); bdsMessages.add(new Bds20(data)); bdsMessages.add(new Bds17(data)); bdsMessages.add(new Bds30(data)); bdsMessages.add(new Bds40(data)); bdsMessages.add(new Bds50(data)); bdsMessages.add(new Bds53(data)); bdsMessages.add(new Bds60(data)); bdsMessages.add(new Bds21(data)); bdsMessages.add(new Bds44(data)); bdsMessages.add(new Bds45(data)); } public Bds decode() throws MultipleBdsMatchesFoundException, EmptyMessageException, NotImplementedException { // Indicates no message is present and is most likely a reply to a uplink request Altitude from ground station. if (data[4] == 0 && data[5] == 0 && data[6] == 0 && data[7] == 0 && data[8] == 0 && data[9] == 0 && data[10] == 0) { throw new EmptyMessageException(); } for (Bds message : bdsMessages) { if (message.isValid()) { valid.add(message); } } if (valid.size() == 0) { throw new NotImplementedException("No matching BDS found for " + Common.toHexString(data)); } if (valid.size() > 1) { throw new MultipleBdsMatchesFoundException(valid); } return valid.get(0); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/bds/MultipleBdsMatchesFoundException.java
package aero.t2s.modes.decoder.df.bds; import aero.t2s.modes.DownlinkException; import java.util.List; public class MultipleBdsMatchesFoundException extends Throwable implements DownlinkException { private final List<Bds> matches; public MultipleBdsMatchesFoundException(List<Bds> matches) { super("Multiple BDS Matches found"); this.matches = matches; } public List<Bds> getMatches() { return matches; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AirbornePosition.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.BarometricAltitudeIntegrityCode; import aero.t2s.modes.constants.SurveillanceStatus; import aero.t2s.modes.constants.Version; public class AirbornePosition extends ExtendedSquitter { private final double originLat; private final double originLon; private SurveillanceStatus surveillanceStatus; private int singleAntennaFlag; private boolean altitudeSourceBaro; private int altitude; private boolean positionAvailable; private double lat; private double lon; public AirbornePosition(short[] data, final double originLat, final double originLon) { super(data); this.originLat = originLat; this.originLon = originLon; } @Override public AirbornePosition decode() { surveillanceStatus = SurveillanceStatus.from((data[4] >>> 1) & 0x3); singleAntennaFlag = data[4] & 0x1; // Calculate altitude altitude = calculateAltitude(data, typeCode); if (typeCode < 20) { altitudeSourceBaro = true; } // Decode position if (typeCode == 0) { // No position information in TC=0 packets return this; } positionAvailable = true; int time = (data[6] >>> 3) & 0x1; boolean cprEven = ((data[6] >>> 2) & 0x1) == 0; int cprLat = (data[6] & 0x3) << 15; cprLat = cprLat | (data[7] << 7); cprLat = cprLat | (data[8] >>> 1); int cprLon = ((data[8] & 0x1) << 16); cprLon = cprLon | (data[9] << 8); cprLon = cprLon | data[10]; calculatePosition(cprEven, ((double)cprLat) / ((double)(1 << 17)), ((double)cprLon) / ((double)(1 << 17)), time); return this; } @Override public void apply(Track track) { track.setGroundBit(false); track.setSpi(surveillanceStatus == SurveillanceStatus.SPI); track.setTempAlert(surveillanceStatus == SurveillanceStatus.TEMPORARY_ALERT); track.setEmergency(surveillanceStatus == SurveillanceStatus.PERMANENT_ALERT); // Determine Antenna or Navigation Integrity Category if (track.getVersion().ordinal() < Version.VERSION2.ordinal()) { track.setSingleAntenna(singleAntennaFlag == 0); } else { track.setNICb(singleAntennaFlag); } if (altitudeSourceBaro) { track.setBaroAltitude(altitude); } else { track.setGnssHeight(altitude); } track.setNIC(determineNIC(track, typeCode)); track.setLat(lat); track.setLon(lon); } public int getSingleAntennaFlag() { // Version 0/1 return singleAntennaFlag; } public BarometricAltitudeIntegrityCode getNICbaro() { // Version 2 try { return BarometricAltitudeIntegrityCode.from(singleAntennaFlag); } catch (IllegalArgumentException e) { return BarometricAltitudeIntegrityCode.NOT_CROSS_CHECKED; } } public double getOriginLat() { return originLat; } public double getOriginLon() { return originLon; } public SurveillanceStatus getSurveillanceStatus() { return surveillanceStatus; } public boolean isAltitudeSourceBaro() { return altitudeSourceBaro; } public int getAltitude() { return altitude; } public boolean isPositionAvailable() { return positionAvailable; } public double getLat() { return lat; } public double getLon() { return lon; } private int determineNIC(Track track, int typeCode) { switch (typeCode) { case 9: case 20: return 11; case 10: case 21: return 10; case 11: if (track.getNICa() == 1 && track.getNICb() == 1) { return 9; } else if (track.getNICa() == 0 && track.getNICb() == 0) { return 8; } else { return 0; } case 12: return 7; case 13: return 6; case 14: return 5; case 15: return 4; case 16: if (track.getNICa() == 0 && track.getNICb() == 0) { return 2; } else if (track.getNICa() == 1 && track.getNICb() == 1) { return 3; } else { return 0; } case 17: return 1; case 18: case 22: default: return 0; } } private void calculatePosition(boolean isEven, double lat, double lon, double time) { // CprPosition cprEven = track.getCprPosition(true); // CprPosition cprOdd = track.getCprPosition(false); // if (! (cprEven.isValid() && cprOdd.isValid())) { calculateLocal(isEven, lat, lon, time); // return; // } // calculateGlobal(track, cprEven, cprOdd); } private void calculateLocal(boolean isEven, double lat, double lon, double time) { boolean isOdd = !isEven; // CprPosition cpr = track.getCprPosition(isEven); double dlat = isOdd ? 360.0 / 59.0 : 360.0 / 60.0; double j = Math.floor(originLat / dlat) + Math.floor((originLat % dlat) / dlat - lat + 0.5); lat = dlat * (j + lat); double nl = NL(lat) - (isOdd ? 1.0 : 0.0); double dlon = nl > 0 ? 360.0 / nl : 360; double m = Math.floor(originLon / dlon) + Math.floor((originLon % dlon) / dlon - lon + 0.5); lon = dlon * (m + lon); this.lat = lat; this.lon = lon; } // private void calculateGlobal(Track track, CprPosition cprEven, CprPosition cprOdd) { // double dLat0 = 360.0 / 60.0; // double dLat1 = 360.0 / 59.0; // // double j = Math.floor(59.0 * cprEven.getLat() - 60.0 * cprOdd.getLat() + 0.5); // // double latEven = dLat0 * (j % 60.0 + cprEven.getLat()); // double latOdd = dLat1 * (j % 59.0 + cprOdd.getLat()); // // if (latEven >= 270.0 && latEven <= 360.0) { // latEven -= 360.0; // } // // if (latOdd >= 270.0 && latOdd <= 360.0) { // latOdd -= 360.0; // } // // if (NL(latEven) != NL(latOdd)) { // return; // } // // double lat; // double lon; // if (cprEven.getTime() > cprOdd.getTime()) { // double ni = cprN(latEven, 0); // double m = Math.floor(cprEven.getLon() * (NL(latEven) - 1) - cprOdd.getLon() * NL(latEven) + 0.5); // // lat = latEven; // lon = (360d / ni) * (m % ni + cprEven.getLon()); // } else { // double ni = cprN(latOdd, 1); // double m = Math.floor(cprEven.getLon() * (NL(latOdd) - 1) - cprOdd.getLon() * NL(latOdd) + 0.5); // // lat = latOdd; // lon = (360d / ni) * (m % ni + cprOdd.getLon()); // } // // if (lon > 180d) { // lon -= 360d; // } // // track.setLat(lat); // track.setLon(lon); // } // private double cprN(double lat, double isOdd) { // double nl = NL(lat) - isOdd; // // return nl > 1 ? nl : 1; // } private double NL(double lat) { if (lat == 0) return 59; else if (Math.abs(lat) == 87) return 2; else if (Math.abs(lat) > 87) return 1; double tmp = 1 - (1 - Math.cos(Math.PI / (2.0 * 15.0))) / Math.pow(Math.cos(Math.PI / 180.0 * Math.abs(lat)), 2); return Math.floor(2 * Math.PI / Math.acos(tmp)); } private int calculateAltitude(short[] data, int typeCode) { // TODO this should use AltitudeEncoding class flagged with mBit false feature. int n = (data[5] >>> 1) << 4; n = n | (data[6] >>> 4); int qBit = (data[5] & 0x1) == 1 ? 25 : 100; // true: 25ft, false: 100 return (n * qBit) - 1000; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AirborneVelocity.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.constants.NavigationUncertaintyCategory; import aero.t2s.modes.constants.RocdSource; public class AirborneVelocity extends ExtendedSquitter { protected NavigationUncertaintyCategory NACv; private int subType; private boolean supersonic; private boolean intentChange; private boolean ifrCapability; private boolean rocdAvailable; private RocdSource rocdSource; private int rocd; private boolean gnssAltitudeDifferenceFromBaroAvailable; private int gnssAltitudeDifferenceFromBaro; public AirborneVelocity(short[] data) { super(data); } @Override public AirborneVelocity decode() { int subType = data[4] & 0x7; switch (subType) { case 1: case 2: return new AirborneVelocityGroundspeed(data).decode(); case 3: case 4: return new AirborneVelocityAirspeedHeading(data).decode(); default: throw new NotImplementedException("BDS0,9 sub type " + subType + " is not implemented"); } } @Override public void apply(Track track) { // Nothing } protected void decodeCommonInformation() { subType = data[4] & 0b00000111; supersonic = subType == 2; intentChange = (data[5] & 0b10000000) != 0; ifrCapability = (data[5] & 0b01000000) != 0; NACv = NavigationUncertaintyCategory.from((data[5] & 0b00111000) >>> 3); rocdSource = (data[8] & 0b00010000) != 0 ? RocdSource.BARO : RocdSource.GNSS; rocd = ((data[8] & 0b00000111) << 6) | (data[9] & 0b11111100) >>> 2; rocdAvailable = rocd != 0; rocd = (rocd - 1) * 64; if ((data[8] & 0b00001000) != 0) { rocd *= -1; } gnssAltitudeDifferenceFromBaro = data[10] & 0b01111111; gnssAltitudeDifferenceFromBaroAvailable = gnssAltitudeDifferenceFromBaro != 0; gnssAltitudeDifferenceFromBaro = (gnssAltitudeDifferenceFromBaro - 1) * 25; if ((data[10] & 0b10000000) != 0) { gnssAltitudeDifferenceFromBaro *= -1; } } public NavigationUncertaintyCategory getNACv() { return NACv; } public int getSubType() { return subType; } public boolean isSupersonic() { return supersonic; } public boolean isIntentChange() { return intentChange; } public boolean isIfrCapability() { return ifrCapability; } public boolean isRocdAvailable() { return rocdAvailable; } public RocdSource getRocdSource() { return rocdSource; } public int getRocd() { return rocd; } public boolean isGnssAltitudeDifferenceFromBaroAvailable() { return gnssAltitudeDifferenceFromBaroAvailable; } public int getGnssAltitudeDifferenceFromBaro() { return gnssAltitudeDifferenceFromBaro; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AirborneVelocityAirspeedHeading.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.RocdSource; import aero.t2s.modes.constants.Speed; public class AirborneVelocityAirspeedHeading extends AirborneVelocity { private static final double HEADING_RESOLUTION = 360.0 / 1024.0; private boolean headingAvailable; private double heading; private boolean airspeedAvailable; private Speed airspeedType; private int airspeed; public AirborneVelocityAirspeedHeading(short[] data) { super(data); } @Override public AirborneVelocityAirspeedHeading decode() { decodeCommonInformation(); headingAvailable = (data[5] & 0b00000100) != 0; heading = (((data[5] & 0b00000011) << 8) | data[6]) * HEADING_RESOLUTION; airspeed = ((data[7] & 0b01111111) << 3) | (data[8] & 0b11100000) >>> 5; airspeedAvailable = airspeed != 0; airspeed = (airspeed - 1) * (isSupersonic() ? 4 : 1); airspeedType = ((data[7] & 0b10000000) != 0) ? Speed.TAS : Speed.IAS; return this; } @Override public void apply(Track track) { track.setNACv(NACv.ordinal()); if (isGnssAltitudeDifferenceFromBaroAvailable()) { track.setGeometricHeightOffset(getGnssAltitudeDifferenceFromBaro()); } if (isRocdAvailable()) { track.setRocdAvailable(true); track.setRocdSourceBaro(getRocdSource() == RocdSource.BARO); if (getRocdSource() == RocdSource.BARO) { track.setBaroRocd(getRocd()); } else { track.setRocd(getRocd()); } } } public boolean isHeadingAvailable() { return headingAvailable; } public double getHeading() { return heading; } public boolean isAirspeedAvailable() { return airspeedAvailable; } public Speed getAirspeedType() { return airspeedType; } public int getAirspeed() { return airspeed; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AirborneVelocityGroundspeed.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.RocdSource; public class AirborneVelocityGroundspeed extends AirborneVelocity { private boolean xVelocityAvailable; private int xVelocity; private boolean yVelocityAvailable; private int yVelocity; public AirborneVelocityGroundspeed(short[] data) { super(data); } @Override public AirborneVelocityGroundspeed decode() { decodeCommonInformation(); xVelocity = ((data[5] & 0b00000011) << 8) | data[6]; xVelocityAvailable = xVelocity != 0; xVelocity = (xVelocity - 1) * (isSupersonic() ? 4 : 1); if ((data[5] & 0b00000100) != 0) { xVelocity *= -1; } yVelocity = ((data[7] & 0b01111111) << 3) | (data[8] & 0b11100000) >>> 5; yVelocityAvailable = yVelocity != 0; yVelocity = (yVelocity - 1) * (isSupersonic() ? 4 : 1); if ((data[7] & 0b10000000) != 0) { yVelocity *= -1; } return this; } @Override public void apply(Track track) { track.setNACv(NACv.ordinal()); if (isGnssAltitudeDifferenceFromBaroAvailable()) { track.setGeometricHeightOffset(getGnssAltitudeDifferenceFromBaro()); } if (isRocdAvailable()) { track.setRocdAvailable(true); track.setRocdSourceBaro(getRocdSource() == RocdSource.BARO); if (getRocdSource() == RocdSource.BARO) { track.setBaroRocd(getRocd()); } else { track.setRocd(getRocd()); } } if (xVelocityAvailable) { track.setVx(xVelocity); } if (yVelocityAvailable) { track.setVy(yVelocity); } if (xVelocityAvailable && yVelocityAvailable) { track.setGs(Math.sqrt(xVelocity * xVelocity + yVelocity * yVelocity)); } } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftIdentification.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.decoder.Common; public class AircraftIdentification extends ExtendedSquitter { private String acid; public AircraftIdentification(short[] data) { super(data); } @Override public AircraftIdentification decode() { acid = Common.charToString(data[5] >>> 2) + Common.charToString(((data[5] & 0x3) << 4) | (data[6] >>> 4)) + Common.charToString(((data[6] & 0xF) << 2) | (data[7] >>> 6)) + Common.charToString(data[7] & 0x3F) + Common.charToString(data[8] >>> 2) + Common.charToString(((data[8] & 0x3) << 4) | (data[9] >>> 4)) + Common.charToString(((data[9] & 0xF) << 2) | (data[10] >>> 6)) + Common.charToString(data[10] & 0x3F); acid = acid.replace("_", ""); return this; } @Override public void apply(Track track) { track.setCallsign(acid); } public String getAcid() { return acid; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusMessage.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.constants.Version; public class AircraftOperationalStatusMessage extends ExtendedSquitter { private Version version; public AircraftOperationalStatusMessage(short[] data) { super(data); } @Override public AircraftOperationalStatusMessage decode() { version = Version.from(data[9] >>> 5); switch (version) { case VERSION0: return new AircraftOperationalStatusVersion0(data).decode(); case VERSION1: return new AircraftOperationalStatusVersion1(data).decode(); case VERSION2: return new AircraftOperationalStatusVersion2(data).decode(); default: throw new NotImplementedException("Aircraft Status Version " + version.name() + " is not implemented"); } } @Override public void apply(Track track) { // Nothing to do here } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion0.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.constants.Version; public class AircraftOperationalStatusVersion0 extends AircraftOperationalStatusMessage { public AircraftOperationalStatusVersion0(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion0 decode() { throw new NotImplementedException("AircraftOperationalStatusVersion0 not implemented"); } @Override public void apply(Track track) { track.setVersion(Version.VERSION0); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion1.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class AircraftOperationalStatusVersion1 extends AircraftOperationalStatusMessage { public AircraftOperationalStatusVersion1(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion1 decode() { int subType = data[4] & 0x7; switch (subType) { case 0: return new AircraftOperationalStatusVersion1Airborne(data).decode(); case 1: return new AircraftOperationalStatusVersion1Surface(data).decode(); default: throw new NotImplementedException("Aircraft operation status version 1 sub type " + subType + " is not known"); } } @Override public void apply(Track track) { // Nothing } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion1Airborne.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; import aero.t2s.modes.decoder.df.df17.data.AirborneCapability; import aero.t2s.modes.decoder.df.df17.data.AirborneOperationalMode; public class AircraftOperationalStatusVersion1Airborne extends AircraftOperationalStatusVersion1 { private int subType = 0; private Version version = Version.VERSION1; private AirborneCapability capability; private AirborneOperationalMode operationalMode; private NavigationIntegrityCategory NICp; private SourceIntegrityLevel SIL; private BarometricAltitudeIntegrityCode NICbaro; private Angle horizontalSource; public AircraftOperationalStatusVersion1Airborne(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion1Airborne decode() { capability = new AirborneCapability((data[5] << 8) | data[6], version); operationalMode = new AirborneOperationalMode((data[7] << 8) | data[8]); int NICsupp = (data[9] & 0b00010000) >>> 4; int NACp = (data[9] & 0b00001111); NICp = NavigationIntegrityCategory.airborne(NACp, NICsupp, 0); SIL = SourceIntegrityLevel.from((data[10] & 0b000110000) >>> 4); NICbaro = BarometricAltitudeIntegrityCode.from((data[10] & 0b00001000) >>> 3); horizontalSource = (data[10] & 0b00000100) != 0 ? Angle.TRUE_HEADING : Angle.MAGNETIC_HEADING; return this; } @Override public void apply(Track track) { track.setVersion(version); } public int getSubType() { return subType; } public Version getVersion() { return version; } public AirborneCapability getCapability() { return capability; } public AirborneOperationalMode getOperationalMode() { return operationalMode; } public NavigationIntegrityCategory getNICp() { return NICp; } public SourceIntegrityLevel getSIL() { return SIL; } public BarometricAltitudeIntegrityCode getNICbaro() { return NICbaro; } public Angle getHorizontalSource() { return horizontalSource; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion1Surface.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; import aero.t2s.modes.decoder.df.df17.data.SurfaceCapability; import aero.t2s.modes.decoder.df.df17.data.SurfaceOperationalMode; public class AircraftOperationalStatusVersion1Surface extends AircraftOperationalStatusVersion1 { private int subType = 1; private Version version = Version.VERSION1; private Angle horizontalSource; private SurfaceCapability surfaceCapability; private LengthWidthCode lengthWidthCode; private SurfaceOperationalMode operationalMode; private SourceIntegrityLevel SIL; private SourceIntegrityLevelSupplement SILsupp; private NavigationIntegrityCategory NICp; public AircraftOperationalStatusVersion1Surface(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion1Surface decode() { surfaceCapability = new SurfaceCapability((data[5] << 4) | (data[6] & 0b11110000) >>> 4, version); lengthWidthCode = LengthWidthCode.from(data[6] & 0b00001111); operationalMode = new SurfaceOperationalMode((data[7] << 8) | data[8]); SIL = SourceIntegrityLevel.from((data[10] & 0b000110000) >>> 4); SILsupp = SourceIntegrityLevelSupplement.from((data[10] & 0b00000010) >>> 1); int NICsupp = (data[9] & 0b00010000) >>> 4; int NACp = (data[9] & 0b00001111); NICp = NavigationIntegrityCategory.surface(NACp, NICsupp); if ((data[10] & 0b00001000) != 0) { if ((data[10] & 0b00000100) != 0) { horizontalSource = Angle.TRUE_TRACK; } else { horizontalSource = Angle.MAGNETIC_TRACK; } } else { if ((data[10] & 0b00000100) != 0) { horizontalSource = Angle.TRUE_HEADING; } else { horizontalSource = Angle.MAGNETIC_HEADING; } } return this; } @Override public void apply(Track track) { track.setVersion(Version.VERSION1); } public int getSubType() { return subType; } public Version getVersion() { return version; } public Angle getHorizontalSource() { return horizontalSource; } public SurfaceCapability getSurfaceCapability() { return surfaceCapability; } public LengthWidthCode getLengthWidthCode() { return lengthWidthCode; } public SurfaceOperationalMode getOperationalMode() { return operationalMode; } public SourceIntegrityLevel getSIL() { return SIL; } public SourceIntegrityLevelSupplement getSILsupp() { return SILsupp; } public NavigationIntegrityCategory getNICp() { return NICp; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion2.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class AircraftOperationalStatusVersion2 extends AircraftOperationalStatusMessage { public AircraftOperationalStatusVersion2(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion2 decode() { int subType = data[4] & 0x7; switch (subType) { case 0: return new AircraftOperationalStatusVersion2Airborne(data).decode(); case 1: return new AircraftOperationalStatusVersion2Surface(data).decode(); default: throw new NotImplementedException("Aircraft operation status version 2 sub type " + subType + " is not known"); } } @Override public void apply(Track track) { // Nothing } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion2Airborne.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; import aero.t2s.modes.decoder.df.df17.data.AirborneCapability; import aero.t2s.modes.decoder.df.df17.data.AirborneOperationalMode; public class AircraftOperationalStatusVersion2Airborne extends AircraftOperationalStatusVersion2 { private AirborneCapability capability; private AirborneOperationalMode operationalMode; private SourceIntegrityLevelSupplement SILsupp; private BarometricAltitudeIntegrityCode NICbaro; private NavigationIntegrityCategory NICp; private SourceIntegrityLevel SIL; private Angle horizontalSource; private GeometricVerticalAccuracy gva; private Version version; public AircraftOperationalStatusVersion2Airborne(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion2Airborne decode() { version = Version.VERSION2; capability = new AirborneCapability((data[5] << 8) | data[6], version); operationalMode = new AirborneOperationalMode((data[7] << 8) | data[8]); int NICsuppA = (data[9] & 0b00010000) >>> 4; int NACp = (data[9] & 0b00001111); NICp = NavigationIntegrityCategory.airborne(NACp, NICsuppA, 0); gva = GeometricVerticalAccuracy.from((data[10] & 0b11000000) >>> 6); SIL = SourceIntegrityLevel.from((data[10] & 0b000110000) >>> 4); NICbaro = BarometricAltitudeIntegrityCode.from((data[10] & 0b00001000) >>> 3); horizontalSource = (data[10] & 0b00000100) != 0 ? Angle.TRUE_HEADING : Angle.MAGNETIC_HEADING; SILsupp = SourceIntegrityLevelSupplement.from((data[10] & 0b00000010) >>> 1); return this; } @Override public void apply(Track track) { track.setVersion(version); } public AirborneCapability getCapability() { return capability; } public AirborneOperationalMode getOperationalMode() { return operationalMode; } public SourceIntegrityLevelSupplement getSILsupp() { return SILsupp; } public BarometricAltitudeIntegrityCode getNICbaro() { return NICbaro; } public NavigationIntegrityCategory getNICp() { return NICp; } public SourceIntegrityLevel getSIL() { return SIL; } public Angle getHorizontalSource() { return horizontalSource; } public GeometricVerticalAccuracy getGva() { return gva; } public Version getVersion() { return version; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftOperationalStatusVersion2Surface.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; import aero.t2s.modes.decoder.df.df17.data.SurfaceCapability; import aero.t2s.modes.decoder.df.df17.data.SurfaceOperationalMode; public class AircraftOperationalStatusVersion2Surface extends AircraftOperationalStatusVersion2 { private SurfaceCapability surfaceCapability; private SurfaceOperationalMode operationalMode; private LengthWidthCode lengthWidthCode; private NavigationIntegrityCategory NICp; private Angle horizontalSource; private SourceIntegrityLevelSupplement SILsupp; private SourceIntegrityLevel SIL; private Version verison; public AircraftOperationalStatusVersion2Surface(short[] data) { super(data); } @Override public AircraftOperationalStatusVersion2Surface decode() { verison = Version.VERSION2; surfaceCapability = new SurfaceCapability((data[5] << 4) | (data[6] & 0b11110000) >>> 4, verison); lengthWidthCode = LengthWidthCode.from(data[6] & 0b00001111); operationalMode = new SurfaceOperationalMode((data[7] << 8) | data[8]); SIL = SourceIntegrityLevel.from((data[10] & 0b000110000) >>> 4); SILsupp = SourceIntegrityLevelSupplement.from((data[10] & 0b00000010) >>> 1); int NICsuppA = (data[9] & 0b00010000) >>> 4; int NACp = (data[9] & 0b00001111); NICp = NavigationIntegrityCategory.surface(NACp, NICsuppA); if ((data[10] & 0b00001000) != 0) { if ((data[10] & 0b00000100) != 0) { horizontalSource = Angle.TRUE_TRACK; } else { horizontalSource = Angle.MAGNETIC_TRACK; } } else { if ((data[10] & 0b00000100) != 0) { horizontalSource = Angle.TRUE_HEADING; } else { horizontalSource = Angle.MAGNETIC_HEADING; } } return this; } @Override public void apply(Track track) { track.setVersion(Version.VERSION2); } public SurfaceCapability getSurfaceCapability() { return surfaceCapability; } public SurfaceOperationalMode getOperationalMode() { return operationalMode; } public LengthWidthCode getLengthWidthCode() { return lengthWidthCode; } public NavigationIntegrityCategory getNICp() { return NICp; } public Angle getHorizontalSource() { return horizontalSource; } public SourceIntegrityLevelSupplement getSILsupp() { return SILsupp; } public SourceIntegrityLevel getSIL() { return SIL; } public Version getVerison() { return verison; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftStatusMessage.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class AircraftStatusMessage extends ExtendedSquitter { public AircraftStatusMessage(short[] data) { super(data); } @Override public AircraftStatusMessage decode() { int subType = data[4] & 0x7; // No Information if (subType == 0) { return this; } if (subType == 1) { return new AircraftStatusMessageEmergency(data).decode(); } if (subType == 2) { return new AircraftStatusMessageAcasRA(data).decode(); } throw new NotImplementedException("BDS6,1 Sub Type " + subType + " not implemented"); } @Override public void apply(Track track) { // Nothing to do in the base type } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftStatusMessageAcasRA.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Acas; import aero.t2s.modes.Track; import aero.t2s.modes.constants.ResolutionAdvisory; import aero.t2s.modes.constants.ThreatTypeIndicator; import aero.t2s.modes.decoder.AltitudeEncoding; import aero.t2s.modes.decoder.Common; public class AircraftStatusMessageAcasRA extends AircraftStatusMessage { private int subType = 2; private ResolutionAdvisory resolutionAdvisory; private boolean multipleThreats; private boolean RANotPassBelow; private boolean RANotPassAbove; private boolean RANotTurnLeft; private boolean RANotTurnRight; private ThreatTypeIndicator threatTypeIndicator; private String threatModeS; private double threatAltitude; private double threatRange; private int threatBearing; public AircraftStatusMessageAcasRA(short[] data) { super(data); } @Override public AircraftStatusMessage decode() { int ara = (data[5] << 6) | (data[6] >>> 3); int rac = ((data[6] & 0x3) << 2) | data[7] >>> 6; int rat = (data[7] >>> 5) & 0x1; multipleThreats = ((data[7] >>> 4) & 0x1) == 1; int tti = (data[7] >>> 2) & 0x3; int tid = ((data[7] & 0x3) << 24) | (data[8] << 16) | (data[9] << 8) | data[10]; resolutionAdvisory = new ResolutionAdvisory(ara); RANotPassBelow = rac >>> 3 == 1; RANotPassAbove = ((rac >>> 2) & 0x1) == 1; RANotTurnLeft = ((rac >>> 1) & 0x1) == 1; RANotTurnLeft = (rac & 0x1) == 1; threatTypeIndicator = ThreatTypeIndicator.from(tti); if (rat == 1) { resolutionAdvisory = new ResolutionAdvisory(); RANotPassBelow = false; RANotPassAbove = false; RANotTurnLeft = false; RANotTurnRight = false; multipleThreats = false; } switch (threatTypeIndicator) { case MODES: threatModeS = Common.icao(Common.toHexString(new short[]{ (short) (data[7] & 0x3), (data[8]), (data[9]), (data[10]), })); break; case ALT_BRG_DIST: threatAltitude = AltitudeEncoding.decodeModeC(tid >>> 13).getAltitude(); threatRange = Common.tidr((tid >>> 6) & 0x7F); threatBearing = Common.tidb(tid & 0x3F); break; } return this; } @Override public void apply(Track track) { Acas acas = track.getAcas(); acas.getResolutionAdvisory().update(resolutionAdvisory); acas.setRANotPassBelow(RANotPassBelow); acas.setRANotPassAbove(RANotPassAbove); acas.setRANotTurnLeft(RANotTurnLeft); acas.setRANotTurnRight(RANotTurnRight); acas.setMultipleThreats(multipleThreats); acas.setThreatType(threatTypeIndicator); switch (threatTypeIndicator) { case MODES: acas.setTargetModeS(threatModeS); break; case ALT_BRG_DIST: acas.setTargetAltitude(threatAltitude); acas.setTargetRange(threatRange); acas.setTargetBearing(threatBearing); break; } } public int getSubType() { return subType; } public ResolutionAdvisory getResolutionAdvisory() { return resolutionAdvisory; } public boolean isMultipleThreats() { return multipleThreats; } public boolean isRANotPassBelow() { return RANotPassBelow; } public boolean isRANotPassAbove() { return RANotPassAbove; } public boolean isRANotTurnLeft() { return RANotTurnLeft; } public boolean isRANotTurnRight() { return RANotTurnRight; } public ThreatTypeIndicator getThreatTypeIndicator() { return threatTypeIndicator; } public String getThreatModeS() { return threatModeS; } public double getThreatAltitude() { return threatAltitude; } public double getThreatRange() { return threatRange; } public int getThreatBearing() { return threatBearing; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/AircraftStatusMessageEmergency.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.EmergencyState; import aero.t2s.modes.decoder.Common; public class AircraftStatusMessageEmergency extends AircraftStatusMessage { private int subType = 1; private EmergencyState emergencyState; private int modeA; public AircraftStatusMessageEmergency(short[] data) { super(data); } @Override public AircraftStatusMessage decode() { emergencyState = EmergencyState.from(data[5] >>> 5); modeA = Common.modeA((data[5] & 0x1F) << 8 | data[6]); return this; } @Override public void apply(Track track) { track.setEmergencyState(emergencyState); if (modeA != 0) { track.setModeA(modeA); } } public int getSubType() { return subType; } public EmergencyState getEmergencyState() { return emergencyState; } public int getModeA() { return modeA; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/ExtendedSquitter.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; public abstract class ExtendedSquitter { protected short[] data; protected int typeCode; public ExtendedSquitter(short[] data) { this.data = data; this.typeCode = data[4] >>> 3; } public abstract ExtendedSquitter decode(); public abstract void apply(Track track); public int getTypeCode() { return typeCode; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/InvalidExtendedSquitterTypeCodeException.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.DownlinkException; public class InvalidExtendedSquitterTypeCodeException extends RuntimeException implements DownlinkException { public InvalidExtendedSquitterTypeCodeException(int typeCode) { super("Mode-S: Type " + typeCode + " is unknown"); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/ReservedMessage.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; public class ReservedMessage extends ExtendedSquitter { public ReservedMessage(short[] data) { super(data); } @Override public ReservedMessage decode() { return this; } @Override public void apply(Track track) { // Nothing to do } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/SurfacePosition.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class SurfacePosition extends ExtendedSquitter { public SurfacePosition(short[] data) { super(data); } @Override public SurfacePosition decode() { throw new NotImplementedException(getClass().getSimpleName() + " Not implemented"); } @Override public void apply(Track track) { throw new NotImplementedException(getClass().getSimpleName() + " Not implemented"); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/SurfaceSystemStatus.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class SurfaceSystemStatus extends ExtendedSquitter { public SurfaceSystemStatus(short[] data) { super(data); } @Override public SurfaceSystemStatus decode() { throw new NotImplementedException(getClass().getSimpleName() + " Not implemented"); } @Override public void apply(Track track) { throw new NotImplementedException(getClass().getSimpleName() + " Not implemented"); } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/TargetStatusMessage.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; public class TargetStatusMessage extends ExtendedSquitter { public TargetStatusMessage(short[] data) { super(data); } @Override public TargetStatusMessage decode() { int subtype = (data[4] >>> 1) & 0x3; if (subtype == 0) return new TargetStatusMessageType0(data).decode(); else if (subtype == 1) return new TargetStatusMessageType1(data).decode(); else throw new NotImplementedException("BDS6,2 Subtype " + subtype + " is not implemented"); } @Override public void apply(Track track) { // Can't apply base message } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/TargetStatusMessageType0.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.NotImplementedException; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; public class TargetStatusMessageType0 extends TargetStatusMessage { private int subType = 0; private VerticalDataAvailable verticalDataAvailable; private TargetAltitudeType targetAltitudeType; private TargetAltitudeCapability targetAltitudeCapability; private VerticalModeIndicator verticalModeIndicator; private int targetAltitude; private HorizontalDataAvailable horizontalDataAvailable; private int targetHeadingTrack; private Angle targetAngle; private HorizontalModeIndicator horizontalModeIndicator; private NavigationAccuracyCategoryPosition NACp; private BarometricAltitudeIntegrityCode NICbaro; private SourceIntegrityLevel sil; private AcasCapability acasCapability; private EmergencyState emergency; public TargetStatusMessageType0(short[] data) { super(data); } @Override public TargetStatusMessageType0 decode() { verticalDataAvailable = VerticalDataAvailable.from(((data[4] & 0b00000001) << 1) | (data[5] >>> 7)); targetAltitudeType = TargetAltitudeType.from((data[5] & 0b01000000) >>> 6); targetAltitudeCapability = TargetAltitudeCapability.from((data[5] & 0b00011000) >>> 3); verticalModeIndicator = VerticalModeIndicator.from((data[5] & 0b00000110) >>> 1); int targetAltitudeValue = ((data[5] & 0b00000001) << 9) | (data[6] << 1) | ((data[7] & 0b10000000) >>> 7); if (targetAltitudeValue < 1011) { if (targetAltitudeValue >= 11) { targetAltitudeValue -= 1; // 11 = 0ft } targetAltitude = (-10 + targetAltitudeValue) * 1000; } horizontalDataAvailable = HorizontalDataAvailable.from((data[7] & 0b01100000) >>> 5); targetHeadingTrack = ((data[7] & 0b00011111) << 4) | data[8] & 0b11110000; targetAngle = (data[8] & 0b00001000) != 0 ? Angle.TRACK : Angle.HEADING; horizontalModeIndicator = HorizontalModeIndicator.from((data[8] & 0b00000110) >>> 1); NACp = NavigationAccuracyCategoryPosition.find(((data[8] & 0b00000001) << 3) | (data[9] & 0b11100000) >>> 5); NICbaro = BarometricAltitudeIntegrityCode.from((data[9] & 0b00010000) >>> 4); sil = SourceIntegrityLevel.from((data[9] & 0b000001100) >>> 2); acasCapability = AcasCapability.from((data[10] & 0b00011000) >>> 3); emergency = EmergencyState.from((data[10] & 0b00000111)); return this; } @Override public void apply(Track track) { track.setNACp(NACp); if (horizontalDataAvailable != HorizontalDataAvailable.NOT_VALID) track.setSelectedHeading(targetHeadingTrack); if (verticalDataAvailable != VerticalDataAvailable.NOT_VALID) track.setSelectedAltitude(targetAltitude); track.setEmergencyState(emergency); track.setSil(sil.ordinal()); } public int getSubType() { return subType; } public boolean isTargetHeadingTrackValid() { return targetHeadingTrack >= 360; } public VerticalDataAvailable getVerticalDataAvailable() { return verticalDataAvailable; } public TargetAltitudeType getTargetAltitudeType() { return targetAltitudeType; } public TargetAltitudeCapability getTargetAltitudeCapability() { return targetAltitudeCapability; } public VerticalModeIndicator getVerticalModeIndicator() { return verticalModeIndicator; } public int getTargetAltitude() { return targetAltitude; } public HorizontalDataAvailable getHorizontalDataAvailable() { return horizontalDataAvailable; } public int getTargetHeadingTrack() { return targetHeadingTrack; } public Angle getTargetAngle() { return targetAngle; } public HorizontalModeIndicator getHorizontalModeIndicator() { return horizontalModeIndicator; } public NavigationAccuracyCategoryPosition getNACp() { return NACp; } public BarometricAltitudeIntegrityCode getNICbaro() { return NICbaro; } public SourceIntegrityLevel getSil() { return sil; } public AcasCapability getAcasCapability() { return acasCapability; } public EmergencyState getEmergency() { return emergency; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/TargetStatusMessageType1.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; import aero.t2s.modes.constants.*; public class TargetStatusMessageType1 extends TargetStatusMessage { private static final double HEADING_RESOLUTION = 180.0 / 256.0; private int subType = 1; private SelectedAltitudeSource selectedAltitudeType; private int selectedAltitude; private double baroSetting; private boolean selectedHeadingAvailable; private double selectedHeading; private SourceIntegrityLevelSupplement SILsupp; private SourceIntegrityLevel SIL; private NavigationAccuracyCategoryPosition NACp; private BarometricAltitudeIntegrityCode NICbaro; private boolean autopilot; private boolean autopilotLnav; private boolean autopilotVnav; private boolean autopilotAltitudeHold; private boolean autopilotApproach; private boolean acasOperation; public TargetStatusMessageType1(short[] data) { super(data); } @Override public TargetStatusMessageType1 decode() { SILsupp = SourceIntegrityLevelSupplement.from(data[4] & 0x1); if ((data[9] & 0b00000010) == 0) { selectedAltitudeType = SelectedAltitudeSource.UNKNOWN; } else if (data[5] >>> 7 == 1) { selectedAltitudeType = SelectedAltitudeSource.FMS; } else { selectedAltitudeType = SelectedAltitudeSource.MCP; } if (selectedAltitudeType != SelectedAltitudeSource.UNKNOWN) { selectedAltitude = (((data[5] & 0x7F) << 4) | (data[6] >>> 4) - 2) * 32; } baroSetting = ((((data[6] & 0b00001111) << 5) | (data[7] >>> 3))); if (baroSetting != 0) { baroSetting = (baroSetting - 1) * 0.8 + 800; } selectedHeadingAvailable = ((data[7] >>> 2) & 0x1) == 1; if (selectedHeadingAvailable) { boolean isNegativeHeading = ((data[7] >>> 1) & 0x1) == 1; selectedHeading = (((data[7] & 0x1) << 7) | (data[8] >>> 1)) * HEADING_RESOLUTION; if (isNegativeHeading) selectedHeading += 180; } NACp = NavigationAccuracyCategoryPosition.find(((data[8] & 0b00000001) << 3) | data[9] >>> 5); NICbaro = BarometricAltitudeIntegrityCode.from((data[9] >>> 4) & 0x1); SIL = SourceIntegrityLevel.from((data[9] >>> 2) & 0x3); autopilot = (data[9] & 0x1) == 1; autopilotVnav = (data[10] >>> 7) == 1; autopilotAltitudeHold = ((data[10] >>> 6) & 0x1) == 1; autopilotApproach = ((data[10] >>> 4) & 0x1) == 1; acasOperation = ((data[10] >>> 3) & 0x1) == 1; autopilotLnav = ((data[10] >>> 2) & 0x1) == 1; return this; } @Override public void apply(Track track) { track.setSelectedAltitudeManagedFms(selectedAltitudeType == SelectedAltitudeSource.FMS); track.setSelectedAltitudeManagedMcp(selectedAltitudeType == SelectedAltitudeSource.MCP); track.setSelectedAltitude(selectedAltitudeType != SelectedAltitudeSource.UNKNOWN ? selectedAltitude : 0); if (isBaroAvailable()) { track.setBaroAltitude((int) Math.round(baroSetting)); } if (selectedHeadingAvailable) { track.setSelectedHeading(selectedHeading); } track.setNACp(NACp); track.setNICb(NICbaro.ordinal()); track.setSil(SIL.ordinal()); track.setAutopilot(autopilot); track.setVnav(autopilotVnav); track.setAltitudeHold(autopilotAltitudeHold); track.setApproachMode(autopilotApproach); track.getAcas().setActive(acasOperation); track.setLnav(autopilotLnav); } public int getSubType() { return subType; } public SourceIntegrityLevelSupplement getSILsupp() { return SILsupp; } public SelectedAltitudeSource getSelectedAltitudeType() { return selectedAltitudeType; } public int getSelectedAltitude() { return selectedAltitude; } public double getBaroSetting() { return baroSetting; } public boolean isBaroAvailable() { return baroSetting != 0; } public boolean isSelectedHeadingAvailable() { return selectedHeadingAvailable; } public double getSelectedHeading() { return selectedHeading; } public SourceIntegrityLevel getSIL() { return SIL; } public NavigationAccuracyCategoryPosition getNACp() { return NACp; } public BarometricAltitudeIntegrityCode getNICbaro() { return NICbaro; } public boolean isAutopilot() { return autopilot; } public boolean isAutopilotLnav() { return autopilotLnav; } public boolean isAutopilotVnav() { return autopilotVnav; } public boolean isAutopilotAltitudeHold() { return autopilotAltitudeHold; } public boolean isAutopilotApproach() { return autopilotApproach; } public boolean isAcasOperation() { return acasOperation; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/TestMessage.java
package aero.t2s.modes.decoder.df.df17; import aero.t2s.modes.Track; public class TestMessage extends ExtendedSquitter { public TestMessage(short[] data) { super(data); } @Override public ExtendedSquitter decode() { return this; } @Override public void apply(Track track) { // Nothing to do } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/data/AirborneCapability.java
package aero.t2s.modes.decoder.df.df17.data; import aero.t2s.modes.constants.TargetChangeReportCapability; import aero.t2s.modes.constants.Version; public class AirborneCapability { private boolean acasOperational; private boolean receive1090ES; private boolean cockpitDisplayOfTraffic; private boolean sendAirReferencedVelocityReport; private boolean sendTargetSateReport; private TargetChangeReportCapability targetChangeReportCapability; private boolean uatReceive; private Version version; public AirborneCapability(int data, Version version) { this.version = version; acasOperational = (data & 0b0010000000000000) != 0; receive1090ES = (data & 0b0001000000000000) != 0; cockpitDisplayOfTraffic = (data & 0b0001000000000000) != 0; sendAirReferencedVelocityReport = (data & 0b0000001000000000) != 0; sendTargetSateReport = (data & 0b0000000100000000) != 0; targetChangeReportCapability = TargetChangeReportCapability.from((data & 0b0000000011000000) >>> 6); uatReceive = (data & 0b0000000000100000) != 0; } public boolean isAcasOperational() { return acasOperational; } public boolean isReceive1090ES() { return receive1090ES; } public boolean isSendAirReferencedVelocityReport() { return sendAirReferencedVelocityReport; } public boolean isSendTargetSateReport() { return sendTargetSateReport; } public TargetChangeReportCapability getTargetChangeReportCapability() { return targetChangeReportCapability; } public boolean isUatReceive() { return uatReceive; } public boolean isCockpitDisplayOfTraffic() { return cockpitDisplayOfTraffic; } public Version getVersion() { return version; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/data/AirborneOperationalMode.java
package aero.t2s.modes.decoder.df.df17.data; import aero.t2s.modes.constants.AcasState; import aero.t2s.modes.constants.SourceIntegrityLevel; public class AirborneOperationalMode { private AcasState acasRA; private boolean acasIdent; private boolean singleAntennaFlag; private SourceIntegrityLevel systemDesignAssurance; public AirborneOperationalMode(int data) { acasRA = (data & 0b0010000000000000) != 0 ? AcasState.RA_ACTIVE : AcasState.RA_NOT_ACTIVE; acasIdent = (data & 0b0001000000000000) != 0; singleAntennaFlag = (data & 0b0000010000000000) != 0; systemDesignAssurance = SourceIntegrityLevel.from((data & 0b0000001100000000) >>> 8); } public AcasState getAcasRA() { return acasRA; } public boolean isAcasIdent() { return acasIdent; } public boolean isSingleAntennaFlag() { return singleAntennaFlag; } public SourceIntegrityLevel getSystemDesignAssurance() { return systemDesignAssurance; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/data/SurfaceCapability.java
package aero.t2s.modes.decoder.df.df17.data; import aero.t2s.modes.constants.NavigationUncertaintyCategory; import aero.t2s.modes.constants.Version; public class SurfaceCapability { private boolean receive1090ES; private boolean lowB2Power; private boolean uatReceive; private boolean cockpitDisplayOfTraffic; private boolean positionOffsetApplied; private NavigationUncertaintyCategory NACv; private short NICsuppC; private Version version; public SurfaceCapability(int data, Version version) { this.version = version; lowB2Power = (data & 0b000000100000) != 0; if (version == Version.VERSION1) { positionOffsetApplied = (data & 0b001000000000) != 0; cockpitDisplayOfTraffic = (data & 0b000100000000) != 0; } else { receive1090ES = (data & 0b000100000000) != 0; uatReceive = (data & 0b000000010000) != 0; NACv = NavigationUncertaintyCategory.from((data & 0b000000001110) >>> 1); NICsuppC = (short) (data & 0b000000000001); } } public boolean isReceive1090ES() { return receive1090ES; } public boolean isLowB2Power() { return lowB2Power; } public boolean isUatReceive() { return uatReceive; } public NavigationUncertaintyCategory getNACv() { return NACv; } public short getNICsuppC() { return NICsuppC; } public Version getVersion() { return version; } public boolean isCockpitDisplayOfTraffic() { return cockpitDisplayOfTraffic; } public boolean isPositionOffsetApplied() { return positionOffsetApplied; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/decoder/df/df17/data/SurfaceOperationalMode.java
package aero.t2s.modes.decoder.df.df17.data; import aero.t2s.modes.constants.AcasState; import aero.t2s.modes.constants.SourceIntegrityLevel; public class SurfaceOperationalMode { private AcasState acasRA; private boolean acasIdent; private boolean singleAntennaFlag; private SourceIntegrityLevel systemDesignAssurance; private boolean gpsLateralOffsetAvailable; /** * Negative is left of center in metres * Positive is right of center in metres */ private int gpsLateralOffset; private boolean gpsLongitudinalOffsetAvailable; private boolean gpsLongitudinalOffsetAppliedBySensor; /** * Aft of aircraft nose in metres */ private int gpsLongitudinalOffset; public SurfaceOperationalMode(int data) { acasRA = (data & 0b0010000000000000) != 0 ? AcasState.RA_ACTIVE : AcasState.RA_NOT_ACTIVE; acasIdent = (data & 0b0001000000000000) != 0; singleAntennaFlag = (data & 0b0000010000000000) != 0; systemDesignAssurance = SourceIntegrityLevel.from((data & 0b0000001100000000) >>> 7); int gpsAntennaOffset = (data & 0b0000000011111111); gpsLateralOffset = (gpsAntennaOffset & 0b11100000) >>> 5; if ((gpsLateralOffset & 0b100) == 0) { gpsLateralOffset = (gpsLateralOffset & 0b011) * 2; gpsLateralOffsetAvailable = gpsLateralOffset != 0; } else { gpsLateralOffset = (gpsLateralOffset & 0b011) * -2; gpsLateralOffsetAvailable = true; } gpsLongitudinalOffset = gpsAntennaOffset & 0b00011111; gpsLongitudinalOffsetAvailable = gpsLongitudinalOffset != 0; gpsLongitudinalOffsetAppliedBySensor = gpsLongitudinalOffset == 1; gpsLongitudinalOffset = (gpsLongitudinalOffset - 1) * 2; } public AcasState getAcasRA() { return acasRA; } public boolean isAcasIdent() { return acasIdent; } public boolean isSingleAntennaFlag() { return singleAntennaFlag; } public SourceIntegrityLevel getSystemDesignAssurance() { return systemDesignAssurance; } public boolean isGpsLateralOffsetAvailable() { return gpsLateralOffsetAvailable; } public int getGpsLateralOffset() { return gpsLateralOffset; } public boolean isGpsLongitudinalOffsetAvailable() { return gpsLongitudinalOffsetAvailable; } public boolean isGpsLongitudinalOffsetAppliedBySensor() { return gpsLongitudinalOffsetAppliedBySensor; } public int getGpsLongitudinalOffset() { return gpsLongitudinalOffset; } }
0
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes
java-sources/aero/t2s/mode-s/0.2.5/aero/t2s/modes/examples/StdOutExample.java
package aero.t2s.modes.examples; import aero.t2s.modes.ModeS; public class StdOutExample { public static void main(String[] args) { ModeS modes = new ModeS( "127.0.0.1", // Host IP where the Dump1090 server is running 30002, // The port with raw output (default 30002) 51, // Decimal latitude 0 // Decimal longitude ); modes.onTrackCreated(track -> System.out.println("CREATED " + track.toString())); modes.onTrackUpdated(track -> System.out.println("UPDATED " + track.toString())); modes.onTrackDeleted(track -> System.out.println("DELETED " + track.toString())); modes.start(); } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ApiMethodSecurityConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; /** * The <b>ApiMethodSecurityConfiguration</b> class applies the API-specific method security * configuration to the global method security configuration. * * @author Marcus Portmann */ @EnableGlobalMethodSecurity(prePostEnabled = true) public class ApiMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>ApiMethodSecurityConfiguration</b>. * * @param applicationContext the Spring application context */ public ApiMethodSecurityConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the method security expression handler. * * @return the method security expression handler */ @Bean public MethodSecurityExpressionHandler expressionHandler() { return new ApiMethodSecurityExpressionHandler(applicationContext); } @Override protected MethodSecurityExpressionHandler createExpressionHandler() { return new ApiMethodSecurityExpressionHandler(applicationContext); } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ApiMethodSecurityExpressionHandler.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import org.aopalliance.intercept.MethodInvocation; import org.springframework.context.ApplicationContext; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; /** * The <b>ApiMethodSecurityExpressionHandler</b> class. * * @author Marcus Portmann */ public class ApiMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>ApiMethodSecurityExpressionHandler</b>. * * @param applicationContext the Spring application context */ public ApiMethodSecurityExpressionHandler(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Creates the root object for expression evaluation. * * @param authentication the authentication * @param invocation the invocation * @return the root object for expression evaluation */ @Override protected MethodSecurityExpressionOperations createSecurityExpressionRoot( Authentication authentication, MethodInvocation invocation) { ApiSecurityExpressionRoot apiSecurityExpressionRoot = new ApiSecurityExpressionRoot(authentication, applicationContext); apiSecurityExpressionRoot.setPermissionEvaluator(getPermissionEvaluator()); apiSecurityExpressionRoot.setTrustResolver(this.getTrustResolver()); apiSecurityExpressionRoot.setRoleHierarchy(getRoleHierarchy()); return apiSecurityExpressionRoot; } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ApiSecurityExpressionRoot.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import org.springframework.context.ApplicationContext; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; import org.springframework.util.StringUtils; /** * The <b>ApiSecurityExpressionRoot</b> class implements the custom methods, which can be used in * conjunction with the <b>@PreAuthorize</b> annotation. * * @author Marcus Portmann */ public class ApiSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations { /** The filter object. */ private Object filterObject; /** Is debugging enabled for the Inception Framework? */ private boolean inDebugMode; /** Is API security enabled for the Inception Framework? */ private boolean isSecurityEnabled; /** The return object. */ private Object returnObject; /** * Constructs a new <b>ApiSecurityExpressionRoot</b>. * * @param authentication the authentication * @param applicationContext the Spring application context */ public ApiSecurityExpressionRoot( Authentication authentication, ApplicationContext applicationContext) { super(authentication); // Check if debugging is enabled for the Inception Framework try { if (StringUtils.hasText( applicationContext.getEnvironment().getProperty("inception.debug.enabled"))) { this.inDebugMode = Boolean.parseBoolean( applicationContext.getEnvironment().getProperty("inception.debug.enabled")); } } catch (Throwable e) { this.inDebugMode = false; } // Check if security is enabled for the Inception Framework try { if (StringUtils.hasText( applicationContext.getEnvironment().getProperty("inception.api.security.enabled"))) { this.isSecurityEnabled = Boolean.parseBoolean( applicationContext.getEnvironment().getProperty("inception.api.security.enabled")); } else { this.isSecurityEnabled = (!this.inDebugMode); } } catch (Throwable e) { this.isSecurityEnabled = (!this.inDebugMode); } } @Override public Object getFilterObject() { return filterObject; } @Override public Object getReturnObject() { return returnObject; } @Override public Object getThis() { return this; } /** * Returns whether security is disabled. * * @return <b>true</b> if security is disabled or <b>false</b> otherwise */ public boolean isSecurityDisabled() { return (!isSecurityEnabled); } /** * Returns whether security is enabled. * * @return <b>true</b> if security is enabled or <b>false</b> otherwise */ public boolean isSecurityEnabled() { return isSecurityEnabled; } @Override public void setFilterObject(Object filterObject) { this.filterObject = filterObject; } @Override public void setReturnObject(Object returnObject) { this.returnObject = returnObject; } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ApiUtil.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import java.io.StringWriter; import org.springframework.util.StringUtils; /** * The <b>RestUtil</b> class provides utility methods that are useful when working with APIs * implemented as RESTful web services. * * @author Marcus Portmann */ public class ApiUtil { /** * Produce a string in double quotes with backslash sequences in all the right places. A backslash * will be inserted within &lt;/, producing &lt;\/, allowing JSON text to be delivered in HTML. In * JSON text, a string cannot contain a control character or an unescaped quote or backslash. * * @param string a String * @return a String correctly formatted for insertion in a JSON text */ public static String quote(String string) { if (!StringUtils.hasText(string)) { return "\"\""; } StringWriter sw = new StringWriter(); char b; char c = 0; String hhhh; int i; int len = string.length(); sw.write('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sw.write('\\'); sw.write(c); break; case '/': if (b == '<') { sw.write('\\'); } sw.write(c); break; case '\b': sw.write("\\b"); break; case '\t': sw.write("\\t"); break; case '\n': sw.write("\\n"); break; case '\f': sw.write("\\f"); break; case '\r': sw.write("\\r"); break; default: if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) { sw.write("\\u"); hhhh = Integer.toHexString(c); sw.write("0000", 0, 4 - hhhh.length()); sw.write(hhhh); } else { sw.write(c); } } } sw.write('"'); return sw.getBuffer().toString(); } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ProblemDetails.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import africa.absa.inception.core.service.ValidationError; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; import java.util.List; /** * The <b>ProblemDetails</b> class holds the information for a Problem Details Object as defined in * RFC 7807. * * <p>It contains a number of additional members, beyond those defined by the specification, which * hold information related to validation errors and support debugging. * * @author Marcus Portmann */ @Schema( description = "A problem details object, as defined by RFC 7807, which holds the information for an error returned by an API") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "timestamp", "type", "title", "status", "detail", "parameter", "validationErrors", "stackTrace" }) public class ProblemDetails { /** The human-readable explanation specific to this occurrence of the problem. */ @Schema( description = "The human-readable explanation specific to this occurrence of the problem", required = true) @JsonProperty(required = true) private String detail; /** The optional name of the parameter associated with the problem. */ @Schema(description = "The optional name of the parameter associated with the problem") @JsonProperty private String parameter; /** The optional stack trace generated by the origin server for the problem. */ @Schema(description = "The optional stack trace generated by the origin server for the problem") @JsonProperty private String stackTrace; /** The HTTP status code generated by the origin server for this occurrence of the problem. */ @Schema( description = "The HTTP status code generated by the origin server for this occurrence of the problem", required = true) @JsonProperty(required = true) private int status; /** The date and time the problem occurred. */ @Schema(description = "The date and time the problem occurred", required = true) @JsonProperty(required = true) private LocalDateTime timestamp; /** * The short, human-readable summary of the problem type; it should not change from occurrence to * occurrence of the problem, except for purposes of localization. */ @Schema( description = "The short, human-readable summary of the problem type; it should not change from occurrence to occurrence of the problem, except for purposes of localization", required = true) @JsonProperty(required = true) private String title; /** The URI reference that identifies the problem type. */ @Schema(description = "The URI reference that identifies the problem type", required = true) @JsonProperty(required = true) private String type; /** The optional validation errors associated with the problem. */ @Schema(description = "The optional validation errors associated with the problem") @JsonProperty private List<ValidationError> validationErrors; /** Constructs a new <b>ProblemDetails</b>. */ public ProblemDetails() {} /** * Returns the human-readable explanation specific to this occurrence of the problem. * * @return the human-readable explanation specific to this occurrence of the problem */ public String getDetail() { return detail; } /** * Returns the optional name of the parameter associated with the problem. * * @return the optional name of the parameter associated with the problem */ public String getParameter() { return parameter; } /** * Returns the optional stack trace generated by the origin server for the problem. * * @return the optional stack trace generated by the origin server for the problem */ public String getStackTrace() { return stackTrace; } /** * Returns the HTTP status code generated by the origin server for this occurrence of the problem. * * @return the HTTP status code generated by the origin server for this occurrence of the problem */ public int getStatus() { return status; } /** * Returns the date and time the problem occurred. * * @return the date and time the problem occurred */ public LocalDateTime getTimestamp() { return timestamp; } /** * Returns the short, human-readable summary of the problem type. * * @return the short, human-readable summary of the problem type */ public String getTitle() { return title; } /** * Returns the URI reference that identifies the problem type. * * @return the URI reference that identifies the problem type */ public String getType() { return type; } /** * Returns the optional validation errors associated with the problem. * * @return the optional validation errors associated with the problem */ public List<ValidationError> getValidationErrors() { return validationErrors; } /** * Set the human-readable explanation specific to this occurrence of the problem. * * @param detail the human-readable explanation specific to this occurrence of the problem */ public void setDetail(String detail) { this.detail = detail; } /** * Set the name of the parameter associated with the problem. * * @param parameter the name of the parameter associated with the problem */ public void setParameter(String parameter) { this.parameter = parameter; } /** * Set the stack trace generated by the origin server for the problem. * * @param stackTrace the stack trace generated by the origin server for the problem */ public void setStackTrace(String stackTrace) { this.stackTrace = stackTrace; } /** * Set the HTTP status code generated by the origin server for this occurrence of the problem. * * @param status the HTTP status code generated by the origin server for this occurrence of the * problem */ public void setStatus(int status) { this.status = status; } /** * Set the date and time the problem occurred. * * @param timestamp the date and time the problem occurred */ public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } /** * Set the short, human-readable summary of the problem type. * * @param title the short, human-readable summary of the problem type */ public void setTitle(String title) { this.title = title; } /** * Set the URI reference that identifies the problem type. * * @param type the URI reference that identifies the problem type */ public void setType(String type) { this.type = type; } /** * Set the validation errors associated with the problem. * * @param validationErrors the validation errors associated with the problem */ public void setValidationErrors(List<ValidationError> validationErrors) { this.validationErrors = validationErrors; } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/ProblemHandler.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; import africa.absa.inception.core.service.ServiceUnavailableException; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.time.LocalDateTime; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * The <b>ProblemHandler</b> class implements the error handler that returns errors raised by * RESTful controllers as RFC 7807 JSON problem details objects. * * @author Marcus Portmann */ @ControllerAdvice @SuppressWarnings("unused") public class ProblemHandler { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(ProblemHandler.class); /** Is debugging enabled for the Inception Framework? */ @Value("${inception.debug.enabled:#{false}}") private boolean inDebugMode; /** Constructs a new <b>ProblemHandler</b>. */ public ProblemHandler() {} /** * Handle the service exception. * * @param request the HTTP request * @param serviceException the service exception * @return the problem details response entity containing the service exception information */ @ExceptionHandler @ResponseBody protected ResponseEntity<ProblemDetails> handle( HttpServletRequest request, ServiceException serviceException) { if (inDebugMode) { logger.error( "Failed to process the HTTP servlet request (" + request.getRequestURI() + ")", serviceException); } ProblemDetails problemDetails = new ProblemDetails(); problemDetails.setTimestamp(serviceException.getTimestamp()); Problem problem = AnnotatedElementUtils.findMergedAnnotation(serviceException.getClass(), Problem.class); if (problem != null) { problemDetails.setType(problem.type()); problemDetails.setTitle(problem.title()); problemDetails.setStatus(problem.status()); } else if (serviceException instanceof InvalidArgumentException) { problemDetails.setType("http://inception.absa.africa/problems/invalid-argument"); problemDetails.setTitle("Invalid argument."); problemDetails.setStatus(HttpStatus.BAD_REQUEST.value()); InvalidArgumentException invalidArgumentException = (InvalidArgumentException) serviceException; problemDetails.setParameter(invalidArgumentException.getParameter()); problemDetails.setValidationErrors(invalidArgumentException.getValidationErrors()); } else if (serviceException instanceof ServiceUnavailableException) { problemDetails.setType("http://inception.absa.africa/problems/service-unavailable"); problemDetails.setTitle( "An error has occurred and your request could not be processed at this time."); problemDetails.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); } else { problemDetails.setType("about:blank"); problemDetails.setTitle( "An error has occurred and your request could not be processed at this time."); problemDetails.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); } problemDetails.setDetail(serviceException.getMessage()); if (inDebugMode) { logger.error(serviceException.getMessage(), serviceException); problemDetails.setStackTrace(dumpStackTrace(serviceException)); } return new ResponseEntity<>(problemDetails, new HttpHeaders(), problemDetails.getStatus()); } /** * Handle the access denied exception. * * @param request the HTTP request * @param accessDeniedException the access denied exception * @return the problem details response entity containing the access denied exception information */ @ExceptionHandler @ResponseBody protected ResponseEntity<ProblemDetails> handle( HttpServletRequest request, AccessDeniedException accessDeniedException) { ProblemDetails problemDetails = new ProblemDetails(); problemDetails.setTimestamp(LocalDateTime.now()); problemDetails.setType("http://inception.absa.africa/problems/access-denied"); problemDetails.setTitle("Access denied."); problemDetails.setStatus(HttpStatus.FORBIDDEN.value()); problemDetails.setDetail(accessDeniedException.getMessage()); if (inDebugMode) { problemDetails.setStackTrace(dumpStackTrace(accessDeniedException)); } return new ResponseEntity<>(problemDetails, new HttpHeaders(), problemDetails.getStatus()); } /** * Handle the exception. * * @param request the HTTP request * @param cause the exception * @return the problem details response entity containing the exception information */ @ExceptionHandler @ResponseBody protected ResponseEntity<ProblemDetails> handle(HttpServletRequest request, Throwable cause) { if (inDebugMode) { logger.error( "Failed to process the HTTP servlet request (" + request.getRequestURI() + ")", cause); } ProblemDetails problemDetails = new ProblemDetails(); problemDetails.setTimestamp(LocalDateTime.now()); problemDetails.setType("about:blank"); problemDetails.setTitle( "An error has occurred and your request could not be processed at this time."); problemDetails.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); problemDetails.setDetail(cause.getMessage()); if (inDebugMode) { problemDetails.setStackTrace(dumpStackTrace(cause)); } return new ResponseEntity<>(problemDetails, new HttpHeaders(), problemDetails.getStatus()); } private String dumpStackTrace(Throwable throwable) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); throwable.printStackTrace(pw); pw.flush(); return baos.toString(); } catch (Throwable e) { return "Failed to retrieve the exception stack trace: " + e.getMessage(); } } }
0
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-api/1.2.0/africa/absa/inception/api/SecureApi.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.api; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.context.ApplicationContext; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; /** * The <b>SecureApi</b> class provides the base class from which all RESTful controllers that * implement secure APIs should be derived. * * @author Marcus Portmann */ @SuppressWarnings("unused") public abstract class SecureApi { /** The code for the Administrator role. */ private static final String ADMINISTRATOR_ROLE_CODE = "Administrator"; /** Is debugging enabled for the Inception Framework? */ private boolean inDebugMode; /** Is API security enabled for the Inception Framework? */ private boolean isSecurityEnabled; /** * Constructs a new <b>SecureApi</b>. * * @param applicationContext the Spring application context */ public SecureApi(ApplicationContext applicationContext) { // Check if debugging is enabled for the Inception Framework try { if (StringUtils.hasText( applicationContext.getEnvironment().getProperty("inception.debug.enabled"))) { this.inDebugMode = Boolean.parseBoolean( applicationContext.getEnvironment().getProperty("inception.debug.enabled")); } } catch (Throwable e) { this.inDebugMode = false; } // Check if security is enabled for the Inception Framework try { if (StringUtils.hasText( applicationContext.getEnvironment().getProperty("inception.api.security.enabled"))) { this.isSecurityEnabled = Boolean.parseBoolean( applicationContext.getEnvironment().getProperty("inception.api.security.enabled")); } } catch (Throwable e) { this.isSecurityEnabled = !this.inDebugMode; } } /** * Returns whether debugging is enabled for the Inception Framework. * * @return <b>true</b> if debugging is enabled for the Inception Framework or <b>false</b> * otherwise */ public boolean inDebugMode() { return inDebugMode; } /** * Returns whether API security is disabled. * * @return <b>true</b> if API security is disabled or <b>false</b> otherwise */ public boolean isSecurityDisabled() { return !isSecurityEnabled; } /** * Returns whether API security is enabled. * * @return <b>true</b> if API security is enabled or <b>false</b> otherwise */ public boolean isSecurityEnabled() { return isSecurityEnabled; } /** * Returns the <b>Long</b> value portion of the authorities with the specified prefix. * * @param authentication the authenticated principal associated with the authenticated request * @param prefix the authority prefix * @return the <b>Long</b> value portion of the authorities with the specified prefix */ protected List<Long> getLongValuesForAuthoritiesWithPrefix( Authentication authentication, String prefix) { var values = new ArrayList<Long>(); for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().startsWith(prefix)) { try { values.add(Long.parseLong(authority.getAuthority().substring(prefix.length()))); } catch (Throwable ignored) { } } } return values; } /** * Returns the <b>UUID</b> value portion of the authorities with the specified prefix. * * @param authentication the authenticated principal associated with the authenticated request * @param prefix the authority prefix * @return the <b>UUID</b> value portion of the authorities with the specified prefix */ protected List<UUID> getUUIDValuesForAuthoritiesWithPrefix( Authentication authentication, String prefix) { var values = new ArrayList<UUID>(); for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().startsWith(prefix)) { try { values.add(UUID.fromString(authority.getAuthority().substring(prefix.length()))); } catch (Throwable ignored) { } } } return values; } /** * Returns the value portion of the authority with the specified prefix. * * @param authentication the authenticated principal associated with the authenticated request * @param prefix the authority prefix * @return an Optional containing the value portion of the authority with the specified prefix or * an empty Optional if the authority with the specified prefix could not be found */ protected Optional<String> getValueForAuthorityWithPrefix( Authentication authentication, String prefix) { for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().startsWith(prefix)) { return Optional.of(authority.getAuthority().substring(prefix.length())); } } return Optional.empty(); } /** * Returns the value portion of the authorities with the specified prefix. * * @param authentication the authenticated principal associated with the authenticated request * @param prefix the authority prefix * @return the value portion of the authorities with the specified prefix */ protected List<String> getValuesForAuthoritiesWithPrefix( Authentication authentication, String prefix) { var values = new ArrayList<String>(); for (GrantedAuthority authority : authentication.getAuthorities()) { if (authority.getAuthority().startsWith(prefix)) { values.add(authority.getAuthority().substring(prefix.length())); } } return values; } /** * Confirm that the user associated with the authenticated request has access to the specified * function. * * @param functionCode the code for the function * @return <b>true</b> if the user associated with the authenticated request has access to the * function identified by the specified function code or <b>false</b> otherwise */ protected boolean hasAccessToFunction(String functionCode) { return hasAuthority("FUNCTION_" + functionCode); } /** * Confirm that the user associated with the authenticated request has access to the tenant. * * @param tenantId the ID for the tenant * @return <b>true</b> if the user associated with the authenticated request has access to the * tenant or <b>false</b> otherwise */ protected boolean hasAccessToTenant(UUID tenantId) { if (isSecurityEnabled) { if (tenantId == null) { return false; } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Could not retrieve the currently authenticated principal if (authentication == null) { return false; } // If the user is not authenticated then they cannot have access if (!authentication.isAuthenticated()) { return false; } // If the user has the "Administrator" role they always have access if (hasRole(ADMINISTRATOR_ROLE_CODE)) { return true; } List<UUID> tenantIds = getUUIDValuesForAuthoritiesWithPrefix(authentication, "TENANT_"); return tenantIds.contains(tenantId); } else { return true; } } /** * Confirm that the user associated with the authenticated request has the specified authority. * * @param authority the authority * @return <b>true</b> if the user associated with the authenticated request has the specified * authority or <b>false</b> otherwise */ protected boolean hasAuthority(String authority) { if (isSecurityEnabled) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Could not retrieve the currently authenticated principal if (authentication == null) { return false; } if (!StringUtils.hasText(authority)) { return false; } if (!authentication.isAuthenticated()) { return false; } for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { if (grantedAuthority.getAuthority().equalsIgnoreCase(authority)) { return true; } } return false; } else { return true; } } /** * Confirm that the user associated with the authenticated request has the specified role. * * @param roleName the name of the role * @return <b>true</b> if the user associated with the authenticated request has the specified * role or <b>false</b> otherwise */ protected boolean hasRole(String roleName) { return hasAuthority("ROLE_" + roleName); } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/Application.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import africa.absa.inception.core.support.MergedMessageSource; import africa.absa.inception.json.DateTimeModule; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import javax.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import org.springframework.stereotype.Component; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; /** * The <b>Application</b> class provides the class that all application-specific application classes * should be derived from. * * @author Marcus Portmann */ @Component @ComponentScan( basePackages = {"africa.absa.inception"}, lazyInit = true) @EnableAsync @EnableScheduling @SuppressWarnings({"unused"}) public abstract class Application implements WebApplicationInitializer { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(Application.class); /** The Spring application context. */ private final ApplicationContext applicationContext; /** The distributed in-memory caches. */ Map<String, Map<?, ?>> caches = new ConcurrentHashMap<>(); /** * Constructs a new <b>Application</b>. * * @param applicationContext the Spring application context */ protected Application(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the Spring application context. * * @return the Spring application context */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * Returns the Jackson2 object mapper. * * @return the Jackson2 object mapper */ @Bean public ObjectMapper objectMapper() { return jackson2ObjectMapperBuilder().build().disable(SerializationFeature.INDENT_OUTPUT); } @Override public void onStartup(ServletContext container) { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); container.addListener(new ContextLoaderListener(rootContext)); } /** * Returns the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON * processor package. * * @return the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON * processor package */ protected Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() { Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder(); jackson2ObjectMapperBuilder.indentOutput(true); /* * Install the custom Jackson module that supports serializing and de-serializing ISO 8601 date * and date/time values. The jackson-datatype-jsr310 module provided by Jackson was not used as * it does not handle timezones correctly for LocalDateTime objects. */ jackson2ObjectMapperBuilder.modulesToInstall(new DateTimeModule()); return jackson2ObjectMapperBuilder; } /** * Returns the application message source. * * @return the application message source */ @Bean protected MessageSource messageSource() { MergedMessageSource messageSource = new MergedMessageSource(); messageSource.setBasename("classpath*:messages"); return messageSource; } /** * Returns the metric registry. * * @return the metric registry */ @Bean protected MetricRegistry metricRegistry() { return new MetricRegistry(); } /** * Returns the Spring task executor to use for @Async method invocations. * * @return the Spring task executor to use for @Async method invocations */ @Bean protected Executor taskExecutor() { return new SimpleAsyncTaskExecutor(); } /** * Returns the Spring task scheduler. * * @return the Spring task scheduler */ @Bean protected TaskScheduler taskScheduler() { return new ConcurrentTaskScheduler(); } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/ApplicationDataSourceConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import io.agroal.api.AgroalDataSource; import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier; import io.agroal.api.configuration.supplier.AgroalPropertiesReader; import io.agroal.api.transaction.TransactionIntegration; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.Properties; import javax.sql.DataSource; import liquibase.Contexts; import liquibase.LabelExpression; import liquibase.Liquibase; import liquibase.configuration.HubConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.resource.ClassLoaderResourceAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * The <b>ApplicationDataSourceConfiguration</b> class provides access to the application data * source configuration and initialises the application data source. * * @author Marcus Portmann */ @Configuration @EnableAutoConfiguration( exclude = {DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class}) @ConditionalOnProperty({ "inception.application.data-source.class-name", "inception.application.data-source.url" }) @SuppressWarnings("unused") public class ApplicationDataSourceConfiguration { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(ApplicationDataSourceConfiguration.class); /** The Spring application context. */ private final ApplicationContext applicationContext; /** * The fully qualified name of the data source class used to connect to the application database. */ @Value("${inception.application.data-source.class-name:#{null}}") private String className; /** Execute the Liquibase changelogs using the data context. */ @Value("${inception.application.data-source.liquibase.apply-data-context:#{true}}") private boolean liquibaseApplyDataContext; /** * The Liquibase changelog resources on the classpath used to initialize the application database. */ @Value("classpath*:**/db/*.changelog.xml") private Resource[] liquibaseChangelogResources; /** Is Liquibase enabled? */ @Value("${inception.application.data-source.liquibase.enabled:#{true}}") private boolean liquibaseEnabled; /** * The maximum size of the database connection pool used to connect to the application database. */ @Value("${inception.application.data-source.max-pool-size:5}") private int maxPoolSize; /** * The minimum size of the database connection pool used to connect to the application database. */ @Value("${inception.application.data-source.min-pool-size:1}") private int minPoolSize; /** The password for the application database. */ @Value("${inception.application.data-source.password:#{null}}") private String password; /** The URL used to connect to the application database. */ @Value("${inception.application.data-source.url:#{null}}") private String url; /** The username for the application database. */ @Value("${inception.application.data-source.username:#{null}}") private String username; /** * Constructs a new <b>ApplicationDataSourceConfiguration</b>. * * @param applicationContext the Spring application context */ public ApplicationDataSourceConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the data source that can be used to interact with the application database. * * @return the data source that can be used to interact with the in-memory database */ @Bean @Primary public DataSource applicationDataSource() { try { // See: https://agroal.github.io/docs.html Properties agroalProperties = new Properties(); agroalProperties.setProperty(AgroalPropertiesReader.JDBC_URL, url); if (StringUtils.hasText(username)) { agroalProperties.setProperty(AgroalPropertiesReader.PRINCIPAL, username); } if (StringUtils.hasText(password)) { agroalProperties.setProperty(AgroalPropertiesReader.CREDENTIAL, password); } agroalProperties.setProperty(AgroalPropertiesReader.PROVIDER_CLASS_NAME, className); agroalProperties.setProperty( AgroalPropertiesReader.MIN_SIZE, (minPoolSize > 0) ? Integer.toString(minPoolSize) : "1"); agroalProperties.setProperty( AgroalPropertiesReader.MAX_SIZE, (maxPoolSize > 0) ? Integer.toString(maxPoolSize) : "5"); AgroalPropertiesReader agroalReaderProperties2 = new AgroalPropertiesReader().readProperties(agroalProperties); AgroalDataSourceConfigurationSupplier agroalDataSourceConfigurationSupplier = agroalReaderProperties2.modify(); try { TransactionIntegration transactionIntegration = applicationContext.getBean(TransactionIntegration.class); if (transactionIntegration != null) { agroalDataSourceConfigurationSupplier .connectionPoolConfiguration() .transactionIntegration(transactionIntegration); } } catch (NoSuchBeanDefinitionException ignored) { } DataSource dataSource = AgroalDataSource.from(agroalDataSourceConfigurationSupplier); // /* // * The SAP JDBC driver does not return a DataSource, instead it provides connections so // we // * make use of the DriverManagerDataSource. // */ // if (dataSourceClass.equals("com.sap.db.jdbc.Driver")) // { // DriverManagerDataSource ds = new DriverManagerDataSource(); // ds.setDriverClassName(dataSourceClass); // ds.setUrl(url); // dataSource = ds; // } // else // { // Class<? extends DataSource> dataSourceClass = // Thread.currentThread().getContextClassLoader() // .loadClass(this.dataSourceClass).asSubclass(DataSource.class); // // dataSource = DataSourceBuilder.create().type(dataSourceClass).url(url).build(); // } boolean isInMemoryH2Database = false; try (Connection connection = dataSource.getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); logger.info( "Connected to the " + metaData.getDatabaseProductName() + " application database with version " + metaData.getDatabaseProductVersion()); switch (metaData.getDatabaseProductName()) { case "H2": isInMemoryH2Database = true; break; default: logger.info( "The default database tables will not be populated for the database type (" + metaData.getDatabaseProductName() + ")"); break; } } // Initialize the in-memory database using Liquibase changeSets if (isInMemoryH2Database || liquibaseEnabled) { if (isInMemoryH2Database) { logger.info("Initializing the in-memory H2 database using Liquibase"); } LiquibaseConfiguration.getInstance() .getConfiguration(HubConfiguration.class) .setLiquibaseHubMode("OFF"); try (Connection connection = dataSource.getConnection()) { liquibase.database.Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(new JdbcConnection(connection)); for (Resource changelogResource : liquibaseChangelogResources) { if (!changelogResource.getFilename().toLowerCase().endsWith("-data.changelog.xml")) { String changelogFile = "db/" + changelogResource.getFilename(); logger.info("Applying Liquibase changelog: " + changelogResource.getFilename()); Liquibase liquibase = new Liquibase(changelogFile, new ClassLoaderResourceAccessor(), database); liquibase.update(new Contexts(), new LabelExpression()); } } for (Resource changelogResource : liquibaseChangelogResources) { if (changelogResource.getFilename().toLowerCase().endsWith("-data.changelog.xml")) { String changelogFile = "db/" + changelogResource.getFilename(); logger.info("Applying Liquibase data changelog: " + changelogResource.getFilename()); Liquibase liquibase = new Liquibase(changelogFile, new ClassLoaderResourceAccessor(), database); liquibase.update(new Contexts(), new LabelExpression()); } } } } return dataSource; } catch (Throwable e) { throw new FatalBeanException("Failed to initialize the application data source", e); } } /** * Returns the fully qualified name of the data source class used to connect to the application * database. * * @return the fully qualified name of the data source class used to connect to the application * database */ public String getClassName() { return className; } /** * Returns the maximum size of the database connection pool used to connect to the application * database. * * @return the maximum size of the database connection pool used to connect to the application * database */ public int getMaxPoolSize() { return maxPoolSize; } /** * Returns the minimum size of the database connection pool used to connect to the application * database. * * @return the minimum size of the database connection pool used to connect to the application * database */ public int getMinPoolSize() { return minPoolSize; } /** * Returns the password for the application database. * * @return the password for the application database */ public String getPassword() { return password; } /** * Returns the URL used to connect to the application database. * * @return the URL used to connect to the application database */ public String getUrl() { return url; } /** * Returns the username for the application database. * * @return the username for the application database */ public String getUsername() { return username; } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/ApplicationException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import africa.absa.inception.core.exception.RichRuntimeException; /** * The <b>ApplicationException</b> exception is thrown to indicate an application error condition. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class ApplicationException extends RichRuntimeException { private static final long serialVersionUID = 1000000; /** Constructs a new <b>ApplicationException</b> with <b>null</b> as its message. */ public ApplicationException() { super(); } /** * Constructs a new <b>ApplicationException</b> with the specified message. * * @param message the message saved for later retrieval by the <b>getMessage()</b> method */ public ApplicationException(String message) { super(message); } /** * Constructs a new <b>ApplicationException</b> with the specified cause and a message of * <b>(cause==null ? null : cause.toString())</b> (which typically contains the class and message * of cause). * * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public ApplicationException(Throwable cause) { super(cause); } /** * Constructs a new <b>ApplicationException</b> with the specified code and message. * * @param code the error code for the error * @param message the message saved for later retrieval by the <b>getMessage()</b> method */ public ApplicationException(String code, String message) { super(code, message); } /** * Constructs a new <b>ApplicationException</b> with the specified message and cause. * * @param message the message saved for later retrieval by the <b>getMessage()</b> method * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public ApplicationException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new <b>ApplicationException</b> with the specified code, message and cause. * * @param code the error code for the error * @param message the message saved for later retrieval by the <b>getMessage()</b> method * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public ApplicationException(String code, String message, Throwable cause) { super(code, message, cause); } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/ApplicationJpaConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import africa.absa.inception.jpa.JpaUtil; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.StringUtils; /** * The <b>ApplicationJpaConfiguration</b> class initialises the JPA EntityManagerFactory for the * application. * * @author Marcus Portmann */ @Configuration @ConditionalOnClass( name = { "org.springframework.orm.jpa.JpaVendorAdapter", "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean", "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter", "org.springframework.transaction.PlatformTransactionManager" }) public class ApplicationJpaConfiguration { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(ApplicationJpaConfiguration.class); private final ApplicationContext applicationContext; /** * Constructs a new <b>ApplicationJpaConfiguration</b>. * * @param applicationContext the Spring application context */ ApplicationJpaConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the application entity manager factory bean associated with the application data * source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the application entity manager factory bean associated with the application data source */ @Bean @Primary @ConditionalOnBean( name = {"applicationDataSource"}, value = {DataSource.class}) public LocalContainerEntityManagerFactoryBean applicationEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "application", dataSource, platformTransactionManager, StringUtils.toStringArray(packagesToScanForEntities())); } /** * Returns the names of the packages to scan for JPA entity classes. * * @return the names of the packages to scan for JPA entity classes */ protected List<String> packagesToScanForEntities() { List<String> packagesToScan = new ArrayList<>(); // Add the base packages specified using the EnableJpaRepositories annotation Map<String, Object> annotatedBeans = applicationContext.getBeansWithAnnotation(EnableJpaRepositories.class); for (String beanName : annotatedBeans.keySet()) { Class<?> beanClass = annotatedBeans.get(beanName).getClass(); EnableJpaRepositories enableJpaRepositories = beanClass.getAnnotation(EnableJpaRepositories.class); if (enableJpaRepositories != null) { for (String basePackage : enableJpaRepositories.basePackages()) { if (!basePackage.startsWith("africa.absa.inception")) { // Replace any existing packages to scan with the higher level package packagesToScan.removeIf(packageToScan -> packageToScan.startsWith(basePackage)); // Check if there is a higher level package already being scanned if (packagesToScan.stream().noneMatch(basePackage::startsWith)) { packagesToScan.add(basePackage); } } } } } logger.info( "Scanning the following packages for JPA entities: " + StringUtils.collectionToDelimitedString(packagesToScan, ",")); return packagesToScan; } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/ApplicationSecurityConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import africa.absa.inception.core.configuration.ConfigurationException; import africa.absa.inception.core.util.CryptoUtil; import java.security.KeyStore; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; /** * The <b>ApplicationSecurityConfiguration</b> class provides access to the application security * configuration and initialises the application key store and trust store. * * @author Marcus Portmann */ @Configuration @ConditionalOnProperty(value = "inception.application.security.trustStore.path") @SuppressWarnings("unused") public class ApplicationSecurityConfiguration { /** The application key store alias. */ @Value("${inception.application.security.keyStore.alias:#{null}}") private String keyStoreAlias; /** The application key store password. */ @Value("${inception.application.security.keyStore.password:#{null}}") private String keyStorePassword; /** The application key store path. */ @Value("${inception.application.security.keyStore.path:#{null}}") private String keyStorePath; /** The application key store type. */ @Value("${inception.application.security.keyStore.type:#{null}}") private String keyStoreType; /** The optional application trust store password. */ @Value("${inception.application.security.trustStore.password:#{null}}") private String trustStorePassword; /** The optional application trust store path. */ @Value("${inception.application.security.trustStore.path:#{null}}") private String trustStorePath; /** The optional application trust store type. */ @Value("${inception.application.security.trustStore.type:#{null}}") private String trustStoreType; /** * Returns whether the key store configuration has been specified. * * @return <b>true</b> if the key store configuration has been specified or <b>false</b> otherwise */ public boolean hasKeyStoreConfiguration() { return ((StringUtils.hasText(keyStoreType)) && (StringUtils.hasText(keyStorePath)) && (StringUtils.hasText(keyStorePassword))); } /** * Returns whether the trust store configuration has been specified. * * @return <b>true</b> if the trust store configuration has been specified or <b>false</b> * otherwise */ public boolean hasTrustStoreConfiguration() { return ((StringUtils.hasText(trustStoreType)) && (StringUtils.hasText(trustStorePath))); } /** * Returns the application key store. * * @return the application key store */ @Bean(name = "applicationKeyStore") public KeyStore keyStore() { try { if (!StringUtils.hasText(keyStoreType)) { throw new ConfigurationException( "The type was not specified for the application key store"); } if (!StringUtils.hasText(keyStorePath)) { throw new ConfigurationException( "The path was not specified for the application key store"); } if (!StringUtils.hasText(keyStorePassword)) { throw new ConfigurationException( "The password was not specified for the application key store"); } return CryptoUtil.loadKeyStore(keyStoreType, keyStorePath, keyStorePassword); } catch (Throwable e) { throw new FatalBeanException("Failed to initialize the application key store", e); } } /** * Returns the application key store password. * * @return the application key store password */ @Bean(name = "applicationKeyStorePassword") public String keyStorePassword() { return keyStorePassword; } /** * Returns the application trust store. * * @return the application trust store */ @Bean(name = "applicationTrustStore") public KeyStore trustStore() { try { if (!StringUtils.hasText(trustStoreType)) { throw new ConfigurationException( "The type was not specified for the application trust store"); } if (!StringUtils.hasText(trustStorePath)) { throw new ConfigurationException( "The path was not specified for the application trust store"); } trustStorePassword = StringUtils.hasText(trustStorePassword) ? trustStorePassword : ""; return CryptoUtil.loadTrustStore(trustStoreType, trustStorePath, trustStorePassword); } catch (Throwable e) { throw new FatalBeanException("Failed to initialize the application trust store", e); } } }
0
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-application/1.2.0/africa/absa/inception/application/SecureWebClientCustomizer.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.application; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.web.reactive.function.client.WebClientCustomizer; import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient.Builder; import reactor.netty.http.client.HttpClient; /** * The <b>SecureWebClientCustomizer</b> class implements the callback interface that can be used to * customize the {@link org.springframework.web.reactive.function.client.WebClient.Builder * WebClient.Builder} to apply the security configuration. * * @author Marcus Portmann */ @Component @ConditionalOnBean(ApplicationSecurityConfiguration.class) public class SecureWebClientCustomizer implements WebClientCustomizer { /** The application security configuration. */ ApplicationSecurityConfiguration applicationSecurityConfiguration; /** * Constructs a new <b>SecureWebClientCustomizer</b>. * * @param applicationSecurityConfiguration the application security configuration */ public SecureWebClientCustomizer( ApplicationSecurityConfiguration applicationSecurityConfiguration) { this.applicationSecurityConfiguration = applicationSecurityConfiguration; } @Override public void customize(Builder webClientBuilder) { try { KeyManagerFactory keyManagerFactory = null; if (applicationSecurityConfiguration.hasKeyStoreConfiguration()) { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init( applicationSecurityConfiguration.keyStore(), applicationSecurityConfiguration.keyStorePassword().toCharArray()); } TrustManagerFactory trustManagerFactory = null; if (applicationSecurityConfiguration.hasTrustStoreConfiguration()) { trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(applicationSecurityConfiguration.trustStore()); } SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); if (keyManagerFactory != null) { sslContextBuilder.keyManager(keyManagerFactory); } if (trustManagerFactory != null) { sslContextBuilder.trustManager(trustManagerFactory); } SslContext sslContext = sslContextBuilder.build(); HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient); webClientBuilder.clientConnector(connector); } catch (Throwable e) { throw new RuntimeException( "Failed to apply the security configuration to the web client builder", e); } } }
0
java-sources/africa/absa/inception-cache/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-cache/1.2.0/africa/absa/inception/cache/HazelcastServerCacheConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.cache; import com.hazelcast.config.AwsConfig; import com.hazelcast.config.Config; import com.hazelcast.config.EvictionConfig; import com.hazelcast.config.EvictionPolicy; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.config.JoinConfig; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MaxSizePolicy; import com.hazelcast.config.MulticastConfig; import com.hazelcast.config.NetworkConfig; import com.hazelcast.config.TcpIpConfig; import java.util.List; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>HazelcastServerCacheConfiguration</b> class provides the Hazelcast server cache * configuration. * * @author Marcus Portmann */ @Configuration @ConditionalOnClass(name = "com.hazelcast.config.Config") @ConditionalOnProperty(value = "inception.cache.hazelcast.server.enabled", havingValue = "true") @ConfigurationProperties("inception.cache.hazelcast.server") public class HazelcastServerCacheConfiguration { /** The distributed in-memory caches. */ private List<CacheConfig> caches; /** The distributed in-memory cache cluster configuration. */ private ClusterConfig cluster; /** Is the Hazelcast server cache enabled? */ private boolean enabled; /** Is port auto increment enabled? */ private boolean portAutoIncrement; /** * Returns the distributed in-memory caches. * * @return the distributed in-memory caches */ public List<CacheConfig> getCaches() { return caches; } /** * Returns the distributed in-memory cache cluster configuration. * * @return the distributed in-memory cache cluster configuration */ public ClusterConfig getCluster() { return cluster; } /** * Returns whether port auto increment is enabled. * * @return whether port auto increment is enabled */ public boolean getPortAutoIncrement() { return portAutoIncrement; } /** * Returns the Hazelcast configuration. * * @return the Hazelcast configuration */ @Bean(name = "hazelcastConfig") public Config hazelcastConfig() { Config config = new Config(); config.setInstanceName(getCluster().getName()); config.setProperty("hazelcast.logging.type", "slf4j"); config.setProperty("hazelcast.rest.enabled", "false"); NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.setPort(getCluster().getPort()); networkConfig.setPortAutoIncrement(portAutoIncrement); networkConfig.setReuseAddress(true); JoinConfig joinConfig = networkConfig.getJoin(); MulticastConfig multicastConfig = joinConfig.getMulticastConfig(); multicastConfig.setEnabled(false); AwsConfig awsConfig = joinConfig.getAwsConfig(); awsConfig.setEnabled(false); TcpIpConfig tcpIpConfig = joinConfig.getTcpIpConfig(); tcpIpConfig.setEnabled(true); // Add the cache members String[] members = {"127.0.0.1"}; if ((getCluster().getMembers() != null) && (getCluster().getMembers().trim().length() > 0)) { members = getCluster().getMembers().trim().split(","); } if (members.length > 0) { for (String member : members) { tcpIpConfig.addMember(member); } } config.setProperty("hazelcast.application.validation.token", getCluster().getPassword()); config.setClusterName(getCluster().getName()); // Initialise the caches for (CacheConfig cacheConfig : getCaches()) { MapConfig mapConfig = config.getMapConfig(cacheConfig.getName()); mapConfig.setInMemoryFormat( Enum.valueOf(InMemoryFormat.class, cacheConfig.getInMemoryFormat())); EvictionConfig evictionConfig = new EvictionConfig(); evictionConfig.setEvictionPolicy( Enum.valueOf(EvictionPolicy.class, cacheConfig.getEvictionPolicy())); evictionConfig.setMaxSizePolicy( Enum.valueOf(MaxSizePolicy.class, cacheConfig.getMaxSizePolicy())); evictionConfig.setSize(cacheConfig.getMaxSize()); mapConfig.setEvictionConfig(evictionConfig); mapConfig.setStatisticsEnabled(cacheConfig.getStatisticsEnabled()); mapConfig.setMaxIdleSeconds(cacheConfig.getMaxIdleSeconds()); mapConfig.setBackupCount(cacheConfig.getBackupCount()); mapConfig.setAsyncBackupCount(cacheConfig.getAsyncBackupCount()); mapConfig.setReadBackupData(cacheConfig.getReadBackupData()); } // HazelcastInstanceFactory return config; } /** * Returns whether the Hazelcast server cache is enabled. * * @return <b>true</b> if the Hazelcast server cache is enabled or <b>false</b> otherwise */ public boolean isEnabled() { return enabled; } /** * Set the distributed in-memory caches. * * @param caches the distributed in-memory caches */ public void setCaches(List<CacheConfig> caches) { this.caches = caches; } /** * Set the distributed in-memory cache cluster configuration. * * @param cluster the distributed in-memory cache cluster configuration */ public void setCluster(ClusterConfig cluster) { this.cluster = cluster; } /** * Set whether the Hazelcast server cache is enabled. * * @param enabled <b>true</b> if the Hazelcast server cache is enabled or <b>false</b> otherwise */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Set whether port auto increment is enabled. * * @param portAutoIncrement is port auto increment enabled */ public void setPortAutoIncrement(boolean portAutoIncrement) { this.portAutoIncrement = portAutoIncrement; } /** * The <b>CacheConfig</b> class provides access to the distributed in-memory cache configuration. */ public static class CacheConfig { /** Are statistics enabled for the distributed in-memory cache? */ boolean statisticsEnabled; /** The number of asynchronous backups for the distributed in-memory cache. */ private int asyncBackupCount; /** The number of synchronous backups for the distributed in-memory cache. */ private int backupCount; /** The eviction policy for the distributed in-memory cache. */ private String evictionPolicy; /** The in-memory format for the distributed in-memory cache. */ private String inMemoryFormat; /** The maximum idle seconds for the distributed in-memory cache. */ private int maxIdleSeconds; /** The maximum size for the distributed in-memory cache. */ private int maxSize; /** The maximum size policy for the distributed in-memory cache. */ private String maxSizePolicy; /** The name of the distributed in-memory cache. */ private String name; /** Is read-backup-data enabled for the distributed in-memory cache. */ private boolean readBackupData; /** * Returns the number of asynchronous backups for the distributed in-memory cache. * * @return the number of asynchronous backups for the distributed in-memory cache */ public int getAsyncBackupCount() { return asyncBackupCount; } /** * Returns the number of synchronous backups for the distributed in-memory cache. * * @return the number of synchronous backups for the distributed in-memory cache */ public int getBackupCount() { return backupCount; } /** * Returns the eviction policy for the distributed in-memory cache. * * @return the eviction policy for the distributed in-memory cache */ public String getEvictionPolicy() { return evictionPolicy; } /** * Returns the in-memory format for the distributed in-memory cache. * * @return the in-memory format for the distributed in-memory cache */ public String getInMemoryFormat() { return inMemoryFormat; } /** * Returns the maximum idle seconds for the distributed in-memory cache. * * @return the maximum idle seconds for the distributed in-memory cache */ public int getMaxIdleSeconds() { return maxIdleSeconds; } /** * Returns the maximum size for the distributed in-memory cache. * * @return the maximum size for the distributed in-memory cache */ public int getMaxSize() { return maxSize; } /** * Returns the maximum size policy for the distributed in-memory cache. * * @return the maximum size policy for the distributed in-memory cache */ public String getMaxSizePolicy() { return maxSizePolicy; } /** * Returns the name of the distributed in-memory cache. * * @return the name of the distributed in-memory cache */ public String getName() { return name; } /** * Returns whether read-backup-data is enabled for the distributed in-memory cache. * * @return <b>true</b> if read-backup-data is enabled for the distributed in-memory cache or * <b>false</b> otherwise */ public boolean getReadBackupData() { return readBackupData; } /** * Returns whether statistics are enabled for the distributed in-memory cache? * * @return <b>true</b> if statistics are enabled for the distributed in-memory cache or * <b>false</b> otherwise */ public boolean getStatisticsEnabled() { return statisticsEnabled; } /** * Set the number of asynchronous backups for the distributed in-memory cache. * * @param asyncBackupCount the number of asynchronous backups for the distributed in-memory * cache */ public void setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = asyncBackupCount; } /** * Set the number of synchronous backups for the distributed in-memory cache. * * @param backupCount the number of synchronous backups for the distributed in-memory cache */ public void setBackupCount(int backupCount) { this.backupCount = backupCount; } /** * Set the eviction policy for the distributed in-memory cache. * * @param evictionPolicy the eviction policy for the distributed in-memory cache */ public void setEvictionPolicy(String evictionPolicy) { this.evictionPolicy = evictionPolicy; } /** * Set the in-memory format for the distributed in-memory cache. * * @param inMemoryFormat the in-memory format for the distributed in-memory cache */ public void setInMemoryFormat(String inMemoryFormat) { this.inMemoryFormat = inMemoryFormat; } /** * Set the maximum idle seconds for the distributed in-memory cache. * * @param maxIdleSeconds the maximum idle seconds for the distributed in-memory cache */ public void setMaxIdleSeconds(int maxIdleSeconds) { this.maxIdleSeconds = maxIdleSeconds; } /** * Set the maximum size for the distributed in-memory cache. * * @param maxSize the maximum size for the distributed in-memory cache */ public void setMaxSize(int maxSize) { this.maxSize = maxSize; } /** * Set the maximum size policy for the distributed in-memory cache. * * @param maxSizePolicy the maximum size policy for the distributed in-memory cache */ public void setMaxSizePolicy(String maxSizePolicy) { this.maxSizePolicy = maxSizePolicy; } /** * Set the name of the distributed in-memory cache. * * @param name the name of the distributed in-memory cache */ public void setName(String name) { this.name = name; } /** * Set whether read-backup-data is enabled for the distributed in-memory cache. * * @param readBackupData <b>true</b> if read-backup-data enabled for the distributed in-memory * cache or <b>false</b> otherwise */ public void setReadBackupData(boolean readBackupData) { this.readBackupData = readBackupData; } /** * Set whether statistics are enabled for the distributed in-memory cache. * * @param statisticsEnabled <b>true</b> if statistics are enabled for the distributed in-memory * cache or <b>false</b> otherwise */ public void setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; } } /** * The <b>ClusterConfig</b> class provides access to the distributed in-memory cache cluster * configuration. */ public static class ClusterConfig { /** * The comma-delimited IP addresses or hostnames for the members of the distributed in-memory * cache cluster. */ private String members; /** The name of the distributed in-memory cache cluster. */ private String name; /** The password used to connect to the distributed in-memory cache cluster. */ private String password; /** The port for the distributed in-memory cache cluster. */ private int port; /** * Returns the comma-delimited IP addresses or hostnames for the members of the distributed * in-memory cache cluster. * * @return the comma-delimited IP addresses or hostnames for the members of the distributed * in-memory cache cluster */ public String getMembers() { return members; } /** * Returns the name of the distributed in-memory cache cluster. * * @return the name of the distributed in-memory cache cluster */ public String getName() { return name; } /** * Returns the password used to connect to the distributed in-memory cache cluster. * * @return the password used to connect to the distributed in-memory cache cluster */ public String getPassword() { return password; } /** * Returns the port for the distributed in-memory cache cluster. * * @return the port for the distributed in-memory cache cluster */ public int getPort() { return port; } /** * Set the comma-delimited IP addresses or hostnames for the members of the distributed * in-memory cache cluster. * * @param members the comma-delimited IP addresses or hostnames for the members of the * distributed in-memory cache cluster */ public void setMembers(String members) { this.members = members; } /** * Set the name of the distributed in-memory cache cluster. * * @param name the name of the distributed in-memory cache cluster */ public void setName(String name) { this.name = name; } /** * Set the password used to connect to the distributed in-memory cache cluster. * * @param password the password used to connect to the distributed in-memory cache cluster */ public void setPassword(String password) { this.password = password; } /** * Set the port for the distributed in-memory cache cluster. * * @param port the port for the distributed in-memory cache cluster */ public void setPort(int port) { this.port = port; } } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/Code.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Code</b> class holds the information for a code. * * @author Marcus Portmann */ @Schema( description = "Reference data in the form of a key-value pair that is used to classify or categorize other data") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "codeCategoryId", "name", "value"}) @Entity @Table(schema = "codes", name = "codes") @IdClass(CodeId.class) public class Code implements Serializable { private static final long serialVersionUID = 1000000; /** The ID for the code category the code is associated with. */ @Schema(description = "The ID for the code category the code is associated with", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "code_category_id", length = 100, nullable = false) private String codeCategoryId; /** The date and time the code was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The ID for the code. */ @Schema(description = "The ID for the code", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the code. */ @Schema(description = "The name of the code", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The date and time the code was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** The value for the code. */ @Schema(description = "The value for the code", required = true) @JsonProperty(required = true) @NotNull @Size(max = 4000) @Column(name = "value", length = 4000, nullable = false) private String value; /** Constructs a new <b>Code</b>. */ public Code() {} /** * Constructs a new <b>Code</b>. * * @param codeCategoryId the ID for the code category the code is associated with */ public Code(String codeCategoryId) { this.codeCategoryId = codeCategoryId; } /** * Constructs a new <b>Code</b>. * * @param id the ID for the code * @param codeCategoryId the ID for the code category the code is associated with * @param name the name of the code * @param value the value for the code */ public Code(String id, String codeCategoryId, String name, String value) { this.id = id; this.codeCategoryId = codeCategoryId; this.name = name; this.value = value; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Code other = (Code) object; return Objects.equals(codeCategoryId, other.codeCategoryId) && Objects.equals(id, other.id); } /** * Returns the ID for the code category the code is associated with. * * @return the ID for the code category the code is associated with */ public String getCodeCategoryId() { return codeCategoryId; } /** * Returns the date and time the code was created. * * @return the date and time the code was created */ public LocalDateTime getCreated() { return created; } /** * Returns the ID for the code. * * @return the ID for the code */ public String getId() { return id; } /** * Returns the name of the code. * * @return the name of the code */ public String getName() { return name; } /** * Returns the date and time the code was last updated. * * @return the date and time the code was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns the value for the code. * * @return the value for the code */ public String getValue() { return this.value; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((codeCategoryId == null) ? 0 : codeCategoryId.hashCode()) + ((id == null) ? 0 : id.hashCode()); } /** * Set the ID for the code category the code is associated with. * * @param codeCategoryId the ID for the code category the code is associated with */ public void setCodeCategoryId(String codeCategoryId) { this.codeCategoryId = codeCategoryId; } /** * Set the ID for the code. * * @param id the ID for the code */ public void setId(String id) { this.id = id; } /** * Set the name of the code. * * @param name the name of the code */ public void setName(String name) { this.name = name; } /** * Set the value for the code. * * @param value the value for the code */ public void setValue(String value) { this.value = value; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeCategory.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>CodeCategory</b> class holds the information for a code category. * * @author Marcus Portmann */ @Schema(description = "A collection of related codes") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "data"}) @Entity @Table(schema = "codes", name = "code_categories") public class CodeCategory implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the code category was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The optional code data for the code category. */ @Schema(description = "The optional code data for the code category") @JsonProperty @Column(name = "data") private String data; /** The ID for the code category. */ @Schema(description = "The ID for the code category", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the code category. */ @Schema(description = "The name of the code category", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The date and time the code category was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** Constructs a new <b>CodeCategory</b>. */ public CodeCategory() {} /** * Constructs a new <b>CodeCategory</b>. * * @param id the ID for the code category * @param name the name of the code category */ public CodeCategory(String id, String name) { this.id = id; this.name = name; } /** * Constructs a new <b>CodeCategory</b>. * * @param id the ID for the code category * @param name the name of the code category * @param data the optional code data for the code category */ public CodeCategory(String id, String name, String data) { this.id = id; this.name = name; this.data = data; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } CodeCategory other = (CodeCategory) object; return Objects.equals(id, other.id); } /** * Returns the date and time the code category was created. * * @return the date and time the code category was created */ public LocalDateTime getCreated() { return created; } /** * Returns the optional code data for the code category. * * @return the optional code data for the code category */ public String getData() { return data; } /** * Returns the ID for the code category. * * @return the ID for the code category */ public String getId() { return id; } /** * Returns the name of the code category. * * @return the name of the code category */ public String getName() { return name; } /** * Returns the date and time the code category was last updated. * * @return the date and time the code category was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Set the code data for the code category. * * @param data the code data for the code category */ public void setData(String data) { this.data = data; } /** * Set the ID for the code category. * * @param id the ID for the code category */ public void setId(String id) { this.id = id; } /** * Set the name of the code category. * * @param name the name of the code category */ public void setName(String name) { this.name = name; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeCategoryNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>CodeCategoryNotFoundException</b> exception is thrown to indicate an error condition as a * result of a code category that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/codes/code-category-not-found", title = "The code category could not be found.", status = 404) public class CodeCategoryNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>CodeCategoryNotFoundException</b>. * * @param codeCategoryId the ID for the code category */ public CodeCategoryNotFoundException(String codeCategoryId) { super("The code category with ID (" + codeCategoryId + ") could not be found"); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeCategoryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import java.time.LocalDateTime; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>CodeCategoryRepository</b> interface declares the repository for the <b>CodeCategory</b> * domain type. * * @author Marcus Portmann */ public interface CodeCategoryRepository extends JpaRepository<CodeCategory, String> { /** * Delete the code category. * * @param codeCategoryId the ID for the code category */ @Modifying @Query("delete from CodeCategory cc where cc.id = :codeCategoryId") void deleteById(@Param("codeCategoryId") String codeCategoryId); /** * Retrieve the data for the code category. * * @param codeCategoryId the ID for the code category * @return an Optional containing the data for the code category or an empty Optional if the code * category could not be found */ @Query("select cc.data from CodeCategory cc where cc.id = :codeCategoryId") Optional<String> getDataById(@Param("codeCategoryId") String codeCategoryId); /** * Retrieve the name for the code category. * * @param codeCategoryId the ID for the code category * @return an Optional containing the name for the code category or an empty Optional if the code * category could not be found */ @Query("select cc.name from CodeCategory cc where cc.id = :codeCategoryId") Optional<String> getNameById(@Param("codeCategoryId") String codeCategoryId); /** * Retrieve the date and time the code category was last updated. * * @param codeCategoryId the ID for the code category * @return an Optional containing the date and time the code category was last updated or an empty * Optional if the code category could not be found */ @Query("select cc.updated from CodeCategory cc where cc.id = :codeCategoryId") Optional<LocalDateTime> getUpdatedById(@Param("codeCategoryId") String codeCategoryId); /** * Set the data and the date and time the code category was last updated. * * @param codeCategoryId the ID for the code category * @param data the data * @param updated the date and time the code category was last updated * @return the number of code categories that were updated */ @Modifying @Query( "update CodeCategory cc set cc.data = :data, cc.updated = :updated " + "where cc.id = :codeCategoryId") int setDataAndUpdatedById( @Param("codeCategoryId") String codeCategoryId, @Param("data") String data, @Param("updated") LocalDateTime updated); }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeCategorySummary.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>CodeCategorySummary</b> class holds the summary information for a code category. * * @author Marcus Portmann */ @Schema(description = "A code category summary") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "updated"}) @Entity @Table(schema = "codes", name = "code_categories") public class CodeCategorySummary implements Serializable { private static final long serialVersionUID = 1000000; /** The ID for the code category. */ @Schema(description = "The ID for the code category", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the code category. */ @Schema(description = "The name of the code category", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The date and time the code category was last updated. */ @Schema(description = "The date and time the code category was last updated") @JsonProperty @Column(name = "updated") private LocalDateTime updated; /** Constructs a new <b>CodeCategorySummary</b>. */ public CodeCategorySummary() {} /** * Constructs a new <b>CodeCategorySummary</b>. * * @param id the ID for the code category * @param name the name of the code category * @param updated the date and time the code category was last updated */ public CodeCategorySummary(String id, String name, LocalDateTime updated) { this.id = id; this.name = name; this.updated = updated; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } CodeCategorySummary other = (CodeCategorySummary) object; return Objects.equals(id, other.id); } /** * Returns the ID for the code category. * * @return the ID for the code category */ public String getId() { return id; } /** * Returns the name of the code category. * * @return the name of the code category */ public String getName() { return name; } /** * Returns the date and time the code category was last updated. * * @return the date and time the code category was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeCategorySummaryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import org.springframework.data.jpa.repository.JpaRepository; /** * The <b>CodeCategorySummaryRepository</b> interface declares the repository for the <b> * CodeCategorySummary</b> domain type. * * @author Marcus Portmann */ public interface CodeCategorySummaryRepository extends JpaRepository<CodeCategorySummary, String> {}
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import java.io.Serializable; import java.util.Objects; /** * The <b>CodeId</b> class implements the ID class for the <b>Code</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class CodeId implements Serializable { private static final long serialVersionUID = 1000000; /** The ID for the code category the code is associated with. */ private String codeCategoryId; /** The ID for the code. */ private String id; /** Constructs a new <b>CodeId</b>. */ public CodeId() {} /** * Constructs a new <b>CodeId</b>. * * @param codeCategoryId the ID for the code category the code is associated with * @param id the ID for the code */ public CodeId(String codeCategoryId, String id) { this.codeCategoryId = codeCategoryId; this.id = id; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } CodeId other = (CodeId) object; return Objects.equals(codeCategoryId, other.codeCategoryId) && Objects.equals(id, other.id); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((codeCategoryId == null) ? 0 : codeCategoryId.hashCode()) + ((id == null) ? 0 : id.hashCode()); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>CodeNotFoundException</b> exception is thrown to indicate an error condition as a result * of a code that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/codes/code-not-found", title = "The code could not be found.", status = 404) public class CodeNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>CodeNotFoundException</b>. * * @param codeCategoryId the ID for the code category the code is associated with * @param codeId the ID for the code */ public CodeNotFoundException(String codeCategoryId, String codeId) { super( "The code with ID (" + codeId + ") for the code category with ID (" + codeCategoryId + ") could not be found"); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeProviderConfig.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import java.io.Serializable; /** * The <b>CodeProviderConfig</b> class stores the configuration information for a code provider. * This is the configuration read from the META-INF/code-providers.xml configuration files on the * classpath. * * @author Marcus Portmann */ @SuppressWarnings("WeakerAccess") public class CodeProviderConfig implements Serializable { private static final long serialVersionUID = 1000000; /** The fully qualified name of the class that implements the code provider. */ private final String className; /** The name of the code provider. */ private final String name; /** * Constructs a new <b>CodeProviderConfig</b>. * * @param name the name of the code provider * @param className fully qualified name of the class that implements the code provider */ CodeProviderConfig(String name, String className) { this.name = name; this.className = className; } /** * Return the fully qualified name of the class that implements the code provider. * * @return the fully qualified name of the class that implements the code provider */ public String getClassName() { return className; } /** * Returns the name of the code provider. * * @return the name of the code provider */ public String getName() { return name; } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeProviderException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; /** * The <b>CodeProviderException</b> exception is thrown to indicate an error condition when invoking * a code provider. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class CodeProviderException extends Exception { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>CodeProviderException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public CodeProviderException(String message) { super(message); } /** * Constructs a new <b>CodeProviderException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public CodeProviderException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodeRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.codes; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>CodeRepository</b> interface declares the repository for the <b>Code</b> domain type. * * @author Marcus Portmann */ public interface CodeRepository extends JpaRepository<Code, CodeId> { /** * Delete the code. * * @param codeCategoryId the ID for the code category the code is associated with * @param codeId the ID for the code */ @Modifying @Query("delete from Code c where c.codeCategoryId = :codeCategoryId and c.id = :codeId") void deleteById(@Param("codeCategoryId") String codeCategoryId, @Param("codeId") String codeId); /** * Retrieve the codes for the code category. * * @param codeCategoryId the ID for the code category the codes are associated with * @return the codes for the code category */ List<Code> findByCodeCategoryId(String codeCategoryId); /** * Retrieve the name for the code. * * @param codeCategoryId the ID for the code category the code is associated with * @param codeId the ID for the code * @return an Optional containing the name for the code or an empty Optional if the code could not * be found */ @Query("select c.name from Code c where c.codeCategoryId = :codeCategoryId and c.id = :codeId") Optional<String> getNameById( @Param("codeCategoryId") String codeCategoryId, @Param("codeId") String codeId); }