method2testcases
stringlengths
118
3.08k
### Question: ServerSynchronization extends UnicastExportable implements RemoteSynchronization { public void beforeCompletion() { sync.beforeCompletion(); } ServerSynchronization(Synchronization sync, Exporter exporter); void afterCompletion(int status); void beforeCompletion(); }### Answer: @Test public void testBeforeCompletion() throws RemoteException { reset(sync); sync.beforeCompletion(); replay(sync); ss.beforeCompletion(); verify(sync); }
### Question: FSBlob extends AbstractBlob { @Override public boolean exists() throws IOException { ensureOpen(); return file.exists(); } FSBlob(FSBlobStoreConnection connection, File baseDir, URI blobId, StreamManager manager, Set<File> modified); @Override URI getCanonicalId(); @Override InputStream openInputStream(); @Override OutputStream openOutputStream(long estimatedSize, boolean overwrite); @Override long getSize(); @Override boolean exists(); @Override void delete(); @Override Blob moveTo(URI blobId, Map<String, String> hints); static final String FORCE_MOVE_AS_COPY_AND_DELETE; }### Answer: @Test public void testExistsFalse() throws Exception { assertFalse(getFSBlob("file:nonExistingPath").exists()); assertFalse(getFSBlob("file:nonExistingPath/nonExistingPath").exists()); }
### Question: FSBlob extends AbstractBlob { @Override public URI getCanonicalId() { return canonicalId; } FSBlob(FSBlobStoreConnection connection, File baseDir, URI blobId, StreamManager manager, Set<File> modified); @Override URI getCanonicalId(); @Override InputStream openInputStream(); @Override OutputStream openOutputStream(long estimatedSize, boolean overwrite); @Override long getSize(); @Override boolean exists(); @Override void delete(); @Override Blob moveTo(URI blobId, Map<String, String> hints); static final String FORCE_MOVE_AS_COPY_AND_DELETE; }### Answer: @Test public void testGetCanonicalId() { assertCanonical("file:foo"); assertCanonical("file:foo/bar"); assertCanonical("file:6a/1b/1e/info%3Afoo%2Fbar.baz%2E"); assertCanonical("file:..."); assertCanonical("file:.../foo"); assertCanonical("file:foo/..."); assertCanonical("file:foo/.../bar"); assertCanonical("file:foo/../bar", "file:bar"); assertCanonical("file:foo/bar/../../baz", "file:baz"); assertCanonical("file:foo/../bar/../qux", "file:qux"); assertCanonical("file:./foo", "file:foo"); assertCanonical("file:foo/./bar", "file:foo/bar"); assertCanonical("file:foo/bar/././baz", "file:foo/bar/baz"); assertCanonical("file:foo/./bar/./qux", "file:foo/bar/qux"); assertCanonical("FILE:foo", "file:foo"); assertCanonical("file:foo assertCanonical("file:foo }
### Question: WWWBlob extends AbstractBlob { public WWWBlob(URL url, BlobStoreConnection conn, StreamManager streamManager) { super(conn, toURI(url)); this.url = url; this.streamManager = streamManager; } WWWBlob(URL url, BlobStoreConnection conn, StreamManager streamManager); @Override long getSize(); @Override InputStream openInputStream(); @Override OutputStream openOutputStream(long estimatedSize, boolean overwrite); @Override boolean exists(); @Override void delete(); @Override Blob moveTo(URI blobId, Map<String, String> hints); }### Answer: @Test public void testWWWBlob() { try { assertEquals(blob, con.getBlob(blobId, null)); } catch (IOException e) { fail("getBlob() failed", e); } }
### Question: ClientIterator implements Iterator<T> { public boolean hasNext() { return load().hasNext(); } ClientIterator(RemoteIterator<T> ri, int batchSize); boolean hasNext(); T next(); void remove(); }### Answer: @Test public void testHasNext() { assertTrue(ci.hasNext()); assertTrue(ci.hasNext()); for (String v : source) { assertTrue(ci.hasNext()); assertEquals(v, ci.next()); } assertFalse(ci.hasNext()); assertFalse(ci.hasNext()); }
### Question: GlucoseFeatureDataCallback extends ProfileReadResponse implements GlucoseFeatureCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 2) { onInvalidDataReceived(device, data); return; } final int value = data.getIntValue(Data.FORMAT_UINT16, 0); final GlucoseFeatures features = new GlucoseFeatures(value); onGlucoseFeaturesReceived(device, features); } GlucoseFeatureDataCallback(); protected GlucoseFeatureDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onGlucoseFeaturesReceived() { final Data data = new Data(new byte[] { (byte) 0b11110000, (byte) 0b00000011 }); callback.onDataReceived(null, data); assertTrue(success); assertFalse(result.lowBatteryDetectionSupported); assertFalse(result.sensorMalfunctionDetectionSupported); assertFalse(result.sensorSampleSizeSupported); assertFalse(result.sensorStripInsertionErrorDetectionSupported); assertTrue(result.sensorStripTypeErrorDetectionSupported); assertTrue(result.sensorResultHighLowSupported); assertTrue(result.sensorTempHighLowDetectionSupported); assertTrue(result.sensorReadInterruptDetectionSupported); assertTrue(result.generalDeviceFaultSupported); assertTrue(result.timeFaultSupported); assertFalse(result.multipleBondSupported); } @Test public void onInvalidDataReceived() { final Data data = new Data(); callback.onDataReceived(null, data); assertTrue(invalidData); }
### Question: SensorLocationDataCallback extends ProfileReadResponse implements SensorLocationCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 1) { onInvalidDataReceived(device, data); return; } final int location = data.getIntValue(Data.FORMAT_UINT8, 0); onSensorLocationReceived(device, location); } SensorLocationDataCallback(); protected SensorLocationDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onSensorLocationReceived() { final ProfileReadResponse callback = new SensorLocationDataCallback() { @Override public void onSensorLocationReceived(@NonNull final BluetoothDevice device, final int location) { called = true; assertEquals("Location", SensorLocationCallback.SENSOR_LOCATION_REAR_WHEEL, location); } }; called = false; final Data data = new Data(new byte[] { 12 }); callback.onDataReceived(null, data); assertTrue(called); assertTrue(callback.isValid()); } @Test public void onInvalidDataReceived() { final ProfileReadResponse callback = new SensorLocationDataCallback() { @Override public void onSensorLocationReceived(@NonNull final BluetoothDevice device, final int location) { called = true; } }; called = false; final Data data = new Data(new byte[] { 0x01, 0x02 }); callback.onDataReceived(null, data); assertFalse(called); assertFalse(callback.isValid()); }
### Question: CRC16 { public static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0x1D0F, data, offset, length, false, false, 0x0000); } private CRC16(); static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length); static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length); static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length); static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length); static int ARC(@NonNull final byte[] data, final int offset, final int length); static int MAXIM(@NonNull final byte[] data, final int offset, final int length); static int CRC(final int poly, final int init, @NonNull final byte[] data, final int offset, final int length, final boolean refin, final boolean refout, final int xorout); }### Answer: @Test public void AUG_CCITT_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0x9479, CRC16.AUG_CCITT(data, 0, 1)); } @Test public void AUG_CCITT_123456789() { final byte[] data = "123456789".getBytes(); assertEquals(0xE5CC, CRC16.AUG_CCITT(data, 0, 9)); } @Test public void AUG_CCITT_empty() { final byte[] data = new byte[0]; assertEquals(0x1D0F, CRC16.AUG_CCITT(data, 0, 0)); }
### Question: BodySensorLocationDataCallback extends ProfileReadResponse implements BodySensorLocationCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 1) { onInvalidDataReceived(device, data); return; } final int sensorLocation = data.getIntValue(Data.FORMAT_UINT8, 0); onBodySensorLocationReceived(device, sensorLocation); } BodySensorLocationDataCallback(); protected BodySensorLocationDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onBodySensorLocationReceived() { success = false; final Data data = new Data(new byte[] { BodySensorLocationCallback.SENSOR_LOCATION_EAR_LOBE }); response.onDataReceived(null, data); assertTrue(response.isValid()); assertTrue(success); assertEquals(BodySensorLocationCallback.SENSOR_LOCATION_EAR_LOBE, sensorLocation); } @Test public void onInvalidDataReceived() { success = false; final Data data = new Data(); response.onDataReceived(null, data); assertFalse(response.isValid()); assertFalse(success); }
### Question: CRC16 { public static int ARC(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x8005, 0x0000, data, offset, length, true, true, 0x0000); } private CRC16(); static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length); static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length); static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length); static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length); static int ARC(@NonNull final byte[] data, final int offset, final int length); static int MAXIM(@NonNull final byte[] data, final int offset, final int length); static int CRC(final int poly, final int init, @NonNull final byte[] data, final int offset, final int length, final boolean refin, final boolean refout, final int xorout); }### Answer: @Test public void ARC_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0x30C0, CRC16.ARC(data, 0, 1)); } @Test public void ARC_123456789() { final byte[] data = "123456789".getBytes(); assertEquals(0xBB3D, CRC16.ARC(data, 0, 9)); } @Test public void ARC_empty() { final byte[] data = new byte[0]; assertEquals(0x0000, CRC16.ARC(data, 0, 0)); }
### Question: DataStream { @SuppressWarnings("SimplifiableIfStatement") public boolean write(@Nullable final byte[] data) { if (data == null) return false; return write(data, 0, data.length); } DataStream(); @SuppressWarnings("SimplifiableIfStatement") boolean write(@Nullable final byte[] data); boolean write(@Nullable final byte[] data, @IntRange(from = 0) final int offset, @IntRange(from = 0) final int length); boolean write(@Nullable final Data data); @IntRange(from = 0) int size(); @NonNull byte[] toByteArray(); @NonNull Data toData(); }### Answer: @Test public void write() { final DataStream stream = new DataStream(); stream.write(new byte[] { 0, 1, 2, 3}); stream.write(new byte[] { 4, 5, 6}); assertArrayEquals(new byte[] { 0, 1, 2, 3, 4, 5, 6}, stream.toByteArray()); }
### Question: DataStream { @IntRange(from = 0) public int size() { return buffer.size(); } DataStream(); @SuppressWarnings("SimplifiableIfStatement") boolean write(@Nullable final byte[] data); boolean write(@Nullable final byte[] data, @IntRange(from = 0) final int offset, @IntRange(from = 0) final int length); boolean write(@Nullable final Data data); @IntRange(from = 0) int size(); @NonNull byte[] toByteArray(); @NonNull Data toData(); }### Answer: @Test public void size() { final DataStream stream = new DataStream(); stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6}); assertEquals(7, stream.size()); }
### Question: DataStream { @NonNull public Data toData() { return new Data(buffer.toByteArray()); } DataStream(); @SuppressWarnings("SimplifiableIfStatement") boolean write(@Nullable final byte[] data); boolean write(@Nullable final byte[] data, @IntRange(from = 0) final int offset, @IntRange(from = 0) final int length); boolean write(@Nullable final Data data); @IntRange(from = 0) int size(); @NonNull byte[] toByteArray(); @NonNull Data toData(); }### Answer: @SuppressWarnings("ConstantConditions") @Test public void toData() { final DataStream stream = new DataStream(); stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6}); final Data data = stream.toData(); assertEquals(0x100, data.getIntValue(Data.FORMAT_UINT16, 0).intValue()); }
### Question: DefaultMtuSplitter implements DataSplitter { @Nullable @Override public byte[] chunk(@NonNull final byte[] message, @IntRange(from = 0) final int index, @IntRange(from = 20) final int maxLength) { final int offset = index * maxLength; final int length = Math.min(maxLength, message.length - offset); if (length <= 0) return null; final byte[] data = new byte[length]; System.arraycopy(message, offset, data, 0, length); return data; } @Nullable @Override byte[] chunk(@NonNull final byte[] message, @IntRange(from = 0) final int index, @IntRange(from = 20) final int maxLength); }### Answer: @Test public void chunk_23() { final int MTU = 23; final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); final byte[] result = splitter.chunk(text.getBytes(), 1, MTU - 3); assertArrayEquals(text.substring(MTU - 3, 2 * (MTU - 3)).getBytes(), result); } @Test public void chunk_43() { final int MTU = 43; final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); final byte[] result = splitter.chunk(text.getBytes(), 2, MTU - 3); assertArrayEquals(text.substring(2 * (MTU - 3), 3 * (MTU - 3)).getBytes(), result); } @Test public void chunk_end() { final int MTU = 23; final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); final byte[] result = splitter.chunk(text.getBytes(), 200, MTU - 3); assertNull(result); }
### Question: CRC16 { public static int MAXIM(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x8005, 0x0000, data, offset, length, true, true, 0xFFFF); } private CRC16(); static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length); static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length); static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length); static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length); static int ARC(@NonNull final byte[] data, final int offset, final int length); static int MAXIM(@NonNull final byte[] data, final int offset, final int length); static int CRC(final int poly, final int init, @NonNull final byte[] data, final int offset, final int length, final boolean refin, final boolean refout, final int xorout); }### Answer: @Test public void MAXIM_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0xCF3F, CRC16.MAXIM(data, 0, 1)); } @Test public void MAXIM_123456789() { final byte[] data = "123456789".getBytes(); assertEquals(0x44C2, CRC16.MAXIM(data, 0, 9)); } @Test public void MAXIM_empty() { final byte[] data = new byte[0]; assertEquals(0xFFFF, CRC16.MAXIM(data, 0, 0)); }
### Question: TimeZoneDataCallback extends ProfileReadResponse implements TimeZoneCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); final Integer offset = readTimeZone(data, 0); if (offset == null) { onInvalidDataReceived(device, data); return; } if (offset == -128) { onUnknownTimeZoneReceived(device); } else if (offset < -48 || offset > 56) { onInvalidDataReceived(device, data); } else { onTimeZoneReceived(device, offset * 15); } } TimeZoneDataCallback(); protected TimeZoneDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); @Nullable static Integer readTimeZone(@NonNull final Data data, final int offset); }### Answer: @Test public void onTimeZoneReceived_basic() { final Data data = new Data(new byte[] { 1 }); callback.onDataReceived(null, data); assertTrue(success); assertEquals(15, result); } @Test public void onTimeZoneReceived_unknown() { final Data data = new Data(new byte[] { -128 }); callback.onDataReceived(null, data); assertTrue(unknownTimeZone); } @Test public void onTimeZoneReceived_invalid() { final Data data = new Data(new byte[] { 60 }); callback.onDataReceived(null, data); assertTrue(invalidData); }
### Question: CRC16 { public static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0xFFFF, data, offset, length, false, false, 0x0000); } private CRC16(); static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length); static int CCITT_FALSE(@NonNull final byte[] data, final int offset, final int length); static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length); static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length); static int ARC(@NonNull final byte[] data, final int offset, final int length); static int MAXIM(@NonNull final byte[] data, final int offset, final int length); static int CRC(final int poly, final int init, @NonNull final byte[] data, final int offset, final int length, final boolean refin, final boolean refout, final int xorout); }### Answer: @Test public void CCITT_FALSE_A() { final byte[] data = new byte[] { 'A' }; assertEquals(0xB915, CRC16.CCITT_FALSE(data, 0, 1)); } @Test public void CCITT_FALSE_123456789() { final byte[] data = "123456789".getBytes(); assertEquals(0x29B1, CRC16.CCITT_FALSE(data, 0, 9)); } @Test public void CCITT_FALSE_A_offset() { final byte[] data = "1234567A89".getBytes(); assertEquals(0xB915, CRC16.CCITT_FALSE(data, 7, 1)); } @Test public void CCITT_FALSE_empty() { final byte[] data = new byte[0]; assertEquals(0xFFFF, CRC16.CCITT_FALSE(data, 0, 0)); }
### Question: MeasurementIntervalDataCallback extends ProfileReadResponse implements MeasurementIntervalCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 2) { onInvalidDataReceived(device, data); return; } final int interval = data.getIntValue(Data.FORMAT_UINT16, 0); onMeasurementIntervalReceived(device, interval); } MeasurementIntervalDataCallback(); protected MeasurementIntervalDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onMeasurementIntervalReceived() { final ProfileReadResponse response = new MeasurementIntervalDataCallback() { @Override public void onMeasurementIntervalReceived(@NonNull final BluetoothDevice device, final int interval) { called = true; assertEquals("Interval", 60, interval); } }; called = false; final Data data = new Data(new byte[] { 60, 0 }); response.onDataReceived(null, data); assertTrue(response.isValid()); assertTrue(called); } @Test public void onInvalidDataReceived() { final ProfileReadResponse response = new MeasurementIntervalDataCallback() { @Override public void onMeasurementIntervalReceived(@NonNull final BluetoothDevice device, final int interval) { called = true; } }; called = false; final Data data = new Data(new byte[] { 60 }); response.onDataReceived(null, data); assertFalse(called); assertFalse(response.isValid()); }
### Question: TemperatureTypeDataCallback extends ProfileReadResponse implements TemperatureTypeCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 1) { onInvalidDataReceived(device, data); return; } final int type = data.getIntValue(Data.FORMAT_UINT8, 0); onTemperatureTypeReceived(device, type); } TemperatureTypeDataCallback(); protected TemperatureTypeDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onMeasurementIntervalReceived() { final ProfileReadResponse response = new TemperatureTypeDataCallback() { @Override public void onTemperatureTypeReceived(@NonNull final BluetoothDevice device, final int type) { called = true; assertEquals("Temperature Type", HealthThermometerTypes.TYPE_EAR, type); } }; called = false; final Data data = new Data(new byte[] { 3 }); response.onDataReceived(null, data); assertTrue(response.isValid()); assertTrue(called); } @Test public void onInvalidDataReceived() { final ProfileReadResponse response = new TemperatureTypeDataCallback() { @Override public void onTemperatureTypeReceived(@NonNull final BluetoothDevice device, final int type) { called = true; } }; called = false; final Data data = new Data(new byte[] { 3, 0 }); response.onDataReceived(null, data); assertFalse(called); assertFalse(response.isValid()); }
### Question: CyclingSpeedAndCadenceFeatureDataCallback extends ProfileReadResponse implements CyclingSpeedAndCadenceFeatureCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 2) { onInvalidDataReceived(device, data); return; } final int value = data.getIntValue(Data.FORMAT_UINT16, 0); final CSCFeatures features = new CSCFeatures(value); onCyclingSpeedAndCadenceFeaturesReceived(device, features); } CyclingSpeedAndCadenceFeatureDataCallback(); protected CyclingSpeedAndCadenceFeatureDataCallback(final Parcel in); @Override void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); }### Answer: @Test public void onCyclingSpeedAndCadenceFeaturesReceived() { final ProfileReadResponse callback = new CyclingSpeedAndCadenceFeatureDataCallback() { @Override public void onCyclingSpeedAndCadenceFeaturesReceived(@NonNull final BluetoothDevice device, @NonNull final CSCFeatures features) { called = true; assertNotNull(features); assertTrue("Wheel revolutions supported", features.wheelRevolutionDataSupported); assertTrue("Crank revolutions supported", features.crankRevolutionDataSupported); assertFalse("Multiple sensors not supported", features.multipleSensorDataSupported); assertEquals("Feature value", 0x03, features.value); } }; called = false; final Data data = new Data(new byte[] { 0x03, 0x00 }); callback.onDataReceived(null, data); assertTrue(called); assertTrue(callback.isValid()); } @Test public void onInvalidDataReceived() { final ProfileReadResponse callback = new CyclingSpeedAndCadenceFeatureDataCallback() { @Override public void onCyclingSpeedAndCadenceFeaturesReceived(@NonNull final BluetoothDevice device, @NonNull final CSCFeatures features) { called = true; } }; called = false; final Data data = new Data(new byte[] { 0x03 }); callback.onDataReceived(null, data); assertFalse(called); assertFalse(callback.isValid()); }
### Question: BitUtilLittle extends BitUtil { @Override public byte[] fromBitString(String str) { int strLen = str.length(); int bLen = str.length() / 8; if (strLen % 8 != 0) bLen++; byte[] bytes = new byte[bLen]; int charI = 0; for (int b = bLen - 1; b >= 0; b--) { byte res = 0; for (int i = 0; i < 8; i++) { res <<= 1; if (charI < strLen && str.charAt(charI) != '0') res |= 1; charI++; } bytes[b] = res; } return bytes; } BitUtilLittle(); @Override final short toShort(byte[] b, int offset); @Override final int toInt(byte[] b, int offset); @Override void fromShort(byte[] bytes, short value, int offset); @Override final void fromInt(byte[] bytes, int value, int offset); @Override final long toLong(int int0, int int1); @Override final long toLong(byte[] b, int offset); @Override final void fromLong(byte[] bytes, long value, int offset); @Override byte[] fromBitString(String str); @Override String toBitString(byte[] bytes); @Override String toString(); }### Answer: @Test public void testFromBitString() { String str = "001110110"; assertEquals(str + "0000000", bitUtil.toBitString(bitUtil.fromBitString(str))); str = "01011110010111000000111111000111"; assertEquals(str, bitUtil.toBitString(bitUtil.fromBitString(str))); str = "0101111001011100000011111100011"; assertEquals(str + "0", bitUtil.toBitString(bitUtil.fromBitString(str))); }
### Question: SimpleIntDeque { public void push(int v) { if (endIndexPlusOne >= arr.length) { arr = Arrays.copyOf(arr, (int) (arr.length * growFactor)); } arr[endIndexPlusOne] = v; endIndexPlusOne++; } SimpleIntDeque(); SimpleIntDeque(int initSize); SimpleIntDeque(int initSize, float growFactor); void setGrowFactor(float factor); boolean isEmpty(); int pop(); int getSize(); void push(int v); @Override String toString(); }### Answer: @Test public void testPush() { SimpleIntDeque deque = new SimpleIntDeque(8, 2f); for (int i = 0; i < 60; i++) { deque.push(i); assertEquals(i + 1, deque.getSize()); } assertEquals(60, deque.getSize()); assertEquals(0, deque.pop()); assertEquals(59, deque.getSize()); assertEquals(1, deque.pop()); assertEquals(58, deque.getSize()); deque.push(2); assertEquals(59, deque.getSize()); deque.push(3); assertEquals(60, deque.getSize()); for (int i = 0; i < 50; i++) { assertEquals(i + 2, deque.pop()); } assertEquals(10, deque.getSize()); assertEquals(39, deque.getCapacity()); deque.push(123); assertEquals(11, deque.getSize()); assertEquals(52, deque.pop()); assertEquals(10, deque.getSize()); }
### Question: PMap { public String get(String key, String _default) { String str = get(key); if (Helper.isEmpty(str)) return _default; return str; } PMap(); PMap(int capacity); PMap(Map<String, String> map); PMap(PMap map); PMap(String propertiesString); PMap put(PMap map); PMap put(String key, Object str); PMap remove(String key); boolean has(String key); long getLong(String key, long _default); int getInt(String key, int _default); boolean getBool(String key, boolean _default); double getDouble(String key, double _default); String get(String key, String _default); Map<String, String> toMap(); PMap merge(PMap read); boolean isEmpty(); @Override String toString(); }### Answer: @Test public void singleStringPropertyCanBeRetrieved() { PMap subject = new PMap("foo=bar"); Assert.assertEquals("bar", subject.get("foo")); } @Test public void propertyFromStringWithMultiplePropertiesCanBeRetrieved() { PMap subject = new PMap("foo=valueA|bar=valueB"); Assert.assertEquals("valueA", subject.get("foo", "")); Assert.assertEquals("valueB", subject.get("bar", "")); } @Test public void keyCannotHaveAnyCasing() { PMap subject = new PMap("foo=valueA|bar=valueB"); assertEquals("valueA", subject.get("foo", "")); assertEquals("", subject.get("Foo", "")); }
### Question: PMap { public long getLong(String key, long _default) { String str = get(key); if (!Helper.isEmpty(str)) { try { return Long.parseLong(str); } catch (Exception ex) { } } return _default; } PMap(); PMap(int capacity); PMap(Map<String, String> map); PMap(PMap map); PMap(String propertiesString); PMap put(PMap map); PMap put(String key, Object str); PMap remove(String key); boolean has(String key); long getLong(String key, long _default); int getInt(String key, int _default); boolean getBool(String key, boolean _default); double getDouble(String key, double _default); String get(String key, String _default); Map<String, String> toMap(); PMap merge(PMap read); boolean isEmpty(); @Override String toString(); }### Answer: @Test public void numericPropertyCanBeRetrievedAsLong() { PMap subject = new PMap("foo=1234|bar=5678"); assertEquals(1234L, subject.getLong("foo", 0)); }
### Question: PMap { public double getDouble(String key, double _default) { String str = get(key); if (!Helper.isEmpty(str)) { try { return Double.parseDouble(str); } catch (Exception ex) { } } return _default; } PMap(); PMap(int capacity); PMap(Map<String, String> map); PMap(PMap map); PMap(String propertiesString); PMap put(PMap map); PMap put(String key, Object str); PMap remove(String key); boolean has(String key); long getLong(String key, long _default); int getInt(String key, int _default); boolean getBool(String key, boolean _default); double getDouble(String key, double _default); String get(String key, String _default); Map<String, String> toMap(); PMap merge(PMap read); boolean isEmpty(); @Override String toString(); }### Answer: @Test public void numericPropertyCanBeRetrievedAsDouble() { PMap subject = new PMap("foo=123.45|bar=56.78"); assertEquals(123.45, subject.getDouble("foo", 0), 1e-4); }
### Question: PMap { public boolean has(String key) { return map.containsKey(Helper.camelCaseToUnderScore(key)); } PMap(); PMap(int capacity); PMap(Map<String, String> map); PMap(PMap map); PMap(String propertiesString); PMap put(PMap map); PMap put(String key, Object str); PMap remove(String key); boolean has(String key); long getLong(String key, long _default); int getInt(String key, int _default); boolean getBool(String key, boolean _default); double getDouble(String key, double _default); String get(String key, String _default); Map<String, String> toMap(); PMap merge(PMap read); boolean isEmpty(); @Override String toString(); }### Answer: @Test public void hasReturnsCorrectResult() { PMap subject = new PMap("foo=123.45|bar=56.78"); assertTrue(subject.has("foo")); assertTrue(subject.has("bar")); assertFalse(subject.has("baz")); }
### Question: TranslationMap { public Translation get(String locale) { locale = locale.replace("-", "_"); Translation tr = translations.get(locale); if (locale.contains("_") && tr == null) tr = translations.get(locale.substring(0, 2)); return tr; } static int countOccurence(String phrase, String splitter); TranslationMap doImport(File folder); TranslationMap doImport(); void add(Translation tr); Translation getWithFallBack(Locale locale); Translation get(String locale); @Override String toString(); }### Answer: @Test public void testToRoundaboutString() { Translation ptMap = SINGLETON.get("pt"); assertTrue(ptMap.tr("roundabout_exit_onto", "1", "somestreet").contains("somestreet")); }
### Question: BitUtilBig extends BitUtil { @Override public byte[] fromBitString(String str) { int strLen = str.length(); int bLen = str.length() / 8; if (strLen % 8 != 0) bLen++; byte[] bytes = new byte[bLen]; int charI = 0; for (int b = 0; b < bLen; b++) { byte res = 0; for (int i = 0; i < 8; i++) { res <<= 1; if (charI < strLen && str.charAt(charI) != '0') res |= 1; charI++; } bytes[b] = res; } return bytes; } BitUtilBig(); @Override final short toShort(byte[] b, int offset); @Override final int toInt(byte[] b, int offset); @Override void fromShort(byte[] bytes, short value, int offset); @Override final void fromInt(byte[] bytes, int value, int offset); @Override final long toLong(int int0, int int1); @Override final long toLong(byte[] b, int offset); @Override final void fromLong(byte[] bytes, long value, int offset); @Override byte[] fromBitString(String str); @Override String toBitString(byte[] bytes); @Override String toString(); }### Answer: @Test public void testFromBitString() { String str = "011011100"; assertEquals(str + "0000000", bitUtil.toBitString(bitUtil.fromBitString(str))); str = "01011110010111000000111111000111"; assertEquals(str, bitUtil.toBitString(bitUtil.fromBitString(str))); str = "0101111001011100000011111100011"; assertEquals(str + "0", bitUtil.toBitString(bitUtil.fromBitString(str))); }
### Question: BBox implements Shape, Cloneable { @Override public GHPoint getCenter() { return new GHPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2); } @JsonCreator BBox(double[] coords); BBox(double minLon, double maxLon, double minLat, double maxLat); BBox(double minLon, double maxLon, double minLat, double maxLat, double minEle, double maxEle); BBox(double minLon, double maxLon, double minLat, double maxLat, double minEle, double maxEle, boolean elevation); static BBox createInverse(boolean elevation); boolean hasElevation(); void update(double lat, double lon); void update(double lat, double lon, double elev); BBox calculateIntersection(BBox bBox); @Override BBox clone(); @Override boolean intersect(Shape s); @Override boolean contains(Shape s); boolean intersect(Circle s); boolean intersect(BBox o); @Override boolean contains(double lat, double lon); boolean contains(BBox b); boolean contains(Circle c); @Override String toString(); String toLessPrecisionString(); @Override BBox getBounds(); @Override GHPoint getCenter(); @Override boolean equals(Object obj); @Override int hashCode(); boolean isValid(); List<Double> toGeoJson(); @Override double calculateArea(); static BBox parseTwoPoints(String objectAsString); static BBox parseBBoxString(String objectAsString); public double minLon; public double maxLon; public double minLat; public double maxLat; public double minEle; public double maxEle; }### Answer: @Test public void testGetCenter() { BBox bBox = new BBox(0, 2, 0, 2); GHPoint center = bBox.getCenter(); assertEquals(1, center.getLat(), .00001); assertEquals(1, center.getLon(), .00001); }
### Question: GHPoint3D extends GHPoint { @Override public boolean equals(Object obj) { if (obj == null) return false; @SuppressWarnings("unchecked") final GHPoint3D other = (GHPoint3D) obj; if (Double.isNaN(ele)) return NumHelper.equalsEps(lat, other.lat) && NumHelper.equalsEps(lon, other.lon); else return NumHelper.equalsEps(lat, other.lat) && NumHelper.equalsEps(lon, other.lon) && NumHelper.equalsEps(ele, other.ele); } GHPoint3D(double lat, double lon, double elevation); double getElevation(); double getEle(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override Double[] toGeoJson(); public double ele; }### Answer: @Test public void testEquals() { GHPoint3D point1 = new GHPoint3D(1, 2, Double.NaN); GHPoint3D point2 = new GHPoint3D(1, 2, Double.NaN); assertEquals(point1, point2); point1 = new GHPoint3D(1, 2, 0); point2 = new GHPoint3D(1, 2, 1); assertNotEquals(point1, point2); point1 = new GHPoint3D(1, 2, 0); point2 = new GHPoint3D(1, 2.1, 0); assertNotEquals(point1, point2); point1 = new GHPoint3D(1, 2.1, 0); point2 = new GHPoint3D(1, 2.1, 0); assertEquals(point1, point2); }
### Question: GHPoint { public boolean isValid() { return !Double.isNaN(lat) && !Double.isNaN(lon); } GHPoint(); GHPoint(double lat, double lon); static GHPoint parse(String str); static GHPoint parseLonLat(String str); double getLon(); double getLat(); boolean isValid(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Double[] toGeoJson(); static GHPoint from(Point point); public double lat; public double lon; }### Answer: @Test public void testIsValid() { GHPoint instance = new GHPoint(); assertFalse(instance.isValid()); instance.lat = 1; assertFalse(instance.isValid()); instance.lon = 1; assertTrue(instance.isValid()); }
### Question: Circle implements Shape { @Override public boolean intersect(Shape o) { if (o instanceof Circle) { return intersect((Circle) o); } else if (o instanceof BBox) { return intersect((BBox) o); } return o.intersect(this); } Circle(double lat, double lon, double radiusInMeter); Circle(double lat, double lon, double radiusInMeter, DistanceCalc calc); double getLat(); double getLon(); @Override boolean contains(double lat1, double lon1); @Override BBox getBounds(); @Override GHPoint getCenter(); @Override boolean intersect(Shape o); @Override boolean contains(Shape o); boolean intersect(BBox b); boolean intersect(Circle c); boolean contains(BBox b); boolean contains(Circle c); @Override double calculateArea(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testIntersectCircleCircle() { assertTrue(new Circle(0, 0, 80000).intersect(new Circle(1, 1, 80000))); assertFalse(new Circle(0, 0, 75000).intersect(new Circle(1, 1, 80000))); } @Test public void testIntersectCircleBBox() { assertTrue(new Circle(10, 10, 120000).intersect(new BBox(9, 11, 8, 9))); assertTrue(new BBox(9, 11, 8, 9).intersect(new Circle(10, 10, 120000))); assertFalse(new Circle(10, 10, 110000).intersect(new BBox(9, 11, 8, 9))); assertFalse(new BBox(9, 11, 8, 9).intersect(new Circle(10, 10, 110000))); }
### Question: Circle implements Shape { @Override public boolean contains(double lat1, double lon1) { return normDist(lat1, lon1) <= normedDist; } Circle(double lat, double lon, double radiusInMeter); Circle(double lat, double lon, double radiusInMeter, DistanceCalc calc); double getLat(); double getLon(); @Override boolean contains(double lat1, double lon1); @Override BBox getBounds(); @Override GHPoint getCenter(); @Override boolean intersect(Shape o); @Override boolean contains(Shape o); boolean intersect(BBox b); boolean intersect(Circle c); boolean contains(BBox b); boolean contains(Circle c); @Override double calculateArea(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testContains() { Circle c = new Circle(10, 10, 120000); assertTrue(c.contains(new BBox(9, 11, 10, 10.1))); assertFalse(c.contains(new BBox(9, 11, 8, 9))); assertFalse(c.contains(new BBox(9, 12, 10, 10.1))); } @Test public void testContainsCircle() { Circle c = new Circle(10, 10, 120000); assertTrue(c.contains(new Circle(9.9, 10.2, 90000))); assertFalse(c.contains(new Circle(10, 10.4, 90000))); }
### Question: Circle implements Shape { @Override public GHPoint getCenter() { return new GHPoint(lat, lon); } Circle(double lat, double lon, double radiusInMeter); Circle(double lat, double lon, double radiusInMeter, DistanceCalc calc); double getLat(); double getLon(); @Override boolean contains(double lat1, double lon1); @Override BBox getBounds(); @Override GHPoint getCenter(); @Override boolean intersect(Shape o); @Override boolean contains(Shape o); boolean intersect(BBox b); boolean intersect(Circle c); boolean contains(BBox b); boolean contains(Circle c); @Override double calculateArea(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testGetCenter() { Circle c = new Circle(10, 10, 10); GHPoint center = c.getCenter(); assertEquals(10, center.getLat(), .00001); assertEquals(10, center.getLon(), .00001); }
### Question: GHResponse { @Override public String toString() { String str = ""; for (PathWrapper a : pathWrappers) { str += "; " + a.toString(); } if (pathWrappers.isEmpty()) str = "no paths"; if (!errors.isEmpty()) str += ", main errors: " + errors.toString(); return str; } GHResponse(); void add(PathWrapper altResponse); PathWrapper getBest(); List<PathWrapper> getAll(); boolean hasAlternatives(); void addDebugInfo(String debugInfo); String getDebugInfo(); boolean hasErrors(); List<Throwable> getErrors(); GHResponse addErrors(List<Throwable> errors); GHResponse addError(Throwable error); @Override String toString(); PMap getHints(); }### Answer: @Test public void testToString() throws Exception { assertEquals("no paths", new GHResponse().toString()); }
### Question: GHRequest { public HintsMap getHints() { return hints; } GHRequest(); GHRequest(int size); GHRequest(double fromLat, double fromLon, double toLat, double toLon, double startHeading, double endHeading); GHRequest(double fromLat, double fromLon, double toLat, double toLon); GHRequest(GHPoint startPlace, GHPoint endPlace, double startHeading, double endHeading); GHRequest(GHPoint startPlace, GHPoint endPlace); GHRequest(List<GHPoint> points, List<Double> favoredHeadings); GHRequest(List<GHPoint> points); GHRequest addPoint(GHPoint point, double favoredHeading); GHRequest addPoint(GHPoint point); double getFavoredHeading(int i); boolean hasFavoredHeading(int i); List<GHPoint> getPoints(); String getAlgorithm(); GHRequest setAlgorithm(String algo); Locale getLocale(); GHRequest setLocale(Locale locale); GHRequest setLocale(String localeStr); String getWeighting(); GHRequest setWeighting(String w); String getVehicle(); GHRequest setVehicle(String vehicle); HintsMap getHints(); GHRequest setPointHints(List<String> pointHints); List<String> getPointHints(); boolean hasPointHints(); GHRequest setPathDetails(List<String> pathDetails); List<String> getPathDetails(); @Override String toString(); }### Answer: @Test public void testGetHint() { GHRequest instance = new GHRequest(10, 12, 12, 10); instance.getHints().put("something", "1"); assertEquals(1, instance.getHints().getInt("something", 2)); assertEquals(1, instance.getHints().getDouble("something", 2d), 1e1); }
### Question: ConditionalOSMTagInspector implements ConditionalTagInspector { @Override public boolean isRestrictedWayConditionallyPermitted(ReaderWay way) { return applies(way, true); } ConditionalOSMTagInspector(Object value, List<String> tagsToCheck, Set<String> restrictiveValues, Set<String> permittedValues); ConditionalOSMTagInspector(List<String> tagsToCheck, List<? extends ConditionalValueParser> valueParsers, Set<String> restrictiveValues, Set<String> permittedValues, boolean enabledLogs); void addValueParser(ConditionalValueParser vp); @Override boolean isRestrictedWayConditionallyPermitted(ReaderWay way); @Override boolean isPermittedWayConditionallyRestricted(ReaderWay way); }### Answer: @Test public void testConditionalAllowance() { Calendar cal = getCalendar(2014, Calendar.MARCH, 10); ConditionalTagInspector acceptor = new ConditionalOSMTagInspector(cal, getSampleConditionalTags(), getSampleRestrictedValues(), getSamplePermissiveValues()); ReaderWay way = new ReaderWay(1); way.setTag("vehicle:conditional", "yes @ (Mar 10-Aug 14)"); assertTrue(acceptor.isRestrictedWayConditionallyPermitted(way)); } @Test public void testConditionalAllowanceSingleDay() { Calendar cal = getCalendar(2015, Calendar.DECEMBER, 27); ConditionalTagInspector acceptor = new ConditionalOSMTagInspector(cal, getSampleConditionalTags(), getSampleRestrictedValues(), getSamplePermissiveValues()); ReaderWay way = new ReaderWay(1); way.setTag("vehicle:conditional", "yes @ (Su)"); assertTrue(acceptor.isRestrictedWayConditionallyPermitted(way)); }
### Question: ConditionalParser { protected static double parseNumber(String str) { int untilIndex = str.length() - 1; for (; untilIndex >= 0; untilIndex--) { if (Character.isDigit(str.charAt(untilIndex))) break; } return Double.parseDouble(str.substring(0, untilIndex + 1)); } ConditionalParser(Set<String> restrictedTags); ConditionalParser(Set<String> restrictedTags, boolean enabledLogs); static ConditionalValueParser createNumberParser(final String assertKey, final Number obj); ConditionalParser addConditionalValueParser(ConditionalValueParser vp); ConditionalParser setConditionalValueParser(ConditionalValueParser vp); boolean checkCondition(String conditionalTag); }### Answer: @Test public void parseNumber() { assertEquals(3, ConditionalParser.parseNumber("3t"), .1); assertEquals(3.1, ConditionalParser.parseNumber("3.1 t"), .1); assertEquals(3, ConditionalParser.parseNumber("3 meters"), .1); }
### Question: CGIARProvider implements ElevationProvider { int down(double val) { int intVal = (int) (val / degree) * degree; if (!(val >= 0 || intVal - val < invPrecision)) intVal = intVal - degree; return intVal; } static void main(String[] args); @Override void setCalcMean(boolean eleCalcMean); void setAutoRemoveTemporaryFiles(boolean autoRemoveTemporary); void setDownloader(Downloader downloader); @Override ElevationProvider setCacheDir(File cacheDir); @Override ElevationProvider setBaseURL(String baseUrl); @Override ElevationProvider setDAType(DAType daType); @Override double getEle(double lat, double lon); @Override void release(); @Override String toString(); }### Answer: @Test public void testDown() { assertEquals(50, instance.down(52.5)); assertEquals(0, instance.down(0.1)); assertEquals(0, instance.down(0.01)); assertEquals(-5, instance.down(-0.01)); assertEquals(-5, instance.down(-2)); assertEquals(-10, instance.down(-5.1)); assertEquals(50, instance.down(50)); assertEquals(45, instance.down(49)); }
### Question: LinearKeyAlgo implements KeyAlgo { @Override public long encode(GHPoint coord) { return encode(coord.lat, coord.lon); } LinearKeyAlgo(int latUnits, int lonUnits); @Override LinearKeyAlgo setBounds(double minLonInit, double maxLonInit, double minLatInit, double maxLatInit); LinearKeyAlgo setBounds(BBox bounds); @Override long encode(GHPoint coord); @Override final long encode(double lat, double lon); @Override final void decode(long linearKey, GHPoint latLon); double getLatDelta(); double getLonDelta(); }### Answer: @Test public void testEncode() { KeyAlgo algo = new LinearKeyAlgo(3, 4).setBounds(-1, 9, -2, 20); assertEquals(2L, algo.encode(-1, 5)); assertEquals(11L, algo.encode(14, 7)); assertEquals(5L, algo.encode(8, 4)); assertEquals(1L, algo.encode(-4, 3)); assertEquals(3L, algo.encode(2, 22)); assertEquals(0L, algo.encode(-4, -4)); assertEquals(11L, algo.encode(22, 22)); }
### Question: LinearKeyAlgo implements KeyAlgo { @Override public final void decode(long linearKey, GHPoint latLon) { double lat = linearKey / lonUnits * latDelta + bounds.minLat; double lon = linearKey % lonUnits * lonDelta + bounds.minLon; latLon.lat = lat + latDelta / 2; latLon.lon = lon + lonDelta / 2; } LinearKeyAlgo(int latUnits, int lonUnits); @Override LinearKeyAlgo setBounds(double minLonInit, double maxLonInit, double minLatInit, double maxLatInit); LinearKeyAlgo setBounds(BBox bounds); @Override long encode(GHPoint coord); @Override final long encode(double lat, double lon); @Override final void decode(long linearKey, GHPoint latLon); double getLatDelta(); double getLonDelta(); }### Answer: @Test public void testDecode() { KeyAlgo algo = new LinearKeyAlgo(3, 4).setBounds(-1, 9, -2, 20); GHPoint latLon = new GHPoint(); algo.decode(5, latLon); assertEquals(9, latLon.lat, 1e-7); assertEquals(2.75, latLon.lon, 1e-7); algo.decode(2, latLon); assertEquals(1.66666666, latLon.lat, 1e-7); assertEquals(5.25, latLon.lon, 1e-7); algo.decode(11, latLon); assertEquals(16.3333333, latLon.lat, 1e-7); assertEquals(7.75, latLon.lon, 1e-7); algo.decode(10, latLon); assertEquals(16.3333333, latLon.lat, 1e-7); assertEquals(5.25, latLon.lon, 1e-7); }
### Question: SpatialKeyAlgo implements KeyAlgo { @Override public long encode(GHPoint coord) { return encode(coord.lat, coord.lon); } SpatialKeyAlgo(int allBits); int getBits(); int getExactPrecision(); SpatialKeyAlgo bounds(BBox box); @Override SpatialKeyAlgo setBounds(double minLonInit, double maxLonInit, double minLatInit, double maxLatInit); @Override long encode(GHPoint coord); @Override final long encode(double lat, double lon); @Override final void decode(long spatialKey, GHPoint latLon); @Override String toString(); }### Answer: @Test public void testEncode() { SpatialKeyAlgo algo = new SpatialKeyAlgo(32); long val = algo.encode(-24.235345f, 47.234234f); assertEquals("01100110101000111100000110010100", BitUtil.BIG.toLastBitString(val, 32)); }
### Question: NameIndex implements Storable<NameIndex> { public long put(String name) { if (name == null || name.isEmpty()) { return 0; } if (name.equals(lastName)) { return lastIndex; } byte[] bytes = getBytes(name); long oldPointer = bytePointer; names.ensureCapacity(bytePointer + 1 + bytes.length); byte[] sizeBytes = new byte[]{ (byte) bytes.length }; names.setBytes(bytePointer, sizeBytes, sizeBytes.length); bytePointer++; names.setBytes(bytePointer, bytes, bytes.length); bytePointer += bytes.length; lastName = name; lastIndex = oldPointer; return oldPointer; } NameIndex(Directory dir); @Override NameIndex create(long initBytes); @Override boolean loadExisting(); long put(String name); String get(long pointer); @Override void flush(); @Override void close(); @Override boolean isClosed(); void setSegmentSize(int segments); @Override long getCapacity(); void copyTo(NameIndex nameIndex); }### Answer: @Test public void testPut() { NameIndex index = new NameIndex(new RAMDirectory()).create(1000); long result = index.put("Something Streetä"); assertEquals("Something Streetä", index.get(result)); long existing = index.put("Something Streetä"); assertEquals(result, existing); result = index.put("testing"); assertEquals("testing", index.get(result)); assertEquals(0, index.put("")); assertEquals(0, index.put(null)); assertEquals("", index.get(0)); index.close(); }
### Question: NameIndex implements Storable<NameIndex> { @Override public NameIndex create(long initBytes) { names.create(initBytes); return this; } NameIndex(Directory dir); @Override NameIndex create(long initBytes); @Override boolean loadExisting(); long put(String name); String get(long pointer); @Override void flush(); @Override void close(); @Override boolean isClosed(); void setSegmentSize(int segments); @Override long getCapacity(); void copyTo(NameIndex nameIndex); }### Answer: @Test public void testCreate() { NameIndex index = new NameIndex(new RAMDirectory()).create(1000); String str1 = "nice"; long pointer1 = index.put(str1); String str2 = "nice work äöß"; long pointer2 = index.put(str2); assertEquals(str2, index.get(pointer2)); assertEquals(str1, index.get(pointer1)); index.close(); }
### Question: NameIndex implements Storable<NameIndex> { @Override public void flush() { names.setHeader(0, BitUtil.LITTLE.getIntLow(bytePointer)); names.setHeader(4, BitUtil.LITTLE.getIntHigh(bytePointer)); names.flush(); } NameIndex(Directory dir); @Override NameIndex create(long initBytes); @Override boolean loadExisting(); long put(String name); String get(long pointer); @Override void flush(); @Override void close(); @Override boolean isClosed(); void setSegmentSize(int segments); @Override long getCapacity(); void copyTo(NameIndex nameIndex); }### Answer: @Test public void testFlush() { String location = "./target/nameindex-store"; Helper.removeDir(new File(location)); NameIndex index = new NameIndex(new RAMDirectory(location, true).create()).create(1000); long pointer = index.put("test"); index.flush(); index.close(); index = new NameIndex(new RAMDirectory(location, true)); assertTrue(index.loadExisting()); assertEquals("test", index.get(pointer)); long newPointer = index.put("testing"); assertEquals(newPointer + ">" + pointer, pointer + "test".getBytes().length + 1, newPointer); index.close(); Helper.removeDir(new File(location)); }
### Question: GHLongIntBTree implements LongIntMap { @Override public int put(long key, int value) { if (key == noNumberValue) { throw new IllegalArgumentException("Illegal key " + key); } ReturnValue rv = root.put(key, value); if (rv.tree != null) { height++; root = rv.tree; } if (rv.oldValue == noNumberValue) { size++; if (size % 1000000 == 0) optimize(); } return rv.oldValue; } GHLongIntBTree(int maxLeafEntries); @Override int put(long key, int value); @Override int get(long key); @Override long getSize(); @Override int getMemoryUsage(); @Override void optimize(); @Override String toString(); }### Answer: @Test public void testThrowException_IfPutting_NoNumber() { GHLongIntBTree instance = new GHLongIntBTree(2); try { instance.put(-1, 1); assertTrue(false); } catch (Exception ex) { } } @Test public void testPut() { GHLongIntBTree instance = new GHLongIntBTree(3); instance.put(2, 4); instance.put(7, 14); instance.put(5, 10); instance.put(6, 12); instance.put(3, 6); instance.put(4, 8); instance.put(9, 18); instance.put(0, 0); instance.put(1, 2); instance.put(8, 16); check(instance, 0); instance.put(10, 20); instance.put(11, 22); assertEquals(12, instance.getSize()); assertEquals(3, instance.height()); assertEquals(12, instance.get(6)); check(instance, 0); }
### Question: GHTreeMapComposed { public void insert(int key, int value) { long v = bitUtil.toLong(value, key); map.put(v, NOT_EMPTY); } GHTreeMapComposed(); void clear(); void update(int key, int oldValue, int value); void insert(int key, int value); int peekValue(); int peekKey(); int pollKey(); int getSize(); boolean isEmpty(); @Override String toString(); }### Answer: @Test public void testInsert() { GHTreeMapComposed instance = new GHTreeMapComposed(); instance.insert(1, 100); assertEquals(1, instance.peekKey()); assertEquals(100, instance.peekValue()); instance.insert(2, 99); instance.insert(3, 101); assertEquals(2, instance.peekKey()); assertEquals(99, instance.peekValue()); assertEquals(2, instance.pollKey()); }
### Question: OSMIDMap implements LongIntMap { @Override public int get(long key) { long retIndex = binarySearch(keys, 0, getSize(), key); if (retIndex < 0) return noEntryValue; return values.getInt(retIndex * 4); } OSMIDMap(Directory dir); OSMIDMap(Directory dir, int noNumber); void remove(); @Override int put(long key, int value); @Override int get(long key); @Override long getSize(); long getCapacity(); @Override int getMemoryUsage(); @Override void optimize(); }### Answer: @Test public void testGet() { OSMIDMap map = new OSMIDMap(new RAMDirectory()); map.put(9, 0); map.put(10, -50); map.put(11, 2); map.put(12, 3); map.put(20, 6); map.put(21, 5); map.put(31, 2); assertEquals(7, map.getSize()); assertEquals(-1, map.get(8)); assertEquals(0, map.get(9)); assertEquals(-50, map.get(10)); assertEquals(2, map.get(11)); assertEquals(3, map.get(12)); assertEquals(-1, map.get(13)); assertEquals(-1, map.get(19)); assertEquals(6, map.get(20)); assertEquals(5, map.get(21)); assertEquals(2, map.get(31)); assertEquals(-1, map.get(32)); for (int i = 0; i < 50; i++) { map.put(i + 50, i + 7); } assertEquals(57, map.getSize()); }
### Question: GHSortedCollection { public void insert(int key, int value) { GHIntHashSet set = map.get(value); if (set == null) { map.put(value, set = new GHIntHashSet(slidingMeanValue)); } if (!set.add(key)) { throw new IllegalStateException("use update if you want to update " + key); } size++; } GHSortedCollection(); void clear(); void update(int key, int oldValue, int value); void insert(int key, int value); int peekValue(); int peekKey(); int pollKey(); int getSize(); boolean isEmpty(); int getSlidingMeanValue(); @Override String toString(); }### Answer: @Test public void testInsert() { GHSortedCollection instance = new GHSortedCollection(); assertTrue(instance.isEmpty()); instance.insert(0, 10); assertEquals(1, instance.getSize()); assertEquals(10, instance.peekValue()); assertEquals(0, instance.peekKey()); instance.update(0, 10, 2); assertEquals(2, instance.peekValue()); assertEquals(1, instance.getSize()); instance.insert(0, 11); assertEquals(2, instance.peekValue()); assertEquals(2, instance.getSize()); instance.insert(1, 0); assertEquals(0, instance.peekValue()); assertEquals(3, instance.getSize()); }
### Question: GHSortedCollection { public void update(int key, int oldValue, int value) { remove(key, oldValue); insert(key, value); } GHSortedCollection(); void clear(); void update(int key, int oldValue, int value); void insert(int key, int value); int peekValue(); int peekKey(); int pollKey(); int getSize(); boolean isEmpty(); int getSlidingMeanValue(); @Override String toString(); }### Answer: @Test public void testUpdate() { GHSortedCollection instance = new GHSortedCollection(); assertTrue(instance.isEmpty()); instance.insert(0, 10); instance.insert(1, 11); assertEquals(10, instance.peekValue()); assertEquals(2, instance.getSize()); instance.update(0, 10, 12); assertEquals(11, instance.peekValue()); assertEquals(2, instance.getSize()); }
### Question: GHIntArrayList extends IntArrayList { public final GHIntArrayList reverse() { final int[] buffer = this.buffer; int tmp; for (int start = 0, end = size() - 1; start < end; start++, end--) { tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; } GHIntArrayList(); GHIntArrayList(int capacity); GHIntArrayList(GHIntArrayList list); final GHIntArrayList reverse(); final GHIntArrayList fill(final int max, final int value); final GHIntArrayList shuffle(Random random); static GHIntArrayList from(int... elements); }### Answer: @Test public void testReverse() { assertEquals(GHIntArrayList.from(4, 3, 2, 1), GHIntArrayList.from(1, 2, 3, 4).reverse()); assertEquals(GHIntArrayList.from(5, 4, 3, 2, 1), GHIntArrayList.from(1, 2, 3, 4, 5).reverse()); }
### Question: GHIntArrayList extends IntArrayList { public final GHIntArrayList shuffle(Random random) { int[] buffer = this.buffer; int max = size(); int maxHalf = max / 2; for (int x1 = 0; x1 < maxHalf; x1++) { int x2 = random.nextInt(maxHalf) + maxHalf; int tmp = buffer[x1]; buffer[x1] = buffer[x2]; buffer[x2] = tmp; } return this; } GHIntArrayList(); GHIntArrayList(int capacity); GHIntArrayList(GHIntArrayList list); final GHIntArrayList reverse(); final GHIntArrayList fill(final int max, final int value); final GHIntArrayList shuffle(Random random); static GHIntArrayList from(int... elements); }### Answer: @Test public void testShuffle() { assertEquals(GHIntArrayList.from(4, 1, 3, 2), GHIntArrayList.from(1, 2, 3, 4).shuffle(new Random(0))); assertEquals(GHIntArrayList.from(4, 3, 2, 1, 5), GHIntArrayList.from(1, 2, 3, 4, 5).shuffle(new Random(1))); }
### Question: GHIntArrayList extends IntArrayList { public final GHIntArrayList fill(final int max, final int value) { for (int i = 0; i < max; i++) { add(value); } return this; } GHIntArrayList(); GHIntArrayList(int capacity); GHIntArrayList(GHIntArrayList list); final GHIntArrayList reverse(); final GHIntArrayList fill(final int max, final int value); final GHIntArrayList shuffle(Random random); static GHIntArrayList from(int... elements); }### Answer: @Test public void testFill() { assertEquals(GHIntArrayList.from(-1, -1, -1, -1), new GHIntArrayList(4).fill(4, -1)); }
### Question: CompressedArray { public static byte[] compress(byte[] value, int offset, int length, int compressionLevel) { ByteArrayOutputStream bos = new ByteArrayOutputStream(length); Deflater compressor = new Deflater(); try { compressor.setLevel(compressionLevel); compressor.setInput(value, offset, length); compressor.finish(); final byte[] buf = new byte[1024]; while (!compressor.finished()) { int count = compressor.deflate(buf); bos.write(buf, 0, count); } } finally { compressor.end(); } return bos.toByteArray(); } CompressedArray(); CompressedArray(int _segments, int entriesPerSeg, int approxBytesPerEntry); static byte[] compress(byte[] value, int offset, int length, int compressionLevel); static byte[] decompress(byte[] value); CompressedArray setCompressionLevel(int compressionLevel); void write(double lat, double lon); GHPoint get(long index); void flush(); float calcMemInMB(); }### Answer: @Test public void testCompress() throws Exception { CompressedArray arr = new CompressedArray(); arr.write(10, 1); arr.write(11, 2); arr.write(12, 3); arr.flush(); GHPoint coord = arr.get(0); assertEquals(10, coord.lat, 1e-6); assertEquals(1, coord.lon, 1e-6); coord = arr.get(1); assertEquals(11, coord.lat, 1e-6); assertEquals(2, coord.lon, 1e-6); coord = arr.get(2); assertEquals(12, coord.lat, 1e-6); assertEquals(3, coord.lon, 1e-6); assertNull(arr.get(3)); }
### Question: OSMReader implements DataReader { @Override public String toString() { return getClass().getSimpleName(); } OSMReader(GraphHopperStorage ghStorage); @Override void readGraph(); void processRelation(ReaderRelation relation); Collection<TurnCostTableEntry> analyzeTurnRelation(OSMTurnRelation turnRelation); Collection<TurnCostTableEntry> analyzeTurnRelation(FlagEncoder encoder, OSMTurnRelation turnRelation); long getOsmIdOfInternalEdge(int edgeId); int getInternalNodeIdOfOsmNode(long nodeOsmId); @Override OSMReader setWayPointMaxDistance(double maxDist); @Override OSMReader setWorkerThreads(int numOfWorkers); @Override OSMReader setElevationProvider(ElevationProvider eleProvider); @Override DataReader setFile(File osmFile); @Override Date getDataDate(); void setDontCreateStorage(boolean dontCreateStorage); @Override String toString(); }### Answer: @Test public void testRoutingRequestFails_issue665() { GraphHopper hopper = new GraphHopperOSM() .setDataReaderFile(getClass().getResource(file7).getFile()) .setEncodingManager(new EncodingManager("car,motorcycle")) .setGraphHopperLocation(dir); hopper.getCHFactoryDecorator().setEnabled(false); hopper.importOrLoad(); GHRequest req = new GHRequest(48.977277, 8.256896, 48.978876, 8.254884). setWeighting("curvature"). setVehicle("motorcycle"); GHResponse ghRsp = hopper.route(req); assertFalse(ghRsp.getErrors().toString(), ghRsp.hasErrors()); }
### Question: WebHelper { public static String encodePolyline(PointList poly) { if (poly.isEmpty()) return ""; return encodePolyline(poly, poly.is3D()); } static String encodeURL(String str); static PointList decodePolyline(String encoded, int initCap, boolean is3D); static String encodePolyline(PointList poly); static String encodePolyline(PointList poly, boolean includeElevation); static String readString(InputStream inputStream); }### Answer: @Test public void testEncode() throws Exception { assertEquals("_p~iF~ps|U", WebHelper.encodePolyline( Helper.createPointList(38.5, -120.2))); assertEquals("_p~iF~ps|U_ulLnnqC_mqNvxq`@", WebHelper.encodePolyline( Helper.createPointList(38.5, -120.2, 40.7, -120.95, 43.252, -126.453))); } @Test public void testEncode3D() throws Exception { assertEquals("_p~iF~ps|Uo}@", WebHelper.encodePolyline(Helper.createPointList3D(38.5, -120.2, 10))); assertEquals("_p~iF~ps|Uo}@_ulLnnqC_anF_mqNvxq`@?", WebHelper.encodePolyline( Helper.createPointList3D(38.5, -120.2, 10, 40.7, -120.95, 1234, 43.252, -126.453, 1234))); }
### Question: EncodingManager { public boolean supports(String encoder) { return getEncoder(encoder, false) != null; } EncodingManager(String flagEncodersStr); EncodingManager(String flagEncodersStr, int bytesForEdgeFlags); EncodingManager(FlagEncoderFactory factory, String flagEncodersStr, int bytesForEdgeFlags); EncodingManager(FlagEncoder... flagEncoders); EncodingManager(List<? extends FlagEncoder> flagEncoders); EncodingManager(List<? extends FlagEncoder> flagEncoders, int bytesForEdgeFlags); static EncodingManager create(FlagEncoderFactory factory, String ghLoc); int getBytesForFlags(); boolean supports(String encoder); FlagEncoder getEncoder(String name); long acceptWay(ReaderWay way); long handleRelationTags(ReaderRelation relation, long oldRelationFlags); long handleWayTags(ReaderWay way, long includeWay, long relationFlags); @Override String toString(); String toDetailsString(); long flagsDefault(boolean forward, boolean backward); long reverseFlags(long flags); @Override int hashCode(); @Override boolean equals(Object obj); long handleNodeTags(ReaderNode node); EncodingManager setEnableInstructions(boolean enableInstructions); EncodingManager setPreferredLanguage(String preferredLanguage); void applyWayTags(ReaderWay way, EdgeIteratorState edge); List<FlagEncoder> fetchEdgeEncoders(); boolean needsTurnCostsSupport(); }### Answer: @Test public void testEncoderAcceptNoException() { EncodingManager manager = new EncodingManager("car"); assertTrue(manager.supports("car")); assertFalse(manager.supports("foot")); }
### Question: EncodingManager { static String fixWayName(String str) { if (str == null) return ""; return str.replaceAll(";[ ]*", ", "); } EncodingManager(String flagEncodersStr); EncodingManager(String flagEncodersStr, int bytesForEdgeFlags); EncodingManager(FlagEncoderFactory factory, String flagEncodersStr, int bytesForEdgeFlags); EncodingManager(FlagEncoder... flagEncoders); EncodingManager(List<? extends FlagEncoder> flagEncoders); EncodingManager(List<? extends FlagEncoder> flagEncoders, int bytesForEdgeFlags); static EncodingManager create(FlagEncoderFactory factory, String ghLoc); int getBytesForFlags(); boolean supports(String encoder); FlagEncoder getEncoder(String name); long acceptWay(ReaderWay way); long handleRelationTags(ReaderRelation relation, long oldRelationFlags); long handleWayTags(ReaderWay way, long includeWay, long relationFlags); @Override String toString(); String toDetailsString(); long flagsDefault(boolean forward, boolean backward); long reverseFlags(long flags); @Override int hashCode(); @Override boolean equals(Object obj); long handleNodeTags(ReaderNode node); EncodingManager setEnableInstructions(boolean enableInstructions); EncodingManager setPreferredLanguage(String preferredLanguage); void applyWayTags(ReaderWay way, EdgeIteratorState edge); List<FlagEncoder> fetchEdgeEncoders(); boolean needsTurnCostsSupport(); }### Answer: @Test public void testFixWayName() { assertEquals("B8, B12", EncodingManager.fixWayName("B8;B12")); assertEquals("B8, B12", EncodingManager.fixWayName("B8; B12")); }
### Question: CarFlagEncoder extends AbstractFlagEncoder { protected double getSpeed(ReaderWay way) { String highwayValue = way.getTag("highway"); if (!Helper.isEmpty(highwayValue) && way.hasTag("motorroad", "yes") && highwayValue != "motorway" && highwayValue != "motorway_link") { highwayValue = "motorroad"; } Integer speed = defaultSpeedMap.get(highwayValue); if (speed == null) throw new IllegalStateException(toString() + ", no speed found for: " + highwayValue + ", tags: " + way); if (highwayValue.equals("track")) { String tt = way.getTag("tracktype"); if (!Helper.isEmpty(tt)) { Integer tInt = trackTypeSpeedMap.get(tt); if (tInt != null) speed = tInt; } } return speed; } CarFlagEncoder(); CarFlagEncoder(PMap properties); CarFlagEncoder(String propertiesStr); CarFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts); @Override int getVersion(); @Override int defineWayBits(int index, int shift); @Override long acceptWay(ReaderWay way); @Override long handleRelationTags(ReaderRelation relation, long oldRelationFlags); @Override long handleWayTags(ReaderWay way, long allowed, long relationFlags); String getWayInfo(ReaderWay way); @Override String toString(); }### Answer: @Test public void testSetSpeed() { assertEquals(10, encoder.getSpeed(encoder.setSpeed(0, 10)), 1e-1); } @Test public void testSetSpeed0_issue367() { long flags = encoder.setProperties(10, true, true); flags = encoder.setSpeed(flags, encoder.speedFactor * 0.49); assertEquals(0, encoder.getSpeed(flags), .1); assertEquals(0, encoder.getReverseSpeed(flags), .1); assertFalse(encoder.isForward(flags)); assertFalse(encoder.isBackward(flags)); }
### Question: CarFlagEncoder extends AbstractFlagEncoder { protected double applyBadSurfaceSpeed(ReaderWay way, double speed) { if (badSurfaceSpeed > 0 && speed > badSurfaceSpeed && way.hasTag("surface", badSurfaceSpeedMap)) speed = badSurfaceSpeed; return speed; } CarFlagEncoder(); CarFlagEncoder(PMap properties); CarFlagEncoder(String propertiesStr); CarFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts); @Override int getVersion(); @Override int defineWayBits(int index, int shift); @Override long acceptWay(ReaderWay way); @Override long handleRelationTags(ReaderRelation relation, long oldRelationFlags); @Override long handleWayTags(ReaderWay way, long allowed, long relationFlags); String getWayInfo(ReaderWay way); @Override String toString(); }### Answer: @Test public void testApplyBadSurfaceSpeed() { ReaderWay way = new ReaderWay(1); way.setTag("highway", "secondary"); way.setTag("surface", "unpaved"); assertEquals(30, encoder.applyBadSurfaceSpeed(way, 90), 1e-1); }
### Question: EncodedDoubleValue extends EncodedValue { public long setDoubleValue(long flags, double value) { if (Double.isNaN(value)) throw new IllegalArgumentException("Value cannot be NaN"); long tmpValue = Math.round(value / factor); checkValue((long) (tmpValue * factor)); tmpValue <<= shift; flags &= ~mask; return flags | tmpValue; } EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue); EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero); @Override long setValue(long flags, long value); @Override long getValue(long flags); @Override long setDefaultValue(long flags); long setDoubleValue(long flags, double value); double getDoubleValue(long flags); }### Answer: @Test public void testSetDoubleValue() { EncodedDoubleValue instance = new EncodedDoubleValue("test", 6, 10, 0.01, 5, 10); assertEquals(10.12, instance.getDoubleValue(instance.setDoubleValue(0, 10.12)), 1e-4); }
### Question: EncodedDoubleValue extends EncodedValue { public double getDoubleValue(long flags) { flags &= mask; flags >>>= shift; return flags * factor; } EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue); EncodedDoubleValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero); @Override long setValue(long flags, long value); @Override long getValue(long flags); @Override long setDefaultValue(long flags); long setDoubleValue(long flags, double value); double getDoubleValue(long flags); }### Answer: @Test public void testUnsignedRightShift_issue417() { EncodedDoubleValue speedEncoder = new EncodedDoubleValue("Speed", 56, 8, 1, 30, 255); Long flags = -72057594037927936L; assertEquals(255, speedEncoder.getDoubleValue(flags), 0.01); }
### Question: PrepareContractionHierarchies extends AbstractAlgoPreparation implements RoutingAlgorithmFactory { @Override public void doWork() { if (prepareWeighting == null) throw new IllegalStateException("No weight calculation set."); allSW.start(); super.doWork(); initFromGraph(); if (!prepareNodes()) return; contractNodes(); } PrepareContractionHierarchies(Directory dir, GraphHopperStorage ghStorage, CHGraph chGraph, Weighting weighting, TraversalMode traversalMode); PrepareContractionHierarchies setPeriodicUpdates(int periodicUpdates); PrepareContractionHierarchies setLazyUpdates(int lazyUpdates); PrepareContractionHierarchies setNeighborUpdates(int neighborUpdates); PrepareContractionHierarchies setLogMessages(double logMessages); PrepareContractionHierarchies setContractedNodes(double nodesContracted); @Override void doWork(); long getDijkstraCount(); double getLazyTime(); double getPeriodTime(); double getDijkstraTime(); double getNeighborTime(); Weighting getWeighting(); void close(); int getShortcuts(); @Override RoutingAlgorithm createAlgo(Graph graph, AlgorithmOptions opts); @Override String toString(); }### Answer: @Test public void testMoreComplexGraph() { GraphHopperStorage g = createGHStorage(); CHGraph lg = g.getGraph(CHGraph.class); initShortcutsGraph(lg); int oldCount = g.getAllEdges().getMaxId(); PrepareContractionHierarchies prepare = new PrepareContractionHierarchies(dir, g, lg, weighting, tMode); prepare.doWork(); assertEquals(oldCount, g.getAllEdges().getMaxId()); assertEquals(oldCount + 7, lg.getAllEdges().getMaxId()); }
### Question: EncodedValue { public long setValue(long flags, long value) { value = Math.round(value / factor); checkValue((long) (value * factor)); value <<= shift; flags &= ~mask; return flags | value; } EncodedValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue); EncodedValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero); long setValue(long flags, long value); String getName(); long getValue(long flags); int getBits(); double getFactor(); long setDefaultValue(long flags); long getMaxValue(); long swap(long flags, EncodedValue otherEncoder); }### Answer: @Test public void testSetValue() { EncodedValue instance = new EncodedValue("test", 6, 4, 1, 5, 10); assertEquals(10, instance.getValue(instance.setValue(0, 10))); instance = new EncodedValue("test", 0, 4, 1, 5, 10); assertEquals(10, instance.getValue(instance.setValue(0, 10))); instance = new EncodedValue("test", 0, 4, 1, 5, 10); assertEquals(5, instance.getValue(instance.setDefaultValue(0))); }
### Question: PrepareRoutingSubnetworks { int removeDeadEndUnvisitedNetworks(final PrepEdgeFilter bothFilter) { StopWatch sw = new StopWatch(bothFilter.getEncoder() + " findComponents").start(); final EdgeFilter outFilter = new DefaultEdgeFilter(bothFilter.getEncoder(), false, true); TarjansSCCAlgorithm tarjan = new TarjansSCCAlgorithm(ghStorage, outFilter, true); List<IntArrayList> components = tarjan.findComponents(); logger.info(sw.stop() + ", size:" + components.size()); return removeEdges(bothFilter, components, minOneWayNetworkSize); } PrepareRoutingSubnetworks(GraphHopperStorage ghStorage, List<FlagEncoder> encoders); PrepareRoutingSubnetworks setMinNetworkSize(int minNetworkSize); PrepareRoutingSubnetworks setMinOneWayNetworkSize(int minOnewayNetworkSize); void doWork(); int getMaxSubnetworks(); }### Answer: @Test public void testRemoveDeadEndUnvisitedNetworks() { GraphHopperStorage g = createDeadEndUnvisitedNetworkStorage(em); assertEquals(11, g.getNodes()); PrepareRoutingSubnetworks instance = new PrepareRoutingSubnetworks(g, Collections.singletonList(carFlagEncoder)). setMinOneWayNetworkSize(3); int removed = instance.removeDeadEndUnvisitedNetworks(new PrepEdgeFilter(carFlagEncoder)); assertEquals(3, removed); instance.markNodesRemovedIfUnreachable(); g.optimize(); assertEquals(8, g.getNodes()); }
### Question: GenericWeighting extends AbstractWeighting { @Override public long calcMillis(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId) { double speed = weightingConfig.getSpeed(edgeState); if (speed == 0) return Long.MAX_VALUE; double maxspeed = gEncoder.getMaxspeed(edgeState, accessType, reverse); if (maxspeed > 0 && speed > maxspeed) speed = maxspeed; long timeInMillis = (long) (edgeState.getDistance() / speed * SPEED_CONV); boolean unfavoredEdge = edgeState.getBool(EdgeIteratorState.K_UNFAVORED_EDGE, false); if (unfavoredEdge) timeInMillis += headingPenaltyMillis; if (timeInMillis < 0) throw new IllegalStateException("Some problem with weight calculation: time:" + timeInMillis + ", speed:" + speed); return timeInMillis; } GenericWeighting(DataFlagEncoder encoder, PMap hintsMap); @Override double getMinWeight(double distance); @Override double calcWeight(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId); @Override long calcMillis(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId); @Override String getName(); static final String HEIGHT_LIMIT; static final String WEIGHT_LIMIT; static final String WIDTH_LIMIT; }### Answer: @Test public void testCalcTime() { GenericWeighting weighting = new GenericWeighting(encoder, new HintsMap()); EdgeIteratorState edge = graph.getEdgeIteratorState(0, 1); assertEquals(edgeWeight, weighting.calcMillis(edge, false, EdgeIterator.NO_EDGE), .1); }
### Question: EncodedValue { public long swap(long flags, EncodedValue otherEncoder) { long otherValue = otherEncoder.getValue(flags); flags = otherEncoder.setValue(flags, getValue(flags)); return setValue(flags, otherValue); } EncodedValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue); EncodedValue(String name, int shift, int bits, double factor, long defaultValue, int maxValue, boolean allowZero); long setValue(long flags, long value); String getName(); long getValue(long flags); int getBits(); double getFactor(); long setDefaultValue(long flags); long getMaxValue(); long swap(long flags, EncodedValue otherEncoder); }### Answer: @Test public void testSwap() { EncodedValue instance1 = new EncodedValue("test1", 0, 10, 1, 5, 1000); EncodedValue instance2 = new EncodedValue("test2", 10, 10, 1, 5, 1000); long flags = instance2.setValue(instance1.setValue(0, 13), 874); long swappedFlags = instance1.setValue(instance2.setValue(0, 13), 874); assertEquals(swappedFlags, instance1.swap(flags, instance2)); }
### Question: AbstractWeighting implements Weighting { @Override public String toString() { return getName() + "|" + flagEncoder; } protected AbstractWeighting(FlagEncoder encoder); @Override long calcMillis(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId); @Override boolean matches(HintsMap reqMap); @Override FlagEncoder getFlagEncoder(); @Override int hashCode(); @Override boolean equals(Object obj); static String weightingToFileName(Weighting w); @Override String toString(); }### Answer: @Test public void testToString() { assertTrue(AbstractWeighting.isValidName("blup")); assertTrue(AbstractWeighting.isValidName("blup_a")); assertTrue(AbstractWeighting.isValidName("blup|a")); assertFalse(AbstractWeighting.isValidName("Blup")); assertFalse(AbstractWeighting.isValidName("Blup!")); }
### Question: InstructionList extends AbstractList<Instruction> { static String simpleXMLEscape(String str) { return str.replaceAll("&", "&amp;"). replaceAll("[\\<\\>]", "_"); } InstructionList(Translation tr); InstructionList(int cap, Translation tr); @Override int size(); @Override Instruction get(int index); @Override Instruction set(int index, Instruction element); @Override void add(int index, Instruction element); @Override Instruction remove(int index); void replaceLast(Instruction instr); @JsonValue List<Map<String, Object>> createJson(); List<GPXEntry> createGPXList(); String createGPX(); String createGPX(String trackName, long startTimeMillis); String createGPX(String trackName, long startTimeMillis, boolean includeElevation, boolean withRoute, boolean withTrack, boolean withWayPoints); void createRteptBlock(StringBuilder output, Instruction instruction, Instruction nextI); Instruction find(double lat, double lon, double maxDistance); }### Answer: @Test public void testXMLEscape_issue572() { assertEquals("_", InstructionList.simpleXMLEscape("<")); assertEquals("_blup_", InstructionList.simpleXMLEscape("<blup>")); assertEquals("a&amp;b", InstructionList.simpleXMLEscape("a&b")); }
### Question: AngleCalc { public double alignOrientation(double baseOrientation, double orientation) { double resultOrientation; if (baseOrientation >= 0) { if (orientation < -Math.PI + baseOrientation) resultOrientation = orientation + 2 * Math.PI; else resultOrientation = orientation; } else if (orientation > +Math.PI + baseOrientation) resultOrientation = orientation - 2 * Math.PI; else resultOrientation = orientation; return resultOrientation; } double calcOrientation(double lat1, double lon1, double lat2, double lon2); double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact); double convertAzimuth2xaxisAngle(double azimuth); double alignOrientation(double baseOrientation, double orientation); double calcAzimuth(double lat1, double lon1, double lat2, double lon2); }### Answer: @Test public void testAlignOrientation() { assertEquals(90.0, Math.toDegrees(AC.alignOrientation(Math.toRadians(90), Math.toRadians(90))), 0.001); assertEquals(225.0, Math.toDegrees(AC.alignOrientation(Math.toRadians(90), Math.toRadians(-135))), 0.001); assertEquals(-45.0, Math.toDegrees(AC.alignOrientation(Math.toRadians(-135), Math.toRadians(-45))), 0.001); assertEquals(-270.0, Math.toDegrees(AC.alignOrientation(Math.toRadians(-135), Math.toRadians(90))), 0.001); }
### Question: AngleCalc { public double calcAzimuth(double lat1, double lon1, double lat2, double lon2) { double orientation = Math.PI / 2 - calcOrientation(lat1, lon1, lat2, lon2); if (orientation < 0) orientation += 2 * Math.PI; return Math.toDegrees(Helper.round4(orientation))%360; } double calcOrientation(double lat1, double lon1, double lat2, double lon2); double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact); double convertAzimuth2xaxisAngle(double azimuth); double alignOrientation(double baseOrientation, double orientation); double calcAzimuth(double lat1, double lon1, double lat2, double lon2); }### Answer: @Test public void testCalcAzimuth() { assertEquals(45.0, AC.calcAzimuth(0, 0, 1, 1), 0.001); assertEquals(90.0, AC.calcAzimuth(0, 0, 0, 1), 0.001); assertEquals(180.0, AC.calcAzimuth(0, 0, -1, 0), 0.001); assertEquals(270.0, AC.calcAzimuth(0, 0, 0, -1), 0.001); assertEquals(0.0, AC.calcAzimuth(49.942, 11.580, 49.944, 11.580), 0.001); }
### Question: AngleCalc { String azimuth2compassPoint(double azimuth) { String cp; double slice = 360.0 / 16; if (azimuth < slice) { cp = "N"; } else if (azimuth < slice * 3) { cp = "NE"; } else if (azimuth < slice * 5) { cp = "E"; } else if (azimuth < slice * 7) { cp = "SE"; } else if (azimuth < slice * 9) { cp = "S"; } else if (azimuth < slice * 11) { cp = "SW"; } else if (azimuth < slice * 13) { cp = "W"; } else if (azimuth < slice * 15) { cp = "NW"; } else { cp = "N"; } return cp; } double calcOrientation(double lat1, double lon1, double lat2, double lon2); double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact); double convertAzimuth2xaxisAngle(double azimuth); double alignOrientation(double baseOrientation, double orientation); double calcAzimuth(double lat1, double lon1, double lat2, double lon2); }### Answer: @Test public void testAzimuthCompassPoint() { assertEquals("S", AC.azimuth2compassPoint(199)); }
### Question: AngleCalc { static final double atan2(double y, double x) { double absY = Math.abs(y) + 1e-10; double r, angle; if (x < 0.0) { r = (x + absY) / (absY - x); angle = PI3_4; } else { r = (x - absY) / (x + absY); angle = PI_4; } angle += (0.1963 * r * r - 0.9817) * r; if (y < 0.0) return -angle; return angle; } double calcOrientation(double lat1, double lon1, double lat2, double lon2); double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact); double convertAzimuth2xaxisAngle(double azimuth); double alignOrientation(double baseOrientation, double orientation); double calcAzimuth(double lat1, double lon1, double lat2, double lon2); }### Answer: @Test public void testAtan2() { assertEquals(45, AngleCalc.atan2(5, 5) * 180 / Math.PI, 1e-2); assertEquals(-45, AngleCalc.atan2(-5, 5) * 180 / Math.PI, 1e-2); assertEquals(11.14, AngleCalc.atan2(1, 5) * 180 / Math.PI, 1); assertEquals(180, AngleCalc.atan2(0, -5) * 180 / Math.PI, 1e-2); assertEquals(-90, AngleCalc.atan2(-5, 0) * 180 / Math.PI, 1e-2); assertEquals(90, Math.atan2(1, 0) * 180 / Math.PI, 1e-2); assertEquals(90, AngleCalc.atan2(1, 0) * 180 / Math.PI, 1e-2); }
### Question: AngleCalc { public double convertAzimuth2xaxisAngle(double azimuth) { if (Double.compare(azimuth, 360) > 0 || Double.compare(azimuth, 0) < 0) { throw new IllegalArgumentException("Azimuth " + azimuth + " must be in (0, 360)"); } double angleXY = PI_2 - azimuth / 180. * Math.PI; if (angleXY < -Math.PI) angleXY += 2 * Math.PI; if (angleXY > Math.PI) angleXY -= 2 * Math.PI; return angleXY; } double calcOrientation(double lat1, double lon1, double lat2, double lon2); double calcOrientation(double lat1, double lon1, double lat2, double lon2, boolean exact); double convertAzimuth2xaxisAngle(double azimuth); double alignOrientation(double baseOrientation, double orientation); double calcAzimuth(double lat1, double lon1, double lat2, double lon2); }### Answer: @Test public void testConvertAzimuth2xaxisAngle() { assertEquals(Math.PI / 2, AC.convertAzimuth2xaxisAngle(0), 1E-6); assertEquals(Math.PI / 2, Math.abs(AC.convertAzimuth2xaxisAngle(360)), 1E-6); assertEquals(0, AC.convertAzimuth2xaxisAngle(90), 1E-6); assertEquals(-Math.PI / 2, AC.convertAzimuth2xaxisAngle(180), 1E-6); assertEquals(Math.PI, Math.abs(AC.convertAzimuth2xaxisAngle(270)), 1E-6); assertEquals(-3 * Math.PI / 4, AC.convertAzimuth2xaxisAngle(225), 1E-6); assertEquals(3 * Math.PI / 4, AC.convertAzimuth2xaxisAngle(315), 1E-6); }
### Question: GzipCompressor implements Compressor { @Override public byte[] compress(byte[] uncompressed) { byte[] returnBuffer; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressed.length); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bos)) { gzipOutputStream.write(uncompressed); gzipOutputStream.close(); returnBuffer = bos.toByteArray(); bos.close(); return returnBuffer; } catch (Exception e) { throw new IllegalStateException("could not compress gzip", e); } } GzipCompressor(); @Override byte[] decompress(byte[] compressed); @Override byte[] compress(byte[] uncompressed); }### Answer: @Test public void compress() throws Exception { byte[] original = Bytes.random(128).append(Bytes.allocate(1024)).transform(BytesTransformers.shuffle()).array(); byte[] compressed = compressor.compress(original); assertTrue(compressed.length < original.length); }
### Question: GzipCompressor implements Compressor { @Override public byte[] decompress(byte[] compressed) { byte[] returnBuffer; byte[] buffer = new byte[2048]; int len; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressed))) { while ((len = gzipInputStream.read(buffer)) > 0) { bos.write(buffer, 0, len); } gzipInputStream.close(); returnBuffer = bos.toByteArray(); bos.close(); Timber.v("compression saved %d byte", compressed.length - returnBuffer.length); return returnBuffer; } catch (Exception e) { throw new IllegalStateException("could not decompress gzip", e); } } GzipCompressor(); @Override byte[] decompress(byte[] compressed); @Override byte[] compress(byte[] uncompressed); }### Answer: @Test public void decompress() throws Exception { testCompressDecompress(1); testCompressDecompress(12); testCompressDecompress(128); testCompressDecompress(512); testCompressDecompress(2048); testCompressDecompress(8096); }
### Question: BrokenBcryptKeyStretcher implements KeyStretchingFunction { private static byte[] bcrypt(char[] password, byte[] salt, int logRounds) { StrictMode.noteSlowCall("bcrypt is a very expensive call and should not be done on the main thread"); return BCrypt.with(CUSTOM_LEGACY_VERSION, new SecureRandom(), rawPassword -> Bytes.wrapNullSafe(rawPassword).copy().array()).hash(logRounds, createLegacySalt(salt), createLegacyPassword(password, salt)); } BrokenBcryptKeyStretcher(); BrokenBcryptKeyStretcher(int log2Rounds); @Override byte[] stretch(byte[] salt, char[] password, int outLengthByte); }### Answer: @Test public void testBcrypt() { for (int i = 4; i < 10; i++) { compareLegacyFallbackImpl(i, 8, 8); compareLegacyFallbackImpl(i, 16, 16); compareLegacyFallbackImpl(i, 32, 16); compareLegacyFallbackImpl(i, 32, 32); compareLegacyFallbackImpl(i, 64, 32); compareLegacyFallbackImpl(i, 64, 64); compareLegacyFallbackImpl(i, 128, 128); compareLegacyFallbackImpl(i, 4, 128); compareLegacyFallbackImpl(i, 128, 4); compareLegacyFallbackImpl(i, 64, 16); } }
### Question: Randomizer { public static int poissonValue(double mean) { if (mean<100){ return poissonSmall(mean); } else{ return poissonLarge(mean); } } static int poissonValue(double mean); static double gaussianValue(double mean, double sigma); static void addMixedGaussianPoissonNoise(String gaussSigma, String gaussMean); static void addMixedGaussianPoissonNoise(double gaussSigma, double gaussMean); static void addMixedGaussianPoissonNoise(ImagePlus imp, double gaussSigma, double gaussMean); static void addMixedGaussianPoissonNoise(ImageProcessor ip, double gaussSigma, double gaussMean); static void addGaussianNoise(ImagePlus imp, double gaussSigma, double gaussMean); static void addGaussianNoise(ImageProcessor ip, double gaussSigma, double gaussMean); static void addsCMOSNoise(ImagePlus imp, ImagePlus sCMOSFPN); static void addPoissonNoise(ImageProcessor ip); static void FPNGainOffset(ImageProcessor ip, ImagePlus sCMOSFPN); static Random random; }### Answer: @Test public void testRandomizer() throws Exception{ double mean = 80; int sampleSize = 10000; float[] randomNumbers = new float[sampleSize]; for(int i = 0; i < randomNumbers.length; i++){ randomNumbers[i] = (float) Randomizer.poissonValue(mean); } float Sum = 0; float Sum2 = 0; float Ave; float Var; for(int i = 0; i < randomNumbers.length; i++){ Sum += randomNumbers[i]; Sum2 += randomNumbers[i] * randomNumbers[i]; } Ave = Sum / ((float)sampleSize); Var = (Sum2 - Sum*Sum/((float)sampleSize))/((float)sampleSize - 1); System.out.println(Ave); System.out.println(Var); }
### Question: CLDevicesInfo { public static String getInfo() { String info = "Best device: " + Device.best(); info += "\nFirst CPU: " + Device.firstCPU(); info += "\nFirst GPU: " + Device.firstGPU(); return info; } static boolean isAparapiLibFound(); static boolean isAparapiJarFound(); static boolean isMultipleCopiesFound(); static List<File> getAparapiLibFile(); static List<File> getAparapiJarFile(); static String getInfo(); static float getGlobalMemSize(String type); static float getGlobalMemSizeBest(); static float getGlobalMemSizeChosenDevice(); static int getComputeUnits(String type); static int getComputeUnits(); static String allInfo(); static List<String> deviceList(); static String deviceIdentity(Device deviceSelected); synchronized static boolean aparapiFileSearch(); static OpenCLDevice chosenDevice; }### Answer: @Test public void testGetInfo() throws Exception { System.out.println(CLDevicesInfo.getInfo()); }
### Question: CLDevicesInfo { public static float getGlobalMemSizeBest() { return getGlobalMemSize("Best"); } static boolean isAparapiLibFound(); static boolean isAparapiJarFound(); static boolean isMultipleCopiesFound(); static List<File> getAparapiLibFile(); static List<File> getAparapiJarFile(); static String getInfo(); static float getGlobalMemSize(String type); static float getGlobalMemSizeBest(); static float getGlobalMemSizeChosenDevice(); static int getComputeUnits(String type); static int getComputeUnits(); static String allInfo(); static List<String> deviceList(); static String deviceIdentity(Device deviceSelected); synchronized static boolean aparapiFileSearch(); static OpenCLDevice chosenDevice; }### Answer: @Test public void testGetMemory() throws Exception { System.out.println("globalMemSize="+ CLDevicesInfo.getGlobalMemSizeBest()); }
### Question: DateUtils { public static String formatInstant(Instant instant) { if (instant == null) { return null; } return DATE_FORMATTER.withZone(ZoneOffset.UTC).format(instant); } static String formatDate(TemporalAccessor dateTime); static String formatInstant(Instant instant); static LocalDateTime parseDate(String date); static LocalDateTime parseDateTime(String dateTime); static Instant parseDateInstant(String strDate); }### Answer: @Test public void testFormatInstant() { Instant instant = of(2017, 12, 10); String formatted = DateUtils.formatInstant(instant); assertThat(formatted).isEqualTo("2017-12-10"); }
### Question: DateUtils { public static Instant parseDateInstant(String strDate) { LocalDateTime dateTime = parseDate(strDate); if (dateTime != null) { return dateTime.toInstant(ZoneOffset.UTC); } return null; } static String formatDate(TemporalAccessor dateTime); static String formatInstant(Instant instant); static LocalDateTime parseDate(String date); static LocalDateTime parseDateTime(String dateTime); static Instant parseDateInstant(String strDate); }### Answer: @Test public void testParseInstant() { String formatted = "2017-12-10"; Instant instant = DateUtils.parseDateInstant(formatted); assertThat(instant).isEqualTo(of(2017, 12, 10)); }
### Question: PhoneUtils { public static boolean isValidNumber(String number) { if (number == null) { return false; } number = number.trim().replaceAll("\\s+", ""); if (!PHONE_PATTERN.matcher(number).matches()) { return false; } return true; } static boolean isValidNumber(String number); static String toInternationalFormat(String number); static Optional<String> extractPhoneNumber(String message); }### Answer: @Parameters({ "123", "+123", " +123 ", " 123 ", " +421 904 938 419 ", "2787240508621337", "27872 405 086 21337", "+ 2787240508621337", " + 2787240508621337", }) @Test public void testIsValidNumber_shouldBeValidNumber(String number){ boolean isValid = PhoneUtils.isValidNumber(number); assertThat(isValid).isTrue(); } @Parameters({ "", "null", "a", "12 ", " aa 123 ", " asdf " }) @Test public void testIsValidNumber_shouldBeINVALIDNumber(@Nullable String number){ boolean isValid = PhoneUtils.isValidNumber(number); assertThat(isValid).isFalse(); }
### Question: PhoneUtils { public static String toInternationalFormat(String number) throws NumberParseException { if (!isValidNumber(number)) { throw new NumberParseException(ErrorType.NOT_A_NUMBER, number + " is not a valid number"); } number = number.replaceAll("\\s+", ""); if (!number.contains("+")) { number = "+" + number; } PhoneNumber phoneNmber = PhoneNumberUtil.getInstance().parse(number, null); String nationalNumber = String.valueOf(phoneNmber.getNationalNumber()); String countryCode = String.valueOf(phoneNmber.getCountryCode()); String leadingZero = phoneNmber.hasItalianLeadingZero() ? "0" : ""; return countryCode + leadingZero + nationalNumber; } static boolean isValidNumber(String number); static String toInternationalFormat(String number); static Optional<String> extractPhoneNumber(String message); }### Answer: @Parameters({ " +421 904 938 419 | 421904938419 ", " 421 904 938 419 | 421904938419 ", " +3906123456 | 3906123456 ", " +4407756738685 | 447756738685 ", " 4407756738685 | 447756738685 ", }) @Test public void testToInternationalFormat_shouldReturnFormattedNumber(String number, String expected) throws NumberParseException{ String actual = PhoneUtils.toInternationalFormat(number); assertThat(actual).isEqualTo(expected); }
### Question: PhoneUtils { public static Optional<String> extractPhoneNumber(String message){ if(message == null){ return Optional.empty(); } String number = REMOVE_NON_NUMERIC_CHARS.matcher(message).replaceAll(""); try { return Optional.ofNullable(toInternationalFormat(number)); } catch (NumberParseException e) { } return Optional.empty(); } static boolean isValidNumber(String number); static String toInternationalFormat(String number); static Optional<String> extractPhoneNumber(String message); }### Answer: @Parameters({ "a +421904938419 a | 421904938419 ", " +3906123456 | 3906123456 ", "+447756738686 | 447756738686 ", "My number is +4407756738685 | 447756738685 ", }) @Test public void testExtractPhoneNumber_shouldBeExtracted(String message, String expectedNumber){ Optional<String> actualNumber = PhoneUtils.extractPhoneNumber(message); assertThat(actualNumber.get()).isEqualTo(expectedNumber); }
### Question: SignupFormValidator implements Validator { @Override public void validate(Object target, Errors errors) { SignupForm form = (SignupForm) target; validateUniqueEmail(form, errors); validateUniquePhone(form, errors); validateValidPhone(form, errors); validatePassword(form, errors); } SignupFormValidator(UserRepository userRepository); @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); }### Answer: @Test @Ignore public void shoudBeValid(){ validator.validate(form, errors); verifyZeroInteractions(errors); }
### Question: MsTeamsNotificationAjaxEditPageController extends BaseController { protected static void checkAndAddBuildState(HttpServletRequest r, BuildState state, BuildStateEnum myBuildState, String varName){ if ((r.getParameter(varName) != null) && ("on".equalsIgnoreCase(r.getParameter(varName)))){ state.enable(myBuildState); } else { state.disable(myBuildState); } } MsTeamsNotificationAjaxEditPageController(SBuildServer server, WebControllerManager webManager, ProjectSettingsManager settings, MsTeamsNotificationProjectSettings whSettings, MsTeamsNotificationPayloadManager manager, PluginDescriptor pluginDescriptor, MsTeamsNotificationMainSettings mainSettings); void register(); }### Answer: @Test public void testCheckAndAddBuildState() { assertFalse(states.enabled(BuildStateEnum.BUILD_SUCCESSFUL)); checkAndAddBuildState(requestSuccessOnAndFailureOff, states, BuildStateEnum.BUILD_SUCCESSFUL, BUILD_SUCCESSFUL); assertTrue(states.enabled(BuildStateEnum.BUILD_SUCCESSFUL)); assertFalse(states.enabled(BuildStateEnum.BUILD_FINISHED)); checkAndAddBuildState(requestSuccessOnAndFailureOff, states, BuildStateEnum.BUILD_FINISHED, BUILD_SUCCESSFUL); assertTrue(states.enabled(BuildStateEnum.BUILD_FINISHED)); assertFalse(states.enabled(BuildStateEnum.BUILD_FAILED)); checkAndAddBuildState(requestSuccessOnAndFailureOff, states, BuildStateEnum.BUILD_FINISHED, BUILD_FAILED); assertFalse(states.enabled(BuildStateEnum.BUILD_FAILED)); assertFalse(states.enabled(BuildStateEnum.BUILD_FINISHED)); }
### Question: VariableMessageBuilder { public String build(){ return matcher.replace(template, resolver); } static VariableMessageBuilder create(final String template, VariableResolver resolver); String build(); }### Answer: @Test public void testBuild() { MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(sBuildServer, sRunningBuild, previousSuccessfulBuild, BuildStateEnum.BEFORE_BUILD_FINISHED); VariableMessageBuilder builder = VariableMessageBuilder.create("This is a test ${buildFullName}", new MsTeamsNotificationBeanUtilsVariableResolver(content)); System.out.println(builder.build()); System.out.println(content.getBuildFullName()); } @Test public void testBuild() { SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(sBuildServer, sRunningBuild, previousSuccessfulBuild, BuildStateEnum.BEFORE_BUILD_FINISHED); VariableMessageBuilder builder = VariableMessageBuilder.create("This is a test ${buildFullName}", new SlackNotificationBeanUtilsVariableResolver(content)); System.out.println(builder.build()); System.out.println(content.getBuildFullName()); }
### Question: LogApi { public AuditLogResponse getAuditLogs(String xProjectId, String resourceType, String cursor, String resourceId, Integer pageNumber, Integer limit) throws ApiException { ApiResponse<AuditLogResponse> resp = getAuditLogsWithHttpInfo(xProjectId, resourceType, cursor, resourceId, pageNumber, limit); return resp.getData(); } LogApi(); LogApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); com.squareup.okhttp.Call getAuditLogsCall(String xProjectId, String resourceType, String cursor, String resourceId, Integer pageNumber, Integer limit, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener); AuditLogResponse getAuditLogs(String xProjectId, String resourceType, String cursor, String resourceId, Integer pageNumber, Integer limit); ApiResponse<AuditLogResponse> getAuditLogsWithHttpInfo(String xProjectId, String resourceType, String cursor, String resourceId, Integer pageNumber, Integer limit); com.squareup.okhttp.Call getAuditLogsAsync(String xProjectId, String resourceType, String cursor, String resourceId, Integer pageNumber, Integer limit, final ApiCallback<AuditLogResponse> callback); }### Answer: @Test public void getAuditLogsTest() throws ApiException { String xProjectId = null; String resourceType = null; String cursor = null; String resourceId = null; Integer pageNumber = null; Integer limit = null; AuditLogResponse response = api.getAuditLogs(xProjectId, resourceType, cursor, resourceId, pageNumber, limit); }
### Question: StatisticsApi { public OverviewResponse overview(String xProjectId) throws ApiException { ApiResponse<OverviewResponse> resp = overviewWithHttpInfo(xProjectId); return resp.getData(); } StatisticsApi(); StatisticsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); com.squareup.okhttp.Call overviewCall(String xProjectId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener); OverviewResponse overview(String xProjectId); ApiResponse<OverviewResponse> overviewWithHttpInfo(String xProjectId); com.squareup.okhttp.Call overviewAsync(String xProjectId, final ApiCallback<OverviewResponse> callback); }### Answer: @Test public void overviewTest() throws ApiException { String xProjectId = null; OverviewResponse response = api.overview(xProjectId); }
### Question: AuthorizeApi { public GlobalResponse authorizeBucket(String xProjectId, List<String> body) throws ApiException { ApiResponse<GlobalResponse> resp = authorizeBucketWithHttpInfo(xProjectId, body); return resp.getData(); } AuthorizeApi(); AuthorizeApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); com.squareup.okhttp.Call authorizeBucketCall(String xProjectId, List<String> body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener); GlobalResponse authorizeBucket(String xProjectId, List<String> body); ApiResponse<GlobalResponse> authorizeBucketWithHttpInfo(String xProjectId, List<String> body); com.squareup.okhttp.Call authorizeBucketAsync(String xProjectId, List<String> body, final ApiCallback<GlobalResponse> callback); }### Answer: @Test public void authorizeBucketTest() throws ApiException { String xProjectId = null; List<String> body = null; GlobalResponse response = api.authorizeBucket(xProjectId, body); }
### Question: RowKeyCoder { public static byte[] encode(Long pointId, Integer baseTime){ int keySize = SALT_LENGTH + Constant.POINT_LENGTH + Constant.TIMESTAMP_LENGTH; byte[] rowKey = new byte[keySize]; byte[] pointIdBytes = Bytes.fromLong(pointId); System.arraycopy(pointIdBytes, 0, rowKey, SALT_LENGTH, Constant.POINT_LENGTH); byte[] saltBytes = getSalt(pointIdBytes); System.arraycopy(saltBytes, 0, rowKey, 0, SALT_LENGTH); byte[] baseTimeBytes = Bytes.fromInt(baseTime); System.arraycopy(baseTimeBytes, 0, rowKey, Constant.POINT_LENGTH + SALT_LENGTH, Constant.TIMESTAMP_LENGTH); return rowKey; } static byte[] encode(Long pointId, Integer baseTime); static RowKey decode(byte[] bytes); static byte[] getSalt(byte[] salt_base); static final int SALT_LENGTH; static final int BUCKETS_SIZE; }### Answer: @Test public void testEncode() { byte[] a = {'6',0,0,0,0,0,(byte)188,97,78,89,(byte)207,(byte)205,(byte)144}; byte[] b = RowKeyCoder.encode(12345678L, 1506790800); if (Bytes.equals(a, b)){ assertTrue(true); } else { assertTrue(false); } }
### Question: RowKeyCoder { public static RowKey decode(byte[] bytes){ byte[] longBytes = new byte[Constant.POINT_LENGTH]; System.arraycopy(bytes, SALT_LENGTH, longBytes, 0, Constant.POINT_LENGTH); long pointId = Bytes.getLong(longBytes); byte[] baseTimeBytes = new byte[Constant.TIMESTAMP_LENGTH]; System.arraycopy(bytes, Constant.POINT_LENGTH + SALT_LENGTH, baseTimeBytes, 0, Constant.TIMESTAMP_LENGTH); Integer baseTime = Bytes.getInt(baseTimeBytes); RowKey rowKey = new RowKey(); rowKey.setPointId(pointId); rowKey.setBaseTime(baseTime); return rowKey; } static byte[] encode(Long pointId, Integer baseTime); static RowKey decode(byte[] bytes); static byte[] getSalt(byte[] salt_base); static final int SALT_LENGTH; static final int BUCKETS_SIZE; }### Answer: @Test public void testDecode() { byte[] a = {'6',0,0,0,0,0,(byte)188,97,78,89,(byte)207,(byte)205,(byte)144}; RowKey r = RowKeyCoder.decode(a); assertTrue((12345678L==r.getPointId()) && (1506790800 == r.getBaseTime())); }
### Question: StandaloneEndpointPublisher implements EndpointPublisher { static int getPort() { int port = DEFAULT_PORT; final String portAsStr = System.getProperty(DEFAULT_PORT_PROPERTY); if (portAsStr != null) { port = Integer.parseInt(portAsStr); } return port; } Endpoint publish(ServiceDomain domain, String context, InboundHandler handler); static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type); static final int DEFAULT_PORT; static final String DEFAULT_PORT_PROPERTY; }### Answer: @Test public void useDefaultPort() { final int port = StandaloneEndpointPublisher.getPort(); assertThat(port, is(equalTo(StandaloneEndpointPublisher.DEFAULT_PORT))); } @Test public void useConfiguredPort() { System.setProperty(StandaloneEndpointPublisher.DEFAULT_PORT_PROPERTY, Integer.toString(TEST_PORT)); final int port = StandaloneEndpointPublisher.getPort(); assertThat(port, is(equalTo(TEST_PORT))); }
### Question: V1ClojureComponentImplementationModel extends V1ComponentImplementationModel implements ClojureComponentImplementationModel { @Override public ClojureScriptModel getScriptModel() { if (_scriptModel != null) { return _scriptModel; } _scriptModel = (ClojureScriptModel) getFirstChildModel(SCRIPT); return _scriptModel; } V1ClojureComponentImplementationModel(String namespace); V1ClojureComponentImplementationModel(final Configuration config, final Descriptor desc); @Override ClojureScriptModel getScriptModel(); @Override V1ClojureComponentImplementationModel setScriptModel(final ClojureScriptModel scriptModel); @Override String getScriptFile(); @Override V1ClojureComponentImplementationModel setScriptFile(final String scriptFile); @Override Boolean injectExchange(); @Override ClojureComponentImplementationModel setInjectExchange(final Boolean enable); }### Answer: @Test public void inlineScript() throws Exception { final V1ClojureComponentImplementationModel implModel = getImplModel("switchyard-clojure-impl.xml"); final Validation validateModel = implModel.validateModel(); assertThat(validateModel.isValid(), is(true)); final String script = implModel.getScriptModel().getScript(); assertThat(script, is(equalTo("(ns printer)(defn print-string [arg] (println arg))"))); }
### Question: QueryString { public String toString() { if (_uriStr.length() == 0) { return ""; } else { return "?" + _uriStr.toString(); } } QueryString(); QueryString add(String name, Object value); String toString(); }### Answer: @Test public void testEmptyQueryString() { QueryString qs = new QueryString(); assertEquals("", qs.toString()); }
### Question: TransactionManagerFactory { public static TransactionManagerFactory getInstance() { return INSTANCE; } private TransactionManagerFactory(); static TransactionManagerFactory getInstance(); PlatformTransactionManager create(); static final String JBOSS_USER_TRANSACTION; static final String JBOSS_TRANSACTION_MANANGER; static final String JBOSS_TRANSACTION_SYNC_REG; static final String OSGI_TRANSACTION_MANAGER; static final String TM; }### Answer: @Test public void getInstance() { final TransactionManagerFactory factory = TransactionManagerFactory.getInstance(); assertThat(factory, is(notNullValue())); }
### Question: InboundHandler extends BaseServiceHandler { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_camelBindingModel == null) ? 0 : _camelBindingModel.getComponentURI().hashCode()); return result; } InboundHandler(final T camelBindingModel, final SwitchYardCamelContext camelContext, final QName serviceName, final ServiceDomain domain); String getRouteId(); @Override void handleMessage(final Exchange switchYardExchange); @Override void handleFault(final Exchange exchange); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void verifyEqualHashCode() { final InboundHandler<?> x = createInboundHandler("direct: final InboundHandler<?> y = createInboundHandler("direct: assertThat(x.hashCode(), is(y.hashCode())); } @Test public void verifyUnEqualHashCode() { final InboundHandler<?> x = createInboundHandler("direct: final InboundHandler<?> y = createInboundHandler("direct: assertThat(x.hashCode() == y.hashCode(), is(false)); }
### Question: V1SOAPMessageComposerModel extends V1MessageComposerModel implements SOAPMessageComposerModel { @Override public Boolean isUnwrapped() { String unwrap = getModelAttribute("unwrapped"); return unwrap != null && Boolean.valueOf(unwrap); } V1SOAPMessageComposerModel(String namespace); V1SOAPMessageComposerModel(Configuration config, Descriptor desc); @Override Boolean isUnwrapped(); @Override SOAPMessageComposerModel setUnwrapped(boolean unwrapped); }### Answer: @Test public void testReadConfigFragment() throws Exception { ModelPuller<V1SOAPMessageComposerModel> puller = new ModelPuller<V1SOAPMessageComposerModel>(); V1SOAPMessageComposerModel model = puller.pull(COMPOSER_FRAG, getClass()); Assert.assertTrue("Unwrap should be true", model.isUnwrapped()); } @Test public void testReadConfigBinding() throws Exception { ModelPuller<SOAPBindingModel> puller = new ModelPuller<SOAPBindingModel>(); SOAPBindingModel model = puller.pull(SOAP_BINDING, getClass()); Assert.assertTrue(model.isModelValid()); Assert.assertTrue("Unwrap should be true", model.getSOAPMessageComposer().isUnwrapped()); }
### Question: V1SOAPMessageComposerModel extends V1MessageComposerModel implements SOAPMessageComposerModel { @Override public SOAPMessageComposerModel setUnwrapped(boolean unwrapped) { setModelAttribute("unwrapped", String.valueOf(unwrapped)); return this; } V1SOAPMessageComposerModel(String namespace); V1SOAPMessageComposerModel(Configuration config, Descriptor desc); @Override Boolean isUnwrapped(); @Override SOAPMessageComposerModel setUnwrapped(boolean unwrapped); }### Answer: @Test public void testWriteConfig() throws Exception { V1SOAPMessageComposerModel scm = new V1SOAPMessageComposerModel(SOAPNamespace.V_1_0.uri()); scm.setUnwrapped(true); V1SOAPMessageComposerModel refModel = new ModelPuller<V1SOAPMessageComposerModel>() .pull(COMPOSER_FRAG, getClass()); XMLUnit.setIgnoreWhitespace(true); Diff diff = XMLUnit.compareXML(refModel.toString(), scm.toString()); Assert.assertTrue(diff.toString(), diff.similar()); }