src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
HueServiceImpl implements HueService { @Override public List<FoundBridgeDTO> findAllBridges() { return new ArrayList<>(Arrays.asList(new TestRestTemplate().getForObject("https: } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @Override void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge); @Override void disconnectFromBridge(BridgeDTO bridge); @Override void showRandomColorsOnAllLamps(); @Async @Override void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config); @Override List<LampHueDTO> findAllLamps(); @Override List<FoundBridgeDTO> findAllBridges(); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); @Override void updateBridgeState(List<BridgeDTO> bridgeDTOs); @Override boolean ipAreEqual(String ip1, String ip2); String removePortAndToLowerCase(String ip); }
@Test public void testFindAllBridgesIsModifiable() { List<FoundBridgeDTO> allBridges = hueService.findAllBridges(); allBridges.add(new FoundBridgeDTO()); allBridges.add(new FoundBridgeDTO()); allBridges.remove(0); }
JobListener { boolean isTurnOffTime(LampDTO lamp, DateTime now) { int workingStart = new DateTime(lamp.getWorkingStart()).getMillisOfDay(); int workingEnd = new DateTime(lamp.getWorkingEnd()).getMillisOfDay(); int n = now.getMillisOfDay(); return (workingStart > n) || (n > workingEnd); } @Autowired JobListener(JenkinsService jenkinsService, LampService lampService, HueService hueService); }
@Test public void testIsTurnOffTime() { LampDTO lampDTO = new LampDTO(); lampDTO.setWorkingStart(DateTime.now().withMillisOfDay(0).withHourOfDay(7).toDate()); lampDTO.setWorkingEnd(DateTime.now().withMillisOfDay(0).withHourOfDay(19).toDate()); DateTime beerOClock = DateTime.now().withHourOfDay(20); assertTrue(jobListener.isTurnOffTime(lampDTO, beerOClock)); DateTime earlyInTheMorning = DateTime.now().withHourOfDay(5); assertTrue(jobListener.isTurnOffTime(lampDTO, earlyInTheMorning)); DateTime hardWorkingTime = DateTime.now().withHourOfDay(10); assertFalse(jobListener.isTurnOffTime(lampDTO, hardWorkingTime)); DateTime workingStart = DateTime.now().withMillisOfDay(0).withHourOfDay(7); assertFalse(jobListener.isTurnOffTime(lampDTO, workingStart)); DateTime beforeWorkingStart = workingStart.minusMillis(1); assertTrue(jobListener.isTurnOffTime(lampDTO, beforeWorkingStart)); DateTime afterWorkingStart = workingStart.plusMillis(1); assertFalse(jobListener.isTurnOffTime(lampDTO, afterWorkingStart)); DateTime workingEnd = DateTime.now().withMillisOfDay(0).withHourOfDay(19); assertFalse(jobListener.isTurnOffTime(lampDTO, workingEnd)); DateTime beforeWorkingEnd = workingEnd.minusMillis(1); assertFalse(jobListener.isTurnOffTime(lampDTO, beforeWorkingEnd)); DateTime afterWorkingEnd = workingEnd.plusMillis(1); assertTrue(jobListener.isTurnOffTime(lampDTO, afterWorkingEnd)); }
JobListener { BuildState extractBuildState(JenkinsBuildDTO build) { if (build == null) { throw new IllegalArgumentException("build ist null!"); } else { if (build.isBuilding()) { return BuildState.BUILDING; } else { return BuildState.valueOf(build.getResult()); } } } @Autowired JobListener(JenkinsService jenkinsService, LampService lampService, HueService hueService); }
@Test public void testExtractBuildState() { JenkinsBuildDTO b1 = new JenkinsBuildDTO(false, "FAILURE", 1, null); JenkinsBuildDTO b2 = new JenkinsBuildDTO(false, "UNSTABLE", 2, null); JenkinsBuildDTO b3 = new JenkinsBuildDTO(false, "SUCCESS", 3, null); JenkinsBuildDTO b4 = new JenkinsBuildDTO(true, "", 4, null); assertEquals(BuildState.FAILURE, jobListener.extractBuildState(b1)); assertEquals(BuildState.UNSTABLE, jobListener.extractBuildState(b2)); assertEquals(BuildState.SUCCESS, jobListener.extractBuildState(b3)); assertEquals(BuildState.BUILDING, jobListener.extractBuildState(b4)); }
HolidayServiceImpl implements HolidayService { @Override public boolean isHoliday(DateTime day) { if (day == null) { return false; } Calendar cal = GregorianCalendar.getInstance(); cal.setTime(day.toDate()); HolidayManager m = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.GERMANY, null)); boolean isHoliday = m.isHoliday(cal, "nw"); if (!isHoliday && day.getMonthOfYear() == 12) { if (day.getDayOfMonth() == 24 || day.getDayOfMonth() == 31) { isHoliday = true; } } return isHoliday; } @Override boolean isHoliday(DateTime day); @Override boolean isWeekend(DateTime day); @Override boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd); }
@Test public void testIsHoliday() { assertTrue(holidayService.isHoliday(new DateTime(2016, 1, 1, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 3, 25, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 3, 28, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 5, 1, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 5, 5, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 5, 16, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 5, 26, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 10, 3, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 11, 1, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 12, 25, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 12, 26, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 12, 24, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 12, 31, 0, 0))); assertFalse(holidayService.isHoliday(new DateTime(2016, 1, 4, 0, 0))); assertFalse(holidayService.isHoliday(null)); }
HolidayServiceImpl implements HolidayService { @Override public boolean isWeekend(DateTime day) { return day != null && (day.getDayOfWeek() == DateTimeConstants.SATURDAY || day.getDayOfWeek() == DateTimeConstants.SUNDAY); } @Override boolean isHoliday(DateTime day); @Override boolean isWeekend(DateTime day); @Override boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd); }
@Test public void testIsWeekend() { assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 1, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 2, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 3, 0, 0))); assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 4, 0, 0))); assertFalse(holidayService.isWeekend(null)); }
HolidayServiceImpl implements HolidayService { @Override public boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd) { if (workingStart == null || workingEnd == null) { return false; } else if (workingEnd.getMillisOfDay() < workingStart.getMillisOfDay()) { return false; } else { return workingStart.getMinuteOfDay() >= 15 && workingEnd.getMinuteOfDay() <= 1425; } } @Override boolean isHoliday(DateTime day); @Override boolean isWeekend(DateTime day); @Override boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd); }
@Test public void testIsValidWorkingPeriod() { DateTime h00m14 = new DateTime(2016, 1, 1, 0, 14); DateTime h00m15 = new DateTime(2016, 1, 1, 0, 15); DateTime h00m16 = new DateTime(2016, 1, 1, 0, 16); DateTime h08m00 = new DateTime(2016, 1, 1, 8, 0); DateTime h16m00 = new DateTime(2016, 1, 1, 16, 0); DateTime h23m44 = new DateTime(2016, 1, 1, 23, 44); DateTime h23m45 = new DateTime(2016, 1, 1, 23, 45); DateTime h23m46 = new DateTime(2016, 1, 1, 23, 46); assertFalse(holidayService.isValidWorkingPeriod(h00m14, h16m00)); assertTrue(holidayService.isValidWorkingPeriod(h00m15, h16m00)); assertTrue(holidayService.isValidWorkingPeriod(h00m16, h16m00)); assertTrue(holidayService.isValidWorkingPeriod(h08m00, h23m44)); assertTrue(holidayService.isValidWorkingPeriod(h08m00, h23m45)); assertFalse(holidayService.isValidWorkingPeriod(h08m00, h23m46)); assertTrue(holidayService.isValidWorkingPeriod(h08m00, h16m00)); assertFalse(holidayService.isValidWorkingPeriod(h16m00, h08m00)); assertFalse(holidayService.isValidWorkingPeriod(null, h16m00)); assertFalse(holidayService.isValidWorkingPeriod(h08m00, null)); }
RMSKeyUtils { int toValueIndex(final Long hashValue) { return (int) (hashValue.longValue() & 0xFFFFFFFF); } }
@Test public void valueIndexValuesCanStoreEntireIntegerRange() { long one = 1; long previous = 0; for (int bits = 0; bits < 32; bits++) { long shifted = one << bits; assertTrue("Overflow when shifting long. Previous value: " + previous + " now: " + shifted, shifted > previous); previous = shifted; int vi = keyUtils.toValueIndex(shifted); assertEquals((int) shifted, vi); } }
StringUtils { public static byte[] hexStringToByteArray(final String s) { if (s == null) { throw new NullPointerException("hexStringToByteArray was pass null string"); } final int n = s.length(); if (n % 2 != 0) { throw new IllegalArgumentException("Input string must be an even length and encoded by byteArrayToHexString(s), but input length is " + n); } final byte[] bytes = new byte[n / 2]; int k = 0; for (int i = 0; i < n; i += 2) { final String substring = s.substring(i, i + 2); final int j = Integer.parseInt(substring, 16); bytes[k++] = (byte) j; } return bytes; } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Test public void sampleBytesToHexString() { assertArrayEquals(sampleAsBytes, StringUtils.hexStringToByteArray(sampleAsHex)); } @Test(expected = IllegalArgumentException.class) public void hexStringChecksForWrongLengthInput() { StringUtils.hexStringToByteArray("0"); } @Test(expected = IllegalArgumentException.class) public void illegalCharsInHexStringFirstPosition() { StringUtils.hexStringToByteArray("QF"); } @Test(expected = IllegalArgumentException.class) public void illegalCharsInHexStringSecondPosition() { StringUtils.hexStringToByteArray("FZ"); }
StringUtils { public static String byteArrayToHexString(final byte[] bytes) { final StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { appendHex(bytes[i], sb); } return sb.toString(); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Test public void sampleHexStringAsBytes() { assertEquals(sampleAsHex, StringUtils.byteArrayToHexString(sampleAsBytes)); } @Test public void toHexTestFF00() { assertEquals("FF00", StringUtils.byteArrayToHexString(byteTest1)); } @Test public void toHexTestCD1A() { assertEquals("CD1A", StringUtils.byteArrayToHexString(byteTest2)); }
StringUtils { public static String urlDecode(final String s) throws UnsupportedEncodingException, IOException { if (s == null) { throw new NullPointerException("Can not urlDecode null string"); } final int n = s.length(); final StringBuffer sb = new StringBuffer(n * 2); for (int i = 0; i < n; i++) { final char c = s.charAt(i); if (c == '+') { sb.append(' '); } else if (c == '%') { final String s1 = s.substring(++i, i++ + 2); final int first = Integer.parseInt(s1, 16); if (first < 128) { sb.append((char) first); } else { if (s.charAt(++i) != '%') { throw new IllegalArgumentException("urlDecode expected second '%' at position " + i + " but was '" + s.charAt(i) + "' : " + s); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final String s2 = s.substring(++i, i++ + 2); final int second = Integer.parseInt(s2, 16); bos.write(first); bos.write(second); if (first < 224) { sb.append(new String(bos.toByteArray(), "UTF-8")); } else { if (s.charAt(++i) != '%') { throw new IllegalArgumentException("urlDecode expected third '%' at position " + i + " but was '" + s.charAt(i) + "'" + s); } final String s3 = s.substring(++i, i++ + 2); final int third = Integer.parseInt(s3, 16); bos.write(third); if (first < 240) { sb.append(new String(bos.toByteArray(), "UTF-8")); } else { if (s.charAt(++i) != '%') { throw new IllegalArgumentException("urlDecode expected fourth '%' at position " + i + " but was '" + s.charAt(i) + "'" + s); } final String s4 = s.substring(++i, i++ + 2); final int fourth = Integer.parseInt(s4, 16); bos.write(fourth); sb.append(new String(bos.toByteArray(), "UTF-8")); } } } } else { sb.append(c); } } return sb.toString(); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Test public void uudecode() throws UnsupportedEncodingException, IOException { assertEquals(roundTripConversionTest, StringUtils.urlDecode(urlDecodeConversionTest)); } @Test public void uudecodeOneChar() throws UnsupportedEncodingException, IOException { System.out.println("oneChar " + oneChar + " - length=" + oneChar.length() + " - " + Integer.toHexString(oneChar.charAt(0)) + " - " + Integer.toBinaryString(oneChar.charAt(0))); char decoded = StringUtils.urlDecode(oneCharEncoded).charAt(0); System.out.println("decoded - " + Integer.toHexString(decoded) + " - " + Integer.toBinaryString(decoded)); assertEquals(oneChar, StringUtils.urlDecode(oneCharEncoded)); } @Test public void fourByteDecode() throws UnsupportedEncodingException, IOException { String fourByteString = new String(fourByteArray, "UTF-8"); assertEquals(fourByteString, StringUtils.urlDecode(fourByteEncoded)); } @Test public void threeByteDecode() throws UnsupportedEncodingException, IOException { String fourByteString = new String(threeByteArray, "UTF-8"); assertEquals(fourByteString, StringUtils.urlDecode(threeByteEncoded)); } @Test public void twoByteDecode() throws UnsupportedEncodingException, IOException { String twoByteString = new String(twoByteArray, "UTF-8"); assertEquals(twoByteString, StringUtils.urlDecode(twoByteEncoded)); } @Test public void oneByteDecode() throws UnsupportedEncodingException, IOException { String oneByteString = new String(oneByteArray, "UTF-8"); assertEquals(oneByteString, StringUtils.urlDecode(oneByteEncoded)); } @Test public void urlDecodeSimple() throws IOException { assertEquals("This+is a simple & short test.", StringUtils.urlDecode("This%2Bis+a+simple+%26+short+test.")); } @Test public void urlDecodeSpaces() throws IOException { assertEquals(" ", StringUtils.urlDecode("+%20")); } @Test public void urlDecodeSymbols() throws IOException { assertEquals("$ & < > ? ; # : = , \" ' ~ + %", StringUtils.urlDecode("%24+%26+%3C+%3E+%3F+%3B+%23+%3A+%3D+%2C+%22+%27+%7E+%2B+%25")); }
StringUtils { public static String urlEncode(final String s) throws IOException { if (s == null) { throw new NullPointerException("Can not urlEncode null string"); } if (s.length() == 0) { return s; } final ByteArrayInputStream bIn; final StringBuffer sb = new StringBuffer((s.length() * 5) / 4); { final ByteArrayOutputStream bOut = new ByteArrayOutputStream((s.length() * 3) / 2); final DataOutputStream dOut = new DataOutputStream(bOut); dOut.writeUTF(s); bIn = new ByteArrayInputStream(bOut.toByteArray()); dOut.close(); } bIn.read(); bIn.read(); int c; while ((c = bIn.read()) >= 0) { if (c == ' ') { sb.append('+'); } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_') { sb.append((char) c); } else { appendTaggedHex(c, sb); if (c >= 128) { appendTaggedHex(bIn.read(), sb); if (c >= 224) { appendTaggedHex(bIn.read(), sb); } } } } return sb.toString(); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Ignore @Test public void fourByteEncode() throws UnsupportedEncodingException, IOException { String fourByteString = new String(fourByteArray, "UTF-8"); assertEquals(fourByteEncoded, StringUtils.urlEncode(fourByteString)); } @Test public void threeByteEncode() throws UnsupportedEncodingException, IOException { String threeByteString = new String(threeByteArray, "UTF-8"); assertEquals(threeByteEncoded, StringUtils.urlEncode(threeByteString)); } @Test public void twoByteEncode() throws UnsupportedEncodingException, IOException { String twoByteString = new String(twoByteArray, "UTF-8"); assertEquals(twoByteEncoded, StringUtils.urlEncode(twoByteString)); } @Test public void oneByteEncode() throws UnsupportedEncodingException, IOException { String oneByteString = new String(oneByteArray, "UTF-8"); assertEquals(oneByteEncoded, StringUtils.urlEncode(oneByteString)); } @Test public void urlEncodeSimple() throws IOException { assertEquals("This%2Bis+a+simple+%26+short+test.", StringUtils.urlEncode("This+is a simple & short test.")); } @Test public void urlEncodeSymbols() throws IOException { assertEquals("%24+%26+%3C+%3E+%3F+%3B+%23+%3A+%3D+%2C+%22+%27+%7E+%2B+%25", StringUtils.urlEncode("$ & < > ? ; # : = , \" ' ~ + %")); } @Test public void urlEncodeTraditionalChinese() throws IOException { assertEquals("%E6%BC%A2%E5%AD%97", StringUtils.urlEncode("漢字")); } @Test public void urlEncodeSimplifiedChinese() throws IOException { assertEquals("%E6%B1%89%E5%AD%97", StringUtils.urlEncode("汉字")); } @Test public void urlEncodeVietnamese() throws IOException { assertEquals("ch%E1%BB%AF+H%C3%A1n", StringUtils.urlEncode("chữ Hán")); } @Test public void urlEncodeZhuang() throws IOException { assertEquals("%E5%80%B1", StringUtils.urlEncode("倱")); } @Test public void urlEncodeKoreanHangul() throws IOException { assertEquals("%ED%95%9C%EC%9E%90", StringUtils.urlEncode("한자")); } @Test public void urlEncodeKoreanHanja() throws IOException { assertEquals("%E6%BC%A2%E5%AD%97", StringUtils.urlEncode("漢字")); } @Test public void urlEncodeJapaneseHiragana() throws IOException { assertEquals("%E3%81%8B%E3%82%93%E3%81%98", StringUtils.urlEncode("かんじ")); } @Test public void urlEncodeHindi() throws IOException { assertEquals("%E0%A4%AE%E0%A5%81%E0%A4%9D%E0%A5%87+%E0%A4%A6%E0%A5%8B+%E0%A4%95%E0%A4%AE%E0%A4%B0%E0%A4%BE+%E0%A4%9A%E0%A4%BE%E0%A4%B9%E0%A4%BF%E0%A4%8F", StringUtils.urlEncode("मुझे दो कमरा चाहिए")); }
RMSKeyUtils { int toKeyIndex(final Long hashValue) { return (int) ((hashValue.longValue() >>> 32) & 0xFFFFFFFF); } }
@Test public void keyIndexValuesCanStoreEntireIntegerRange() { final int bitsInInteger = 32; final long one = 1; for (int bits = 0; bits < bitsInInteger; bits++) { final int keyIntegerValue = (int)(one << bits); final long shiftedLong = one << (bits + bitsInInteger); int ki = keyUtils.toKeyIndex(shiftedLong); assertEquals(keyIntegerValue, ki); } }
RMSFastCache extends FlashCache { public void removeData(final long digest) throws FlashDatabaseException { synchronized (mutex) { try { final Long indexEntry = indexHashGet(digest, false); if (indexEntry != null) { final Long dig = new Long(digest); indexHash.remove(dig); final int valueRecordId = RMSKeyUtils.toValueIndex(indexEntry); final int keyRecordId = RMSKeyUtils.toKeyIndex(indexEntry); int size = 0; if (!Task.isShuttingDown()) { try { final byte[] keyBytes = getKeyRS().getRecord(keyRecordId); final byte[] valueBytes = getValueRS().getRecord(valueRecordId); size = valueBytes.length + keyBytes.length; } catch (Exception e) { L.e(this, "removeData", "can't read", e); } } final boolean storeFlagSet = setStoreFlag(); getValueRS().deleteRecord(valueRecordId); getKeyRS().deleteRecord(keyRecordId); if (storeFlagSet) { clearStoreFlag(); } rmsByteSize -= size; } else { L.i("*** Can not remove from RMS, digest not found", "" + digest + " - " + toString()); } } catch (RecordStoreException e) { throw new FlashDatabaseException("Can not removeData from RMS: " + Long.toString(digest, 16) + " - " + e); } } } RMSFastCache(final char priority, final FlashCache.StartupTask startupTask); void markLeastRecentlyUsed(final Long digest); static void deleteDataFiles(final char priority); String getKey(final long digest); byte[] get(final long digest, final boolean markAsLeastRecentlyUsed); void put(final String key, final byte[] value); void removeData(final long digest); Enumeration getDigests(); void clear(); long getFreespace(); long getSize(); void close(); String toString(); void maintainDatabase(); }
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenNullStringRemoveData() throws DigestException, FlashDatabaseException { rmsFastCache.removeData((String) null); }
StringUtils { public static String readStringFromJAR(final String name) throws IOException { return readStringFromJAR(name, "UTF-8"); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Test public void testReadStringFromJAR() throws Exception { String name_1 = "/test.txt"; String expResult_1 = "Hello, this is test text"; String result_1 = StringUtils.readStringFromJAR(name_1); assertEquals(expResult_1, result_1); }
StringUtils { public static byte[] readBytesFromJAR(final String name) throws IOException { return StringUtilsHolder.instance.doReadBytesFromJAR(name); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }
@Test public void testReadBytesFromJAR() throws Exception { InputStream stream = getClass().getResourceAsStream(EXAMPLE_FILE_NAME); assertNotNull("Could not read example file from classpath", stream); byte[] result_1 = StringUtils.readBytesFromJAR(EXAMPLE_FILE_NAME); assertNotNull(result_1); assertEquals(stream.available(), result_1.length); }
RMSFastCache extends FlashCache { public void put(final String key, final byte[] value) throws DigestException, FlashFullException, FlashDatabaseException { if (key == null) { throw new NullPointerException("You attempted to put a null key to the cache"); } if (value == null) { throw new NullPointerException("You attempted to put null data to the cache"); } synchronized (mutex) { try { final long digest = CryptoUtils.getInstance().toDigest(key); final Long indexEntry = indexHashGet(digest, true); final int valueRecordId; final int keyRecordId; final boolean storeFlagSet = setStoreFlag(); byte[] byteKey = null; if (indexEntry == null) { valueRecordId = getValueRS().addRecord(value, 0, value.length); byteKey = RMSKeyUtils.toIndexBytes(key, valueRecordId); keyRecordId = getKeyRS().addRecord(byteKey, 0, byteKey.length); indexHashPut(digest, keyRecordId, valueRecordId); L.i(this, "put(" + key + ") digest=" + Long.toString(digest, 16), "Value added to RMS=" + getValueRS().getName() + " index=" + valueRecordId + " bytes=" + value.length + " keyIndex=" + keyRecordId); } else { valueRecordId = RMSKeyUtils.toValueIndex(indexEntry); getValueRS().setRecord(valueRecordId, value, 0, value.length); L.i(this, "put(" + key + ") digest=" + Long.toString(digest, 16), "Value overwrite to RMS=" + getValueRS().getName() + " index=" + valueRecordId + " bytes=" + value.length); } if (storeFlagSet) { clearStoreFlag(); } rmsByteSize += value.length + (byteKey == null ? 0 : byteKey.length); } catch (RecordStoreFullException e) { L.e(this, "Can not write", "key=" + key, e); throw new FlashFullException("Flash full when adding key: " + key); } catch (RecordStoreException e) { L.e(this, "Can not write", "key=" + key, e); throw new FlashDatabaseException("Can not putData to RMS: " + key + " - " + e); } catch (UnsupportedEncodingException ex) { L.e(this, "Can not write", "key=" + key, ex); throw new FlashDatabaseException("Can not putData to RMS: " + key + " - " + ex); } } } RMSFastCache(final char priority, final FlashCache.StartupTask startupTask); void markLeastRecentlyUsed(final Long digest); static void deleteDataFiles(final char priority); String getKey(final long digest); byte[] get(final long digest, final boolean markAsLeastRecentlyUsed); void put(final String key, final byte[] value); void removeData(final long digest); Enumeration getDigests(); void clear(); long getFreespace(); long getSize(); void close(); String toString(); void maintainDatabase(); }
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenPutNullKey() throws DigestException, FlashDatabaseException { rmsFastCache.put(null, new byte[16]); } @Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenPutNullData() throws DigestException, FlashDatabaseException { rmsFastCache.put("fah", null); }
SortedVector extends Vector { public synchronized void addElement(final Object o) { int insertIndex = size(); for (int i = size() - 1; i >= 0; i--) { if (comparator.compare(o, elementAt(i)) < 0) { insertIndex--; } else { break; } } if (insertIndex == size()) { super.addElement(o); } else { super.insertElementAt(o, insertIndex); } } SortedVector(final Comparator comparator); synchronized void addElement(final Object o); final void insertElementAt(Object o, int index); final void setElementAt(Object o, int index); boolean equals(Object o); int hashCode(); }
@Test public void collectionMaintainsSortOrder() { collection.addElement(2); collection.addElement(1); assertEquals(1, collection.firstElement()); assertEquals(2, collection.lastElement()); } @Test public void duplicatesAreAllowed() { Integer one = new Integer(1); Integer two = new Integer(1); assertNotSame(one, two); assertEquals(one, two); collection.addElement(one); collection.addElement(two); assertEquals(2, collection.size()); } @Test public void integerSequenceOrderIsCorrectTest() { Object o_1 = new Integer(10); Object o_2 = new Integer(20); Object o_3 = new Integer(50); Object o_4 = new Integer(40); Object o_5 = new Integer(30); System.out.println("Collection now " + collection); collection.addElement(o_1); System.out.println("Collection now " + collection); collection.addElement(o_2); System.out.println("Collection now " + collection); collection.addElement(o_3); System.out.println("Collection now " + collection); collection.addElement(o_4); System.out.println("Collection now " + collection); collection.addElement(o_5); System.out.println("Collection now " + collection); Integer[] expected = {new Integer(10), new Integer(20), new Integer(30), new Integer(40), new Integer(50)}; for (int i = 0; i < collection.size(); i++) { assertEquals("sequence test " + (i + 1), expected[i], (Integer) collection.elementAt(i)); } } @Test public void addElementTest() { System.out.println("addElement"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = new Integer(10); Object o_2 = new Integer(1); Object o_3 = new Integer(3); instance.addElement(o_1); instance.addElement(o_2); instance.addElement(o_3); assertEquals("First", o_2, instance.elementAt(0)); assertEquals("Second", o_3, instance.elementAt(1)); assertEquals("Third", o_1, instance.elementAt(2)); } @Test public void sequenceTest() { System.out.println("testSequence"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = new Integer(10); Object o_2 = new Integer(20); Object o_3 = new Integer(50); Object o_4 = new Integer(40); Object o_5 = new Integer(30); instance.addElement(o_1); instance.addElement(o_2); instance.addElement(o_3); instance.addElement(o_4); instance.addElement(o_5); Integer[] expected = {new Integer(10), new Integer(20), new Integer(30), new Integer(40), new Integer(50)}; for (int i = 0; i < instance.size(); i++) { assertEquals("sequence test " + (i + 1), expected[i], (Integer) instance.elementAt(i)); } }
SortedVector extends Vector { public final void insertElementAt(Object o, int index) { throw new IllegalArgumentException("insertElementAt() not supported"); } SortedVector(final Comparator comparator); synchronized void addElement(final Object o); final void insertElementAt(Object o, int index); final void setElementAt(Object o, int index); boolean equals(Object o); int hashCode(); }
@Test public void insertElementAtTest() { System.out.println("insertElementAt"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = null; int index_1 = 0; try { instance.insertElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testInsertElementAt() should throw an exception."); }
SortedVector extends Vector { public final void setElementAt(Object o, int index) { throw new IllegalArgumentException("setElementAt() not supported"); } SortedVector(final Comparator comparator); synchronized void addElement(final Object o); final void insertElementAt(Object o, int index); final void setElementAt(Object o, int index); boolean equals(Object o); int hashCode(); }
@Test public void setElementAtTest() { System.out.println("setElementAt"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = null; int index_1 = 0; try { instance.setElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testSetElementAt() should throw an exception."); }
CryptoUtils { public synchronized long toDigest(final String key) throws DigestException, UnsupportedEncodingException { if (key == null) { throw new NullPointerException("You attempted to convert a null string into a hash digest"); } final byte[] bytes = key.getBytes("UTF-8"); return toDigest(bytes); } private CryptoUtils(); static CryptoUtils getInstance(); synchronized long toDigest(final String key); synchronized long toDigest(final byte[] bytes); long bytesToLong(final byte[] bytes, final int start); byte[] longToBytes(final long l); void longToBytes(final long l, final byte[] bytes, final int start); static final int DIGEST_LENGTH; }
@Test public void boodleLongsAreNotTheSameTest() throws DigestException, UnsupportedEncodingException { assertNotEquals("boodle is not a url", cryptoUtils.toDigest(imageUrl1), cryptoUtils.toDigest(boodle)); } @Test public void almostSameLongsAreNotTheSameTest() throws DigestException, UnsupportedEncodingException { assertNotEquals(cryptoUtils.toDigest(imageUrl1), cryptoUtils.toDigest(imageUrl2)); } @Test public void statelessSequenceTest() throws DigestException, UnsupportedEncodingException { long l = cryptoUtils.toDigest(imageUrl2); cryptoUtils.toDigest("wahhh"); assertEquals(l, cryptoUtils.toDigest(imageUrl2)); } @Test public void magicValueTest() throws DigestException, UnsupportedEncodingException { assertEquals(1683574533465955905l, cryptoUtils.toDigest(imageUrl3)); } @Test public void magicValuesAreNotTheSameTest() throws DigestException, UnsupportedEncodingException { assertNotEquals(cryptoUtils.toDigest(imageUrl1), cryptoUtils.toDigest(imageUrl3)); } @Test public void spaceIsNotEqualEmptyStringTest() throws DigestException, UnsupportedEncodingException { assertNotEquals(cryptoUtils.toDigest(" "), cryptoUtils.toDigest("")); } @Test(expected = NullPointerException.class) public void nullStringTest() throws DigestException, UnsupportedEncodingException { cryptoUtils.toDigest((String) null); } @Test(expected = NullPointerException.class) public void nullByteArrayTest() throws DigestException, UnsupportedEncodingException { cryptoUtils.toDigest((byte[]) null); }
LengthLimitedVector extends Vector { public synchronized void addElement(final Object o) { if (maxLength == 0) { throw new IllegalArgumentException("Max length of LRU vector is currently 0, can not add: " + o); } super.addElement(o); if (size() > maxLength) { final Object extra = firstElement(); removeElementAt(0); lengthExceeded(extra); } } LengthLimitedVector(final int maxLength); synchronized void addElement(final Object o); synchronized final boolean isLengthExceeded(); boolean markAsExtra(final Object o); synchronized void setMaxLength(final int maxLength); }
@Test public void testAddElement() { System.out.println("addElement"); LengthLimitedVector instance = new LengthLimitedVector(3) { protected void lengthExceeded(Object extra) { tooLong = true; } }; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); instance.addElement("d"); assertEquals("too long test", true, tooLong); }
LengthLimitedVector extends Vector { protected abstract void lengthExceeded(Object extra); LengthLimitedVector(final int maxLength); synchronized void addElement(final Object o); synchronized final boolean isLengthExceeded(); boolean markAsExtra(final Object o); synchronized void setMaxLength(final int maxLength); }
@Test public void testLengthExceeded() { System.out.println("lengthExceeded"); LengthLimitedVector instance = new LengthLimitedVector(3) { protected void lengthExceeded(Object o) { } }; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); assertEquals("Full length", 3, instance.size()); instance.addElement("d"); assertEquals("Max length", 3, instance.size()); assertEquals("LRU after length exceeded", "b", instance.firstElement()); }
RollingAverage { public float value() { return average; } RollingAverage(final int windowLength, final float initialValue); void setUpperBound(final float upperBound); void setLowerBound(final float lowerBound); float value(); float update(final float value); float reset(final float value); }
@Test public void firstGet() { RollingAverage rollingAverage = new RollingAverage(10, 10.0f); assertEquals(10.f, rollingAverage.value(), 0.000001f); }
RMSFastCache extends FlashCache { public byte[] get(final long digest, final boolean markAsLeastRecentlyUsed) throws FlashDatabaseException { synchronized (mutex) { final Long dig = new Long(digest); final Long hashValue = ((Long) indexHash.get(dig, markAsLeastRecentlyUsed)); if (hashValue != null) { try { final int valueIndex = RMSKeyUtils.toValueIndex(hashValue); final byte[] bytes = getValueRS().getRecord(valueIndex); return bytes; } catch (Exception ex) { throw new FlashDatabaseException("Can not getData from RMS: " + Long.toString(digest, 16) + " - " + ex); } } return null; } } RMSFastCache(final char priority, final FlashCache.StartupTask startupTask); void markLeastRecentlyUsed(final Long digest); static void deleteDataFiles(final char priority); String getKey(final long digest); byte[] get(final long digest, final boolean markAsLeastRecentlyUsed); void put(final String key, final byte[] value); void removeData(final long digest); Enumeration getDigests(); void clear(); long getFreespace(); long getSize(); void close(); String toString(); void maintainDatabase(); }
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenGetNullString() throws DigestException, FlashDatabaseException { rmsFastCache.get((String) null); }
WeakHashCache { public synchronized boolean remove(final Object key) { if (key != null) { return hash.remove(key) != null; } L.i(this, "WeakHashCache", "remove() with null key"); return false; } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testRemove() { System.out.println("remove"); WeakHashCache instance = new WeakHashCache(); String key1 = ""; String key2 = "a"; instance.remove(null); instance.remove(key1); instance.put(key1, "fruit"); instance.put(key2, "cake"); instance.remove(key1); instance.remove(key2); assertEquals(instance.size(), 0); }
WeakHashCache { public synchronized void put(final Object key, final Object value) { if (key == null) { throw new NullPointerException("null key put to WeakHashCache"); } if (value == null) { throw new IllegalArgumentException("null value put to WeakHashCache"); } hash.put(key, new WeakReference(value)); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testPut() { System.out.println("put"); WeakHashCache instance = new WeakHashCache(); String key1 = ""; String key2 = "a"; String expectedVal1 = "fruit"; instance.put(key1, expectedVal1); instance.put(key2, "cake"); try { instance.put(null, "dog"); fail("Did not catch null key put to WeakHashCache"); } catch (Exception e) { } assertEquals(instance.size(), 2); for (int i = 0; i < 10000; i++) { instance.put("keykeykey" + i, "valuevaluevalue" + i); } Object val1 = instance.get(key1); if (val1 != null) { assertEquals(val1, expectedVal1); } } @Test(expected = IllegalArgumentException.class) public void testPutNullValue() { WeakHashCache instance = new WeakHashCache(); instance.put("aKey", null); } @Test(expected = NullPointerException.class) public void testPutNullKey() { WeakHashCache instance = new WeakHashCache(); instance.put(null, "aValue"); }
WeakHashCache { public synchronized Object get(final Object key) { if (key == null) { throw new NullPointerException("Attempt to get(null) from WeakHashCache"); } final WeakReference reference = (WeakReference) hash.get(key); if (reference == null) { return null; } return reference.get(); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testGet() { System.out.println("get"); WeakHashCache instance = new WeakHashCache(); String key1 = "11"; String key2 = "22"; Object value1 = "chocolate"; Object value2 = "cake"; Object result_1 = instance.get(key1); assertNull("get null", result_1); instance.put(key1, value1); instance.put(key2, value2); assertEquals("get val 1", value1, instance.get(key1)); assertEquals("get val 2", value2, instance.get(key2)); }
WeakHashCache { public synchronized boolean containsKey(final Object key) { if (key == null) { throw new NullPointerException("containsKey() with null key"); } return hash.containsKey(key); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testContainsKey() { System.out.println("containsKey"); WeakHashCache instance = new WeakHashCache(); String key1 = "11"; String key2 = "22"; Object value1 = "chocolate"; Object value2 = "cake"; instance.put(key1, value1); instance.put(key2, value2); assertEquals(false, instance.containsKey("red")); assertEquals(true, instance.containsKey(key1)); try { instance.containsKey(null); fail("Did not throw exception on containsKey(null)"); } catch (Exception e) { } }
WeakHashCache { public synchronized int size() { return hash.size(); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testSize() { System.out.println("size"); WeakHashCache instance = new WeakHashCache(); final int length = 10000; for (int i = 0; i < length; i++) { instance.put("keykeykey" + i, "valuevaluevalue" + i); } assertEquals(length, instance.size()); }
WeakHashCache { public synchronized void clear() { hash.clear(); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }
@Test public void testClear() { System.out.println("size"); WeakHashCache instance = new WeakHashCache(); final int length = 10000; for (int i = 0; i < length; i++) { instance.put(VALUE_CONSTANT + i, "valuevaluevalue" + i); } assertEquals(length, instance.size()); instance.clearValues(); assertEquals(length, instance.size()); for (int i = 0; i < length; i++) { String key = (String) KEY_CONSTANT + i; assertEquals(null, instance.get(key)); } }
JSONModel { public synchronized void setJSON(final String json) throws JSONException { if (json == null) { throw new NullPointerException("Can not setJSON(null): " + this); } jsonObject = new JSONObject(json); } JSONModel(); JSONModel(final String json); synchronized void setJSON(final String json); synchronized boolean getBoolean(final String key); synchronized String getString(final String key); synchronized double getDouble(final String key); synchronized int getInt(final String key); synchronized long getLong(final String key); synchronized JSONObject take(); }
@Test public void basicModelTest() throws JSONException { JSONModel model = new JSONModel(); model.setJSON(SAMPLE_DATA); } @Test public void oddParsingOfTheModel() throws IOException, JSONException { final JSONModel jsonModel = new JSONModel(); jsonModel.setJSON(SAMPLE_DATA); }
LRUVector extends Vector { public void setElementAt(Object o, int index) { throw new IllegalArgumentException("setElementAt() not allowed on LRUVector"); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }
@Test public void testSetElementAt() { System.out.println("setElementAt"); LRUVector instance = new LRUVector(); Object o_1 = null; int index_1 = 0; try { instance.setElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testSetElementAt() should throw an exception."); }
RSSModel extends XMLModel { protected synchronized void parseElement(final String qname, final String chars, final XMLAttributes attributes) { try { if (currentItem != null) { if (qname.equals("title")) { currentItem.setTitle(chars); } else if (qname.equals("description")) { currentItem.setDescription(chars); } else if (qname.equals("link")) { currentItem.setLink(chars); } else if (qname.equals("pubDate")) { currentItem.setPubDate(chars); } else if (qname.equals("media:thumbnail")) { currentItem.setThumbnail((String) attributes.getValue("url")); } } } catch (Exception e) { L.e("RSS parsing error", "qname=" + qname + " - chars=" + chars, e); } } RSSModel(final int maxLength); synchronized void startElement(final String uri, final String localName, final String qName, final Attributes attributes); synchronized void endElement(final String uri, final String localName, final String qname); synchronized void removeAllElements(); synchronized int size(); synchronized RSSItem elementAt(final int i); final synchronized RSSItem[] copy(RSSItem[] copy); synchronized RSSItem itemNextTo(final RSSItem item, final boolean before); String toString(); }
@Test public void testParseElement() throws SAXException { instance.setXML(xml); assertEquals("rss size", 86, instance.size()); }
HttpGetter extends Task { public Object exec(final Object in) throws InterruptedException { LOR out = null; if (Task.isShuttingDown()) { L.i("Attempt to run HttpGetter during shutdown", "ignored"); setRetriesRemaining(0); cancel("Attempt to run HttpGetter during shutdown"); return out; } if (!(in instanceof String) || ((String) in).indexOf(':') <= 0) { final String s = "HTTP operation was passed a bad url=" + in + ". Check calling method or previous chained task: " + this; cancel(s); return out; } startTime = staggerHeaderStartTime(); String url = keyIncludingPostDataHashtoUrl((String) in); final Integer netActivityKey = new Integer(hashCode()); HttpGetter.networkActivity(netActivityKey); final String userAgent = HttpGetter.getUserAgent(); if (userAgent != null) { this.setRequestProperty(USER_AGENT, userAgent); } L.i(this, "Start", url); ByteArrayOutputStream bos = null; PlatformUtils.HttpConn httpConn = null; boolean tryAgain = false; boolean success = false; addUpstreamDataCount(url.length()); try { final OutputStream outputStream; if (this instanceof HttpPoster) { if (postMessage == null && streamWriter == null) { throw new NullPointerException("null HTTP POST- did you forget to call httpPoster.setMessage(byte[]) ? : " + url); } httpConn = PlatformUtils.getInstance().getHttpPostConn(url, requestPropertyKeys, requestPropertyValues, postMessage); outputStream = httpConn.getOutputStream(); final StreamWriter writer = this.streamWriter; if (writer != null) { writer.writeReady(outputStream); success = true; } addUpstreamDataCount(postMessage.length); } else { httpConn = PlatformUtils.getInstance().getHttpGetConn(url, requestPropertyKeys, requestPropertyValues); } final InputStream inputStream = httpConn.getInputStream(); final StreamReader reader = streamReader; if (reader != null) { reader.readReady(inputStream); success = true; } for (int i = 0; i < requestPropertyKeys.size(); i++) { addUpstreamDataCount(((String) requestPropertyKeys.elementAt(i)).length()); addUpstreamDataCount(((String) requestPropertyValues.elementAt(i)).length()); } final int length = (int) httpConn.getLength(); final int downstreamDataHeaderLength; synchronized (this) { responseCode = httpConn.getResponseCode(); httpConn.getResponseHeaders(responseHeaders); downstreamDataHeaderLength = PlatformUtils.responseHeadersToString(responseHeaders).length(); } addDownstreamDataCount(downstreamDataHeaderLength); long firstByteTime = Long.MAX_VALUE; if (length == 0) { L.i(this, "Exec", "No response. Stream is null, or length is 0"); } else if (length > httpConn.getMaxLengthSupportedAsBlockOperation()) { cancel("Http server sent Content-Length > " + httpConn.getMaxLengthSupportedAsBlockOperation() + " which might cause out-of-memory on this platform"); } else if (length > 0 && HttpGetter.netActivityListenerDelegate.isEmpty()) { final byte[] bytes = new byte[length]; firstByteTime = readBytesFixedLength(url, inputStream, bytes); out = new LOR(bytes); } else { bos = new ByteArrayOutputStream(OUTPUT_BUFFER_INITIAL_LENGTH); firstByteTime = readBytesVariableLength(inputStream, bos, netActivityKey); out = new LOR(bos.toByteArray()); } if (firstByteTime != Long.MAX_VALUE) { final long responseTime = firstByteTime - startTime; HttpGetter.averageResponseDelayMillis.update(responseTime); L.i(this, "Average HTTP header response time", HttpGetter.averageResponseDelayMillis.value() + " current=" + responseTime); } final long lastByteTime = System.currentTimeMillis(); final float baud; int dataLength = 0; if (out != null) { dataLength = out.getBytes().length; } if (dataLength > 0 && lastByteTime > firstByteTime) { baud = (dataLength * 8 * 1000) / ((int) (lastByteTime - firstByteTime)); } else { baud = THRESHOLD_BAUD * 2; } HttpGetter.averageBaud.update(baud); L.i(this, "Average HTTP body read baud", HttpGetter.averageBaud.value() + " current=" + baud); if (out != null) { addDownstreamDataCount(dataLength); L.i(this, "End read", "url=" + url + " bytes=" + dataLength); } synchronized (this) { success = checkResponseCode(url, responseCode, responseHeaders); } L.i(this, "Response", "HTTP response code indicates success=" + success); } catch (IllegalArgumentException e) { L.e(this, "HttpGetter has illegal argument", url, e); throw e; } catch (NullPointerException e) { L.e(this, "HttpGetter has null pointer", url, e); throw e; } catch (IOException e) { if (responseCode == HTTP_301_MOVED_PERMANENTLY || responseCode == HTTP_302_FOUND) { Object locations = responseHeaders.get("Location"); if (locations != null) { if (((String[]) locations).length > 0) { String newUrl = ((String[])locations)[0]; L.i(this, "Response", "HTTP response code indicates a redirect, new url=" + newUrl); url = newUrl; tryAgain = true; success = true; } } } L.e(this, "Retries remaining", url + ", retries=" + retriesRemaining, e); if (retriesRemaining > 0) { retriesRemaining--; tryAgain = true; } else if (!tryAgain) { L.i(this, "No more retries", url); cancel("No more retries"); } } finally { if (httpConn != null) { try { httpConn.close(); } catch (IOException e) { L.e("Closing Http InputStream error", url, e); } httpConn = null; } bos = null; if (tryAgain && status == Task.PENDING) { Thread.sleep(HTTP_RETRY_DELAY); } else if (!success) { L.i("HTTP GET FAILED: about to HttpGetter.cancel() this and any chained Tasks", this.toString()); cancel("HttpGetter failed response code and header check: " + this); } L.i(this, "End", url + " status=" + getStatus() + " out=" + (out == null ? "null" : "(" + out.getBytes().length + " bytes)")); HttpGetter.endNetworkActivity(netActivityKey); } if (!success) { if (!isCanceled() && this.retriesRemaining <= 0) { cancel("HttpGetter did not succeed"); } return null; } return out; } HttpGetter(final int priority); HttpGetter(final int priority, final String url); HttpGetter(final String url); static synchronized void setUserAgent(final String userAgent); static synchronized String getUserAgent(); static long staggerHeaderStartTime(); long getStartTime(); StreamWriter getWriter(); void setWriter(final StreamWriter writer); StreamReader getReader(); void setReader(final StreamReader reader); Task setRetriesRemaining(final int retries); synchronized int getResponseCode(); synchronized Hashtable getResponseHeaders(); synchronized void setRequestProperty(final String key, final String value); Object exec(final Object in); boolean cancel(final String reason, final Throwable t); synchronized static int getDownstreamDataCount(); synchronized static int getUpstreamDataCount(); synchronized static void clearDownstreamDataCount(); synchronized static void clearUpstreamDataCount(); synchronized String toString(); static void registerNetActivityListener(final NetActivityListener listener); static void unregisterNetActivityListener(final NetActivityListener listener); static void networkActivity(final Integer key); static void endNetworkActivity(final Integer key); static void setNetActivityListenerTimeout(final int inactiveTimeoutInMilliseconds); static final String HTTP_GET; static final String HTTP_HEAD; static final String HTTP_POST; static final String HTTP_PUT; static final String HTTP_DELETE; static final String HTTP_TRACE; static final String HTTP_CONNECT; static final int HTTP_100_CONTINUE; static final int HTTP_101_SWITCHING_PROTOCOLS; static final int HTTP_102_PROCESSING; static final int HTTP_200_OK; static final int HTTP_201_CREATED; static final int HTTP_202_ACCEPTED; static final int HTTP_203_NON_AUTHORITATIVE_INFORMATION; static final int HTTP_204_NO_CONTENT; static final int HTTP_205_RESET_CONTENT; static final int HTTP_206_PARTIAL_CONTENT; static final int HTTP_207_MULTI_STATUS; static final int HTTP_208_ALREADY_REPORTED; static final int HTTP_250_LOW_ON_STORAGE_SPACE; static final int HTTP_226_IM_USED; static final int HTTP_300_MULTIPLE_CHOICES; static final int HTTP_301_MOVED_PERMANENTLY; static final int HTTP_302_FOUND; static final int HTTP_303_SEE_OTHER; static final int HTTP_304_NOT_MODIFIED; static final int HTTP_305_USE_PROXY; static final int HTTP_306_SWITCH_PROXY; static final int HTTP_307_TEMPORARY_REDIRECT; static final int HTTP_308_PERMANENT_REDIRECT; static final int HTTP_400_BAD_REQUEST; static final int HTTP_401_UNAUTHORIZED; static final int HTTP_402_PAYMENT_REQUIRED; static final int HTTP_403_FORBIDDEN; static final int HTTP_404_NOT_FOUND; static final int HTTP_405_METHOD_NOT_ALLOWED; static final int HTTP_406_NOT_ACCEPTABLE; static final int HTTP_407_PROXY_AUTHENTICATION_REQUIRED; static final int HTTP_408_REQUEST_TIMEOUT; static final int HTTP_409_CONFLICT; static final int HTTP_410_GONE; static final int HTTP_411_LENGTH_REQUIRED; static final int HTTP_412_PRECONDITION_FAILED; static final int HTTP_413_REQUEST_ENTITY_TOO_LARGE; static final int HTTP_414_REQUEST_URI_TOO_LONG; static final int HTTP_415_UNSUPPORTED_MEDIA_TYPE; static final int HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE; static final int HTTP_417_EXPECTATION_FAILED; static final int HTTP_418_IM_A_TEAPOT; static final int HTTP_420_ENHANCE_YOUR_CALM; static final int HTTP_422_UNPROCESSABLE_ENTITY; static final int HTTP_423_LOCKED; static final int HTTP_424_FAILED_DEPENDENCY; static final int HTTP_424_METHOD_FAILURE; static final int HTTP_425_UNORDERED_COLLECTION; static final int HTTP_426_UPGRADE_REQUIRED; static final int HTTP_428_PRECONDITION_REQUIRED; static final int HTTP_429_TOO_MANY_REQUESTS; static final int HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE; static final int HTTP_444_NO_RESPONSE; static final int HTTP_449_RETRY_WITH; static final int HTTP_450_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS; static final int HTTP_451_PARAMETER_NOT_UNDERSTOOD; static final int HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS; static final int HTTP_451_REDIRECT; static final int HTTP_452_CONFERENCE_NOT_FOUND; static final int HTTP_453_NOT_ENOUGH_BANDWIDTH; static final int HTTP_454_SESSION_NOT_FOUND; static final int HTTP_455_METHOD_NOT_VALID_IN_THIS_STATE; static final int HTTP_456_HEADER_FIELD_NOT_VALID_FOR_RESOURCE; static final int HTTP_457_INVALID_RANGE; static final int HTTP_458_PARAMETER_IS_READ_ONLY; static final int HTTP_459_AGGREGATE_OPERATION_NOT_ALLOWED; static final int HTTP_460_ONLY_AGGREGATE_OPERATION_ALLOWED; static final int HTTP_461_UNSUPPORTED_TRANSPORT; static final int HTTP_462_DESTINATION_UNREACHABLE; static final int HTTP_494_REQUEST_HEADER_TOO_LARGE; static final int HTTP_495_CERT_ERROR; static final int HTTP_496_NO_CERT; static final int HTTP_497_HTTP_TO_HTTPS; static final int HTTP_499_CLIENT_CLOSED_REQUEST; static final int HTTP_500_INTERNAL_SERVER_ERROR; static final int HTTP_501_NOT_IMPLEMENTED; static final int HTTP_502_BAD_GATEWAY; static final int HTTP_503_SERVICE_UNAVAILABLE; static final int HTTP_504_GATEWAY_TIMEOUT; static final int HTTP_505_HTTP_VERSION_NOT_SUPPORTED; static final int HTTP_506_VARIANT_ALSO_NEGOTIATES; static final int HTTP_507_INSUFFICIENT_STORAGE; static final int HTTP_508_LOOP_DETECTED; static final int HTTP_509_BANDWIDTH_LIMIT_EXCEEDED; static final int HTTP_510_NOT_EXTENDED; static final int HTTP_511_NETWORK_AUTHENTICATION_REQUIRED; static final int HTTP_550_PERMISSION_DENIED; static final int HTTP_551_OPTION_NOT_SUPPORTED; static final int HTTP_598_NETWORK_READ_TIMEOUT_ERROR; static final int HTTP_599_NETWORK_CONNECT_TIMEOUT_ERROR; static final String USER_AGENT; static final int HTTP_OPERATION_PENDING; static final float THRESHOLD_BAUD; static final RollingAverage averageResponseDelayMillis; static final RollingAverage averageBaud; }
@Test public void canceledWhenNonStringKey() throws InterruptedException { getter.exec(new Object()); assertEquals("Getter was not correctly cancelled for non-String url", getter.getStatus(), Task.CANCELED); }
Task { public final Task fork() { return Worker.fork(this); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShuttingDown(); static boolean isShutdownComplete(); static Timer getTimer(); void unchain(); final Object get(); final Task set(final Object value); final Task fork(); static Task[] fork(final Task[] tasks); final Object join(); final Object join(long timeout); static void joinAll(final Task[] tasks); static void joinAll(final Task[] tasks, final long timeout); final int getStatus(); final String getStatusString(); final Task chain(final Task nextTask); final int getForkPriority(); final boolean cancel(final String reason); boolean cancel(final String reason, final Throwable t); final boolean isCanceled(); static String getClassName(final Object o); String getClassName(); Task setClassName(final String name); static Vector getCurrentState(); String toString(); static final int DEDICATED_THREAD_PRIORITY; static final int UI_PRIORITY; static final int FASTLANE_PRIORITY; static final int SERIAL_CURRENT_THREAD_PRIORITY; static final int SERIAL_PRIORITY; static final int HIGH_PRIORITY; static final int NORMAL_PRIORITY; static final int IDLE_PRIORITY; static final int SHUTDOWN_UI; static final int SHUTDOWN; static final Object LARGE_MEMORY_MUTEX; static final int MAX_TIMEOUT; static final int PENDING; static final int FINISHED; static final int CANCELED; static final String QUEUE_LENGTH_EXCEEDED; }
@Test public void testFork() { System.out.println("fork"); Task instance = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { return "run"; } }; Task result_1 = instance.fork(); assertEquals(instance, result_1); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } try { assertEquals("run", (String) instance.get()); } catch (Exception ex) { ex.printStackTrace(); fail("Can not get() : " + ex); } }
Task { public final Object join() throws CancellationException, TimeoutException { return join(MAX_TIMEOUT); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShuttingDown(); static boolean isShutdownComplete(); static Timer getTimer(); void unchain(); final Object get(); final Task set(final Object value); final Task fork(); static Task[] fork(final Task[] tasks); final Object join(); final Object join(long timeout); static void joinAll(final Task[] tasks); static void joinAll(final Task[] tasks, final long timeout); final int getStatus(); final String getStatusString(); final Task chain(final Task nextTask); final int getForkPriority(); final boolean cancel(final String reason); boolean cancel(final String reason, final Throwable t); final boolean isCanceled(); static String getClassName(final Object o); String getClassName(); Task setClassName(final String name); static Vector getCurrentState(); String toString(); static final int DEDICATED_THREAD_PRIORITY; static final int UI_PRIORITY; static final int FASTLANE_PRIORITY; static final int SERIAL_CURRENT_THREAD_PRIORITY; static final int SERIAL_PRIORITY; static final int HIGH_PRIORITY; static final int NORMAL_PRIORITY; static final int IDLE_PRIORITY; static final int SHUTDOWN_UI; static final int SHUTDOWN; static final Object LARGE_MEMORY_MUTEX; static final int MAX_TIMEOUT; static final int PENDING; static final int FINISHED; static final int CANCELED; static final String QUEUE_LENGTH_EXCEEDED; }
@Test(expected = TimeoutException.class) public void taskTimesOutIfJoinedBeforeFork() throws CancellationException, TimeoutException { Task instance = new Task(Task.FASTLANE_PRIORITY, "white") { protected Object exec(Object in) { System.out.println("Executing task 1"); return (String) in + " rabbit"; } }; instance.join(100); fail("join() or get() to a Task that was not fork()ed should timeout"); }
Task { protected void onCanceled(final String reason) { L.i(this, "default Task.onCanceled() - this method was not overridden: cancellationReason=" + reason, this.toString()); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShuttingDown(); static boolean isShutdownComplete(); static Timer getTimer(); void unchain(); final Object get(); final Task set(final Object value); final Task fork(); static Task[] fork(final Task[] tasks); final Object join(); final Object join(long timeout); static void joinAll(final Task[] tasks); static void joinAll(final Task[] tasks, final long timeout); final int getStatus(); final String getStatusString(); final Task chain(final Task nextTask); final int getForkPriority(); final boolean cancel(final String reason); boolean cancel(final String reason, final Throwable t); final boolean isCanceled(); static String getClassName(final Object o); String getClassName(); Task setClassName(final String name); static Vector getCurrentState(); String toString(); static final int DEDICATED_THREAD_PRIORITY; static final int UI_PRIORITY; static final int FASTLANE_PRIORITY; static final int SERIAL_CURRENT_THREAD_PRIORITY; static final int SERIAL_PRIORITY; static final int HIGH_PRIORITY; static final int NORMAL_PRIORITY; static final int IDLE_PRIORITY; static final int SHUTDOWN_UI; static final int SHUTDOWN; static final Object LARGE_MEMORY_MUTEX; static final int MAX_TIMEOUT; static final int PENDING; static final int FINISHED; static final int CANCELED; static final String QUEUE_LENGTH_EXCEEDED; }
@Ignore @Test public void onCanceledTest() { System.out.println("onCanceled"); final Vector v = new Vector(); v.addElement("Dummy"); final Task instance = new Task(Task.HIGH_PRIORITY) { @Override protected Object exec(Object in) { try { Thread.sleep(200); fail("testOnCanceled() Task instance should have been interrupted"); } catch (InterruptedException ex) { } return in; } @Override protected void onCanceled(String reason) { v.insertElementAt("canceled-" + reason, 0); } }; instance.fork(); try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } instance.cancel("testing"); try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } assertEquals("canceled-testing", (String) v.firstElement()); }
LRUVector extends Vector { public void insertElementAt(Object o, int index) { throw new IllegalArgumentException("insertElementAt() not allowed on LRUVector"); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }
@Test public void testInsertElementAt() { System.out.println("setElementAt"); LRUVector instance = new LRUVector(); Object o_1 = null; int index_1 = 0; try { instance.insertElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testInsertElementAt() should throw an exception."); }
LRUVector extends Vector { public synchronized void addElement(Object o) { removeElement(o); super.addElement(o); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }
@Test public void testAddElement() { System.out.println("addElement"); LRUVector instance = new LRUVector(); Object o_1 = "a"; Object o_2 = "b"; instance.addElement(o_1); assertEquals("Size 1", 1, instance.size()); instance.addElement(o_2); assertEquals("Size 2", 2, instance.size()); instance.addElement(o_1); assertEquals("Size 2 again", 2, instance.size()); }
LRUVector extends Vector { public synchronized Object removeLeastRecentlyUsed() { final Object o = getLeastRecentlyUsed(); if (o != null) { removeElement(o); } return o; } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }
@Test public void testRemoveLeastRecentlyUsed() { System.out.println("removeLeastRecentlyUsed"); LRUVector instance = new LRUVector(); Object expResult_1 = true; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); instance.addElement("d"); instance.addElement("e"); instance.addElement("f"); Object result_1 = instance.contains("a"); assertEquals("Least recently used", expResult_1, result_1); instance.addElement("a"); instance.contains("b"); Object result_2 = instance.removeLeastRecentlyUsed(); assertEquals("Least recently used", "c", result_2); }
CustomerController { @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) public void createCustomer(@Valid @RequestBody Customer customer) { log.debug("Creating customer {}", customer); customerRepository.save(customer); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }
@Test public void testCreateCustomer() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/customer").content(CUSTOMER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); }
ProductController { @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") public Product findOne(@PathVariable("productId") Long productId) { return productRepository.findOne(productId); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }
@Test public void testFindOne() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.get("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content() .json("{}")); }
AccountEntry { public BigDecimal getTotalAmount() { return price.multiply(BigDecimal.valueOf(quantity)); } BigDecimal getTotalAmount(); }
@Test public void testTotalAmount() throws Exception { AccountEntry entry = new AccountEntry().setPrice(BigDecimal.ONE).setQuantity(12l); assertThat(entry.getTotalAmount(), is(equalTo(new BigDecimal("12")))); }
StockService { public Long registerStock(String stockName) { return stockRepository.save(new Stock().setName(stockName)).getId(); } Long registerStock(String stockName); List<Stock> findAllStocks(); Stock findStock(Long stockId); List<StockEntryQuantity> quantityOfAvailableProducts(Long stockId); void put(Long stockId, Long productId, Long quantity, double price); List<StockEntryResponse> pull(Long stockId, Long productId, Long quantity); }
@Test public void testRegisterStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); assertThat(stockId, is(notNullValue())); }
StockService { public Stock findStock(Long stockId) { return stockRepository.findOne(stockId); } Long registerStock(String stockName); List<Stock> findAllStocks(); Stock findStock(Long stockId); List<StockEntryQuantity> quantityOfAvailableProducts(Long stockId); void put(Long stockId, Long productId, Long quantity, double price); List<StockEntryResponse> pull(Long stockId, Long productId, Long quantity); }
@Test public void testFindStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); Stock stock = stockService.findStock(stockId); assertThat(stock.getName(), is(STOCKNAME)); }
StockController { @ApiOperation("Get stock") @GetMapping(path = "/{stockId}") public StockInfo getStock(@PathVariable("stockId") Long stockId) { Stock stock = stockService.findStock(stockId); return new StockInfo(stock.getId(),stock.getName()); } @ApiOperation("Get all stocks") @GetMapping List<StockInfo> getStocks(); @ApiOperation("Create new stock") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createStock(@RequestBody @Valid StockRegisterRequest stockRegisterRequest); @ApiOperation("Get stock") @GetMapping(path = "/{stockId}") StockInfo getStock(@PathVariable("stockId") Long stockId); @ApiOperation("Get available product quantities") @GetMapping(path = "/{stockId}/entries") List<StockEntryQuantity> getAvailableProductQuantities(@PathVariable("stockId") Long stockId); @ApiOperation("Receipt products") @PutMapping(path = "/{stockId}/entries") void putToStock(@PathVariable("stockId") Long stockId, @RequestBody @Valid EntryReceiptRequest entry); @ApiOperation("Pull product from stock.") @PostMapping(path = "/{stockId}/entries") List<StockEntryResponse> getPull(@PathVariable("stockId") Long stockId, @RequestBody @Valid EntryPullRequest entryPullRequest); }
@Test public void testGetStock() throws Exception { when(stockService.findStock(1l)).thenReturn(buildPersistentStock()); mvc.perform(MockMvcRequestBuilders.get("/stock/{stockId}", 1l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json("{\"stockId\":1,\"name\":\"STOCK_NAME\"}s")); verify(stockService, times(1)).findStock(1l); }
CustomerController { @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") public Customer findCustomer(@PathVariable("customerId") long customerId) { return customerRepository.findOne(customerId); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }
@Test public void testFindCustomer() throws Exception { when(customerRepository.findOne(anyLong())) .thenReturn(CustomerFixture.buildDefaultCustomer()); mvc.perform(MockMvcRequestBuilders.get("/customer/{customerId}", 5l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content() .json(CUSTOMER_JSON)); }
CustomerController { @ApiOperation("Find all customers.") @GetMapping public List<Customer> findAll() { return customerRepository.findAll(); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }
@Test public void testFindAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/customer") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content() .json("[]")); }
CustomerController { @ApiOperation("Update customer") @PutMapping("/{customerId}") public Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer) { final Customer customerModel = customerRepository.findOne(customerId); customerModel.setName(customer.getName()); customerModel.setAddress(customer.getAddress()); customerModel.setEmail(customer.getEmail()); log.debug("Saving customer {}", customerModel); return customerRepository.save(customerModel); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }
@Test public void testUpdateCustomer() throws Exception { when(customerRepository.findOne(anyLong())) .thenReturn(CustomerFixture.buildDefaultCustomer()); mvc.perform(MockMvcRequestBuilders.put("/customer/{customerId}", 5l).content(CUSTOMER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); }
UserController { @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) public void createUser(@Valid @RequestBody User user) { userRepository.save(user); } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createUser(@Valid @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }
@Test public void testCreateUser() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/user").content(USER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); }
UserController { @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) public void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest) { User user = userRepository.findOne(userId); if (user != null) { if (user.getPassword().equals(passwordRequest.getOldPassword())) { user.setPassword(passwordRequest.getNewPassword()); userRepository.save(user); } } } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createUser(@Valid @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }
@Test public void testUpdatePassword() throws Exception { User user = UserFixture.buildPersistentUser(); when(userRepository.findOne(2L)) .thenReturn(user); mvc.perform(MockMvcRequestBuilders.put("/user/{userId}/change-password", 2L).content(PASSWORD_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isAccepted()); user.setPassword("ZYX"); verify(userRepository, times(1)) .save(user); }
UserController { @ApiOperation(value = "Find all users.") @GetMapping public List<UserInfo> findAll() { return userRepository .findAll() .stream() .filter(u -> u != null) .map(this::mapToUserInfo).collect(Collectors.toList()); } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createUser(@Valid @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }
@Test public void testFindCustomer() throws Exception { when(userRepository.findAll()) .thenReturn(Arrays.asList(UserFixture.buildDefaultUser(), UserFixture.buildPersistentUser())); mvc.perform(MockMvcRequestBuilders.get("/user", 5l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content() .json(" [{\"id\":null,\"email\":\"[email protected]\",\"name\":\"Name\"},{\"id\":-2,\"email\":\"[email protected]\",\"name\":\"Name2\"}]")); }
ProductController { @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping public void createProduct(@Valid @RequestBody Product product) { productRepository.save(product); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }
@Test public void testCreateProduct() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/product").content(PRODUCT_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); verify(productRepository, times(1)).save(any(Product.class)); }
ProductController { @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") public void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product) { Product entity = productRepository.findOne(productId); if (entity != null) { entity.setName(product.getName()); entity.setDescription(product.getDescription()); entity.setUnit(product.getUnit()); entity.setAmount(product.getAmount()); productRepository.save(entity); } } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }
@Test public void testUpdateProduct() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.put("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(productRepository, times(1)).save(any(Product.class)); }
ProductController { @ApiOperation(value = "Find all products.") @GetMapping public List<Product> findAll() { return productRepository.findAll(); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }
@Test public void testFindAll() throws Exception { when(productRepository.findAll()).thenReturn(Arrays.asList(buildDefaultProduct(), buildPersistentProduct())); mvc.perform(MockMvcRequestBuilders.get("/product") .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content() .json("[{\"id\":null,\"version\":null,\"name\":\"PRODUCT_NAME\",\"description\":\"PRODUCT_DESCRIPTION\",\"unit\":\"Liter\",\"amount\":1.0,\"tags\":[]},{\"id\":-2,\"version\":null,\"name\":\"PRODUCT_NAME_2\",\"description\":\"PRODUCT_DESCRIPTION_2\",\"unit\":\"1L\",\"amount\":123.45,\"tags\":[]}]")); }
PDDocumentCatalogBleach { private void sanitizeAcroFormActions(PDAcroForm acroForm) { if (acroForm == null) { LOGGER.debug("No AcroForms found"); return; } LOGGER.trace("Checking AcroForm Actions"); Iterator<PDField> fields = acroForm.getFieldIterator(); fields.forEachRemaining(this::sanitizeField); } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeAcroFormActions() { PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions(); fieldActions.setC(new PDActionJavaScript()); fieldActions.setF(new PDActionJavaScript()); fieldActions.setK(new PDActionJavaScript()); fieldActions.setV(new PDActionJavaScript()); instance.sanitizeFieldAdditionalActions(fieldActions); assertThreatsFound(session, 4); assertNull(fieldActions.getC()); assertNull(fieldActions.getF()); assertNull(fieldActions.getK()); assertNull(fieldActions.getV()); reset(session); instance.sanitizeFieldAdditionalActions(fieldActions); assertThreatsFound(session, 0); }
MacroRemover extends EntryFilter { @Override public boolean test(Entry entry) { String entryName = entry.getName(); if (!isMacro(entryName)) { return true; } LOGGER.info("Found Macros, removing them."); StringBuilder infos = new StringBuilder(); if (entry instanceof DirectoryEntry) { Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames(); LOGGER.trace("Macros' entries: {}", entryNames); infos.append("Entries: ").append(entryNames); } else if (entry instanceof DocumentEntry) { int size = ((DocumentEntry) entry).getSize(); infos.append("Size: ").append(size); } Threat threat = Threat.builder() .type(ThreatType.ACTIVE_CONTENT) .severity(ThreatSeverity.EXTREME) .action(ThreatAction.REMOVE) .location(entryName) .details(infos.toString()) .build(); session.recordThreat(threat); return false; } MacroRemover(BleachSession session); @Override boolean test(Entry entry); }
@Test void testRemovesMacro() { Entry entry = mock(Entry.class); doReturn("_VBA_PROJECT_CUR").when(entry).getName(); assertFalse(instance.test(entry), "A macro entry should not be copied over"); BleachTestBase.assertThreatsFound(session, 1); reset(session); } @Test void testKeepsEverythingElse() { Entry entry = mock(Entry.class); doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName(); assertTrue(instance.test(entry), "Non-macro streams should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); doReturn("RandomName").when(entry).getName(); assertTrue(instance.test(entry), "Non-macro streams should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); }
MacroRemover extends EntryFilter { protected boolean isMacro(String entryName) { return MACRO_ENTRY.equalsIgnoreCase(entryName) || entryName.contains(VBA_ENTRY); } MacroRemover(BleachSession session); @Override boolean test(Entry entry); }
@Test void recognizesMacros() { assertTrue( instance.isMacro("_VBA_PROJECT_CUR"), "_VBA_PROJECT_CUR is the Excel Macro directory"); assertFalse(instance.isMacro("Nothing"), "Nothing is not a macro. Is-it?"); }
ExcelRecordCleaner { protected static void removeObProjRecord(Collection<Record> records) { new HashSet<>(records) .forEach( record -> { if (!isObProj(record)) { return; } records.remove(record); LOGGER.debug("Found and removed ObProj record: {}", record); }); } }
@Test void removeObProjRecord() { Record valid1 = new UnknownRecord(0x01, new byte[]{}); Record obProj1 = new UnknownRecord(0xD3, new byte[]{}); Record valid2 = new UnknownRecord(0x02, new byte[]{}); Collection<Record> records = new HashSet<>(); records.add(valid1); records.add(obProj1); records.add(valid2); ExcelRecordCleaner.removeObProjRecord(records); assertTrue(records.contains(valid1), "A valid record is not removed"); assertTrue(records.contains(valid2), "A valid record is not removed"); assertFalse(records.contains(obProj1), "The ObProj record is removed"); }
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeSummaryInformation(BleachSession session, DocumentEntry dsiEntry) { if (dsiEntry.getSize() <= 0) { return; } try (DocumentInputStream dis = new DocumentInputStream(dsiEntry)) { PropertySet ps = new PropertySet(dis); SummaryInformation dsi = new SummaryInformation(ps); sanitizeSummaryInformation(session, dsi); } catch (NoPropertySetStreamException | UnexpectedPropertySetTypeException | IOException e) { LOGGER.error("An error occured while trying to sanitize the document entry", e); } } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }
@Test void sanitizeSummaryInformation() { }
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeComments(BleachSession session, SummaryInformation dsi) { String comments = dsi.getComments(); if (comments == null || comments.isEmpty()) { return; } LOGGER.trace("Removing the document's Comments (was '{}')", comments); dsi.removeComments(); Threat threat = Threat.builder() .type(ThreatType.UNRECOGNIZED_CONTENT) .severity(ThreatSeverity.LOW) .action(ThreatAction.REMOVE) .location("Summary Information - Comment") .details("Comment was: '" + comments + "'") .build(); session.recordThreat(threat); } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }
@Test void sanitizeComments() { SummaryInformation si = new SummaryInformation(); instance.sanitizeComments(session, si); assertThreatsFound(session, 0); si.setComments("Hello!"); instance.sanitizeComments(session, si); assertNull(si.getComments()); assertThreatsFound(session, 1); }
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeTemplate(BleachSession session, SummaryInformation dsi) { String template = dsi.getTemplate(); if (NORMAL_TEMPLATE.equals(template)) { return; } if (template == null) { return; } LOGGER.trace("Removing the document's template (was '{}')", template); dsi.removeTemplate(); ThreatSeverity severity = isExternalTemplate(template) ? ThreatSeverity.HIGH : ThreatSeverity.LOW; Threat threat = Threat.builder() .type(ThreatType.EXTERNAL_CONTENT) .severity(severity) .action(ThreatAction.REMOVE) .location("Summary Information - Template") .details("Template was: '" + template + "'") .build(); session.recordThreat(threat); } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }
@Test void sanitizeTemplate() { }
SummaryInformationSanitiser extends EntryFilter { protected boolean isExternalTemplate(String template) { return template.startsWith("http: || template.startsWith("https: || template.startsWith("ftp: } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }
@Test void isExternalTemplate() { assertFalse(instance.isExternalTemplate("Normal.dotm"), "The base template is not external"); assertFalse(instance.isExternalTemplate("my-template.dotm"), "Unknown template"); assertFalse(instance.isExternalTemplate("hxxp: assertTrue(instance.isExternalTemplate("https: assertTrue(instance.isExternalTemplate("http: assertTrue(instance.isExternalTemplate("ftp: }
ObjectRemover extends EntryFilter { @Override public boolean test(Entry entry) { String entryName = entry.getName(); if (!isObject(entryName)) { return true; } LOGGER.info("Found Compound Objects, removing them."); StringBuilder infos = new StringBuilder(); if (entry instanceof DirectoryEntry) { Set<String> entryNames = ((DirectoryEntry) entry).getEntryNames(); LOGGER.trace("Compound Objects' entries: {}", entryNames); infos.append("Entries: ").append(entryNames); } else if (entry instanceof DocumentEntry) { int size = ((DocumentEntry) entry).getSize(); infos.append("Size: ").append(size); } Threat threat = Threat.builder() .type(ThreatType.EXTERNAL_CONTENT) .severity(ThreatSeverity.HIGH) .action(ThreatAction.REMOVE) .location(entryName) .details(infos.toString()) .build(); session.recordThreat(threat); return false; } ObjectRemover(BleachSession session); @Override boolean test(Entry entry); }
@Test void testRemovesMacro() { Entry entry = mock(Entry.class); doReturn("\u0001CompObj").when(entry).getName(); assertFalse(instance.test(entry), "An object entry should not be copied over"); BleachTestBase.assertThreatsFound(session, 1); reset(session); } @Test void testKeepsEverythingElse() { Entry entry = mock(Entry.class); doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName(); assertTrue(instance.test(entry), "Non-object entries should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); doReturn("RandomName").when(entry).getName(); assertTrue(instance.test(entry), "Non-object entries should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); }
PDDocumentCatalogBleach { private void sanitizePageActions(PDPageTree pages) throws IOException { LOGGER.trace("Checking Pages Actions"); for (PDPage page : pages) { sanitizePage(page); } } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizePageActions() { PDPageAdditionalActions actions = new PDPageAdditionalActions(); actions.setC(new PDActionJavaScript()); actions.setO(new PDActionJavaScript()); instance.sanitizePageActions(actions); assertThreatsFound(session, 2); assertNull(actions.getC()); assertNull(actions.getO()); reset(session); instance.sanitizePageActions(actions); assertThreatsFound(session, 0); }
ObjectRemover extends EntryFilter { protected boolean isObject(String entryName) { return OBJECT_POOL_ENTRY.equalsIgnoreCase(entryName) || COMPOUND_OBJECT_ENTRY.equalsIgnoreCase(entryName); } ObjectRemover(BleachSession session); @Override boolean test(Entry entry); }
@Test void recognizesObjects() { assertTrue( instance.isObject("\u0001CompObj"), "u0001CompObj is the Excel Macro directory name"); assertFalse(instance.isObject("Nothing"), "Nothing is not an object. Is-it?"); }
OOXMLBleach implements Bleach { boolean isForbiddenType(ContentType type) { String fullType = type.toString(false); for (String _type : BLACKLISTED_CONTENT_TYPES) { if (_type.equalsIgnoreCase(fullType)) { return true; } } return false; } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); void sanitize(OPCPackage pkg, BleachSession session); }
@Test @Disabled void isForbiddenType() throws InvalidFormatException { ContentType ct; ct = new ContentType("application/postscript"); assertTrue(instance.isForbiddenType(ct)); } @Test @Disabled void noFalsePositiveForbiddenType() throws InvalidFormatException { ContentType ct; for (String contentType : NOT_DYNAMIC_TYPES) { ct = new ContentType(contentType); assertFalse(instance.isForbiddenType(ct), contentType + " should not be a forbidden type"); } } @Test @Disabled void remapsMacroEnabledDocumentType() throws InvalidFormatException { ContentType ct; for (String contentType : DYNAMIC_TYPES) { ct = new ContentType(contentType); assertTrue(instance.isForbiddenType(ct), contentType + " should be a forbidden type"); } }
OOXMLBleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { try { return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OOXML; } catch (Exception e) { LOGGER.warn("An exception occured", e); return false; } } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); void sanitize(OPCPackage pkg, BleachSession session); }
@Test void handlesMagic() throws IOException { Charset cs = Charset.defaultCharset(); InputStream invalidInputStream2 = new ByteArrayInputStream("".getBytes(cs)); assertFalse(instance.handlesMagic(invalidInputStream2)); InputStream invalidInputStream3 = new ByteArrayInputStream("Anything".getBytes(cs)); assertFalse(instance.handlesMagic(invalidInputStream3)); }
PDDocumentCatalogBleach { void sanitizeDocumentActions(PDDocumentCatalogAdditionalActions documentActions) { LOGGER.trace("Checking additional actions..."); if (documentActions.getDP() != null) { LOGGER.debug("Found&removed action after printing (was {})", documentActions.getDP()); documentActions.setDP(null); pdfBleachSession .recordJavascriptThreat("DocumentCatalogAdditionalActions", "Action after printing"); } if (documentActions.getDS() != null) { LOGGER.debug("Found&removed action after saving (was {})", documentActions.getDS()); documentActions.setDS(null); pdfBleachSession .recordJavascriptThreat("DocumentCatalogAdditionalActions", "Action after saving"); } if (documentActions.getWC() != null) { LOGGER.debug("Found&removed action before closing (was {}", documentActions.getWC()); documentActions.setWC(null); pdfBleachSession .recordJavascriptThreat("DocumentCatalogAdditionalActions", "Action before closing"); } if (documentActions.getWP() != null) { LOGGER.debug("Found&removed action before printing (was {})", documentActions.getWP()); documentActions.setWP(null); pdfBleachSession .recordJavascriptThreat("DocumentCatalogAdditionalActions", "Action before printing"); } if (documentActions.getWS() != null) { LOGGER.debug("Found&removed action before saving (was {})", documentActions.getWS()); documentActions.setWS(null); pdfBleachSession .recordJavascriptThreat("DocumentCatalogAdditionalActions", "Action before saving"); } } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeAdditionalActions() { PDDocumentCatalogAdditionalActions documentCatalogAdditionalActions = new PDDocumentCatalogAdditionalActions(); instance.sanitizeDocumentActions(documentCatalogAdditionalActions); documentCatalogAdditionalActions.setDP(new PDActionJavaScript()); documentCatalogAdditionalActions.setDS(new PDActionJavaScript()); documentCatalogAdditionalActions.setWC(new PDActionJavaScript()); documentCatalogAdditionalActions.setWP(new PDActionJavaScript()); documentCatalogAdditionalActions.setWS(new PDActionJavaScript()); instance.sanitizeDocumentActions(documentCatalogAdditionalActions); assertThreatsFound(session, 5); reset(session); assertNull(documentCatalogAdditionalActions.getDP()); assertNull(documentCatalogAdditionalActions.getDS()); assertNull(documentCatalogAdditionalActions.getWC()); assertNull(documentCatalogAdditionalActions.getWP()); assertNull(documentCatalogAdditionalActions.getWS()); instance.sanitizeDocumentActions(documentCatalogAdditionalActions); assertThreatsFound(session, 0); }
PDDocumentCatalogBleach { void sanitizeOpenAction(PDDocumentCatalog docCatalog) throws IOException { LOGGER.trace("Checking OpenAction..."); PDDestinationOrAction openAction = docCatalog.getOpenAction(); if (openAction == null) { return; } LOGGER.debug("Found a JavaScript OpenAction, removed. Was {}", openAction); docCatalog.setOpenAction(null); pdfBleachSession.recordJavascriptThreat("Document Catalog", "OpenAction"); } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeOpenAction() throws IOException { PDDocumentCatalog documentCatalog = mock(PDDocumentCatalog.class); when(documentCatalog.getOpenAction()).thenReturn(new PDActionJavaScript()); instance.sanitizeOpenAction(documentCatalog); verify(documentCatalog, atLeastOnce()).getOpenAction(); verify(documentCatalog, atLeastOnce()).setOpenAction(null); assertThreatsFound(session, 1); reset(session); reset(documentCatalog); when(documentCatalog.getOpenAction()).thenReturn(null); instance.sanitizeOpenAction(documentCatalog); verify(documentCatalog, atLeastOnce()).getOpenAction(); verify(documentCatalog, never()).setOpenAction(null); assertThreatsFound(session, 0); }
PDAnnotationBleach { void sanitizeLinkAnnotation(PDAnnotationLink annotationLink) { if (annotationLink.getAction() == null) { return; } LOGGER.debug("Found&removed annotation link - action, was {}", annotationLink.getAction()); pdfBleachSession.recordJavascriptThreat("Annotation", "External link"); annotationLink.setAction(null); } PDAnnotationBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeAnnotationLink() { PDAnnotationLink annotationLink = new PDAnnotationLink(); annotationLink.setAction(new PDActionJavaScript()); instance.sanitizeLinkAnnotation(annotationLink); assertThreatsFound(session, 1); assertNull(annotationLink.getAction()); reset(session); instance.sanitizeLinkAnnotation(annotationLink); assertThreatsFound(session, 0); }
PDAnnotationBleach { void sanitizeWidgetAnnotation(PDAnnotationWidget annotationWidget) { if (annotationWidget.getAction() != null) { LOGGER.debug( "Found&Removed action on annotation widget, was {}", annotationWidget.getAction()); pdfBleachSession.recordJavascriptThreat("Annotation", "External widget"); annotationWidget.setAction(null); } sanitizeAnnotationActions(annotationWidget.getActions()); } PDAnnotationBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeAnnotationWidgetAction() { PDAnnotationWidget annotationWidget = new PDAnnotationWidget(); annotationWidget.setAction(new PDActionJavaScript()); instance.sanitizeWidgetAnnotation(annotationWidget); assertThreatsFound(session, 1); assertNull(annotationWidget.getAction()); reset(session); instance.sanitizeWidgetAnnotation(annotationWidget); assertThreatsFound(session, 0); }
PDAnnotationBleach { void sanitizeAnnotationActions(PDAnnotationAdditionalActions annotationAdditionalActions) { if (annotationAdditionalActions == null) { return; } if (annotationAdditionalActions.getBl() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the annotation loses the input focus, was {}", annotationAdditionalActions.getBl()); pdfBleachSession .recordJavascriptThreat("Annotation", "Action when annotation loses the input focus"); annotationAdditionalActions.setBl(null); } if (annotationAdditionalActions.getD() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the mouse button is pressed inside the annotation's active area, was {}", annotationAdditionalActions.getD()); annotationAdditionalActions.setD(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when mouse button is pressed inside the annotation's active area"); } if (annotationAdditionalActions.getE() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the cursor enters the annotation's active area, was {}", annotationAdditionalActions.getE()); annotationAdditionalActions.setE(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the cursor enters the annotation's active area"); } if (annotationAdditionalActions.getFo() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the annotation receives the input focus, was {}", annotationAdditionalActions.getFo()); annotationAdditionalActions.setFo(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the annotation receives the input focus"); } if (annotationAdditionalActions.getPC() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the page containing the annotation is closed, was {}", annotationAdditionalActions.getPC()); annotationAdditionalActions.setPC(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the page containing the annotation is closed"); } if (annotationAdditionalActions.getPI() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the page containing the annotation is no longer visible in the viewer application's user interface, was {}", annotationAdditionalActions.getPI()); annotationAdditionalActions.setPI(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the page containing the annotation is no longer visible"); } if (annotationAdditionalActions.getPO() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the page containing the annotation is opened, was {}", annotationAdditionalActions.getPO()); annotationAdditionalActions.setPO(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the page containing the annotation is opened"); } if (annotationAdditionalActions.getPV() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the page containing the annotation becomes visible in the viewer application's user interface, was {}", annotationAdditionalActions.getPV()); annotationAdditionalActions.setPV(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action the page containing the annotation becomes visible"); } if (annotationAdditionalActions.getU() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the mouse button is released inside the annotation's active area, was {}", annotationAdditionalActions.getU()); annotationAdditionalActions.setU(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the mouse button is released inside the annotation's active area"); } if (annotationAdditionalActions.getX() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the cursor exits the annotation's active area, was {}", annotationAdditionalActions.getX()); annotationAdditionalActions.setX(null); pdfBleachSession.recordJavascriptThreat( "Annotation", "Action when the cursor exits the annotation's active area"); } } PDAnnotationBleach(PdfBleachSession pdfBleachSession); }
@Test void sanitizeAnnotationWidgetActions() throws ReflectiveOperationException { final String[] methods = {"Bl", "D", "E", "Fo", "PC", "PI", "PO", "U", "X"}; final PDAction action = new PDActionJavaScript(); final Class<PDAnnotationAdditionalActions> clazz = PDAnnotationAdditionalActions.class; for (String name : methods) { PDAnnotationAdditionalActions annotationAdditionalActions = new PDAnnotationAdditionalActions(); Method setMethod = clazz.getMethod("set" + name, PDAction.class); Method getMethod = clazz.getMethod("get" + name); setMethod.invoke(annotationAdditionalActions, action); assertNotNull(getMethod.invoke(annotationAdditionalActions), "get" + name + " returned null after being set"); instance.sanitizeAnnotationActions(annotationAdditionalActions); assertNull(getMethod.invoke(annotationAdditionalActions)); assertThreatsFound(session, 1); reset(session); } }
PdfBleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { return StreamUtils.hasHeader(stream, PDF_MAGIC); } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); }
@Test void handlesMagic() { Charset charset = Charset.defaultCharset(); InputStream validInputStream = new ByteArrayInputStream("%PDF1.5".getBytes(charset)); assertTrue(instance.handlesMagic(validInputStream)); InputStream invalidInputStream = new ByteArrayInputStream("".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); invalidInputStream = new ByteArrayInputStream("Anything".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); }
PdfBleachSession { void recordJavascriptThreat(String location, String details) { Threat threat = Threat.builder() .type(ThreatType.ACTIVE_CONTENT) .severity(ThreatSeverity.HIGH) .details(details) .location(location) .action(ThreatAction.REMOVE) .build(); session.recordThreat(threat); } PdfBleachSession(BleachSession session); }
@Test void recordingJavascriptThreatWorks() { instance.recordJavascriptThreat("", ""); assertThreatsFound(session, 1); }
OLE2Bleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { try { return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2; } catch (Exception e) { LOGGER.warn("An exception occured", e); return false; } } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); }
@Test void handlesMagic() throws IOException { Charset charset = Charset.defaultCharset(); InputStream invalidInputStream = new ByteArrayInputStream("".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); invalidInputStream = new ByteArrayInputStream("Anything".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); }
Altitude implements IWrappedInteger<Altitude>, Comparable<Altitude> { @Override public int compareTo(final Altitude that) { return Integer.compare(this.val, that.val); } Altitude(final int val); @Override int intValue(); @Override int compareTo(final Altitude that); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Altitude UNINITIALIZED; static final Altitude ZERO; }
@Test public void Test_compareTo() { { final Altitude a1 = new Altitude(0); final Altitude a2 = new Altitude(0); Assert.assertTrue(a1.compareTo(a2) == 0); } { final Altitude a1 = new Altitude(1); final Altitude a2 = new Altitude(2); Assert.assertTrue(a1.compareTo(a2) < 0); } { final Altitude a1 = new Altitude(1); final Altitude a2 = new Altitude(2); Assert.assertTrue(a2.compareTo(a1) > 0); } } @Test public void Test_Collections_sort() { final List<Altitude> arrayList = new ArrayList<>(); arrayList.add(new Altitude(9)); arrayList.add(new Altitude(2)); arrayList.add(new Altitude(3)); arrayList.add(new Altitude(0)); arrayList.add(new Altitude(5)); arrayList.add(new Altitude(1)); arrayList.add(new Altitude(6)); arrayList.add(new Altitude(7)); arrayList.add(new Altitude(4)); arrayList.add(new Altitude(8)); { boolean ascendingOrder = true; for (int i = 1; i < arrayList.size(); ++i) { if (arrayList.get(i - 1).compareTo(arrayList.get(i)) > 0) { ascendingOrder = false; } } Assert.assertFalse(ascendingOrder); } Collections.sort(arrayList); { boolean ascendingOrder = true; for (int i = 1; i < arrayList.size(); ++i) { if (arrayList.get(i - 1).compareTo(arrayList.get(i)) > 0) { ascendingOrder = false; } } Assert.assertTrue(ascendingOrder); } }
Position { public Position divide(final Position position) { final int x = getX() / position.getX(); final int y = getY() / position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionDivide() { Position p1 = new Position(1, 2); Position p2 = p1.divide(new Position(1, 1)); Position p3 = p1.divide(new Position(2, 2)); Assert.assertEquals(new Position(1, 2), p2); Assert.assertEquals(new Position(0, 1), p3); p2 = p2.divide(new Position(2, 2)); p3 = p3.divide(new Position(1, 1)); Assert.assertEquals(new Position(0, 1), p2); Assert.assertEquals(new Position(0, 1), p3); }
Position { @Override public String toString() { return "[" + getX() + ", " + getY() + "]"; } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionOstream() { Position p1 = new Position(2, -3); Assert.assertEquals("[2, -3]", p1.toString()); }
Altitude implements IWrappedInteger<Altitude>, Comparable<Altitude> { @Override public int intValue() { return this.val; } Altitude(final int val); @Override int intValue(); @Override int compareTo(final Altitude that); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Altitude UNINITIALIZED; static final Altitude ZERO; }
@Test public void Test_HashMap_get() { final AbstractMap<Altitude, Integer> map = new ConcurrentHashMap<>(); map.put(new Altitude(0), 0); map.put(new Altitude(1), 1); map.put(new Altitude(2), 2); map.put(new Altitude(3), 3); map.put(new Altitude(4), 4); Assert.assertEquals(0, map.get(new Altitude(0)).intValue()); Assert.assertEquals(1, map.get(new Altitude(1)).intValue()); Assert.assertEquals(2, map.get(new Altitude(2)).intValue()); Assert.assertEquals(3, map.get(new Altitude(3)).intValue()); Assert.assertEquals(4, map.get(new Altitude(4)).intValue()); Assert.assertNotEquals(1, map.get(new Altitude(0)).intValue()); Assert.assertNotEquals(4, map.get(new Altitude(1)).intValue()); Assert.assertNotEquals(3, map.get(new Altitude(2)).intValue()); Assert.assertNotEquals(4, map.get(new Altitude(3)).intValue()); Assert.assertNotEquals(8, map.get(new Altitude(4)).intValue()); }
WalkPosition { public WalkPosition add(WalkPosition walkPosition) { final int x = getX() + walkPosition.getX(); final int y = getY() + walkPosition.getY(); return new WalkPosition(x, y); } WalkPosition(final int x, final int y); WalkPosition(final TilePosition tilePosition); WalkPosition(final Position position); int getX(); int getY(); TilePosition toTilePosition(); Position toPosition(); WalkPosition add(WalkPosition walkPosition); WalkPosition subtract(WalkPosition walkPosition); WalkPosition multiply(WalkPosition walkPosition); WalkPosition divide(WalkPosition walkPosition); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); static final int SIZE_IN_PIXELS; }
@Test public void testArrayListContains() { final List<WalkPosition> list = new ArrayList<>(); list.add(new WalkPosition(0, 0)); list.add(new WalkPosition(24, 87)); list.add(new WalkPosition(48, 39)); list.add(new WalkPosition(361, 92)); list.add(new WalkPosition(510, 6)); Assert.assertTrue(list.contains(new WalkPosition(0, 0))); Assert.assertTrue(list.contains(new WalkPosition(24, 87))); Assert.assertTrue(list.contains(new WalkPosition(48, 39))); Assert.assertTrue(list.contains(new WalkPosition(361, 92))); Assert.assertTrue(list.contains(new WalkPosition(510, 6))); }
TilePosition { @Override public boolean equals(final Object object) { if (this == object) { return true; } if (!(object instanceof TilePosition)) { return false; } final TilePosition tilePosition = (TilePosition) object; if (getX() != tilePosition.getX()) { return false; } if (getY() != tilePosition.getY()) { return false; } return true; } @BridgeValue TilePosition(final int x, final int y); TilePosition(final WalkPosition walkPosition); TilePosition(final Position position); int getX(); int getY(); double getDistance(final TilePosition position); WalkPosition toWalkPosition(); Position toPosition(); TilePosition add(final TilePosition tilePosition); TilePosition subtract(final TilePosition tilePosition); TilePosition multiply(final TilePosition tilePosition); TilePosition divide(final TilePosition tilePosition); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); static final int SIZE_IN_PIXELS; }
@Test public void testEquals() { { TilePosition a1 = new TilePosition(0, 0); TilePosition a2 = new TilePosition(0, 0); Assert.assertTrue(a1.equals(a2) && a2.equals(a1)); } { TilePosition b1 = new TilePosition(27, 98); TilePosition b2 = new TilePosition(27, 98); Assert.assertTrue(b1.equals(b2) && b2.equals(b1)); } { TilePosition c1 = new TilePosition(114, 8); TilePosition c2 = new TilePosition(114, 8); Assert.assertTrue(c1.equals(c2) && c2.equals(c1)); } Assert.assertTrue((new TilePosition(0, 0).equals(new TilePosition(0, 0)))); Assert.assertTrue((new TilePosition(1, 1).equals(new TilePosition(1, 1)))); Assert.assertTrue((new TilePosition(127, 37).equals(new TilePosition(127, 37)))); for (int y = 0; y < 256; ++y) { for (int x = 0; x < 256; ++x) { TilePosition t1 = new TilePosition(x, y); TilePosition t2 = new TilePosition(x, y); Assert.assertTrue(t1.equals(t2) && t2.equals(t1)); } } }
TilePosition { @Override public int hashCode() { return (getX() * 2048 + getY()); } @BridgeValue TilePosition(final int x, final int y); TilePosition(final WalkPosition walkPosition); TilePosition(final Position position); int getX(); int getY(); double getDistance(final TilePosition position); WalkPosition toWalkPosition(); Position toPosition(); TilePosition add(final TilePosition tilePosition); TilePosition subtract(final TilePosition tilePosition); TilePosition multiply(final TilePosition tilePosition); TilePosition divide(final TilePosition tilePosition); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); static final int SIZE_IN_PIXELS; }
@Test public void testHashCode() { Assert.assertEquals(new TilePosition(0, 0).hashCode(), new TilePosition(0, 0).hashCode()); Assert.assertEquals(new TilePosition(3, 87).hashCode(), new TilePosition(3, 87).hashCode()); Assert.assertEquals(new TilePosition(112, 6).hashCode(), new TilePosition(112, 6).hashCode()); HashMap<TilePosition, Integer> map = new HashMap<>(); int index = 0; for (int y = 0; y < 256; ++y) { for (int x = 0; x < 256; ++x) { map.put(new TilePosition(x, y), index++); } } Assert.assertEquals(map.get(new TilePosition(0, 0)).intValue(), 0); Assert.assertEquals(map.get(new TilePosition(3, 87)).intValue(), 22275); Assert.assertEquals(map.get(new TilePosition(112, 6)).intValue(), 1648); Assert.assertEquals(map.get(new TilePosition(128, 136)).intValue(), 34944); Assert.assertEquals(map.get(new TilePosition(37, 255)).intValue(), 65317); Assert.assertEquals(map.get(new TilePosition(255, 37)).intValue(), 9727); Assert.assertEquals(map.get(new TilePosition(136, 128)).intValue(), 32904); Assert.assertEquals(map.get(new TilePosition(255, 255)).intValue(), 65535); }
Position { @Override public boolean equals(final Object object) { if (this == object) { return true; } if (!(object instanceof Position)) { return false; } final Position position = (Position) object; if (getX() != position.getX()) { return false; } if (getY() != position.getY()) { return false; } return true; } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionEquality() { final TilePosition p1 = new TilePosition(0, 0); final TilePosition p2 = new TilePosition(2, 2); Assert.assertFalse(p1.equals(p2)); Assert.assertTrue(!p1.equals(p2)); }
Position { public Position add(final Position position) { final int x = getX() + position.getX(); final int y = getY() + position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionAdd() { Position p1 = new Position(1, 1); Position p2 = new Position(1, 2); Position p3 = p1.add(p2); Assert.assertEquals(new Position(2, 3), p3); p3 = p3.add(p1); Assert.assertEquals(new Position(3, 4), p3); p3 = p3.add(new Position(0, 0)); Assert.assertEquals(new Position(3, 4), p3); }
Position { public Position subtract(final Position position) { final int x = getX() - position.getX(); final int y = getY() - position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionSubtract() { Position p1 = new Position(1, 1); Position p2 = new Position(1, 2); Position p3 = p1.subtract(p2); Assert.assertEquals(new Position(0, -1), p3); p3 = p3.subtract(p1); Assert.assertEquals(new Position(-1, -2), p3); p3 = p3.subtract(new Position(0, 0)); Assert.assertEquals(new Position(-1, -2), p3); }
Position { public Position multiply(final Position position) { final int x = getX() * position.getX(); final int y = getY() * position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }
@Test public void PositionMultiply() { Position p1 = new Position(1, 2); Position p2 = p1.multiply(new Position(1, 1)); Position p3 = p1.multiply(new Position(2, 2)); Assert.assertEquals(new Position(1, 2), p2); Assert.assertEquals(new Position(2, 4), p3); p2 = p2.multiply(new Position(2, 2)); p3 = p3.multiply(new Position(1, 1)); Assert.assertEquals(new Position(2, 4), p2); Assert.assertEquals(new Position(2, 4), p3); }
LostApiClientImpl implements LostApiClient { @Override public void connect() { clientManager.addClient(this); GeofencingApiImpl geofencingApi = getGeofencingImpl(); if (!geofencingApi.isConnected()) { geofencingApi.connect(context); } SettingsApiImpl settingsApi = getSettingsApiImpl(); if (!settingsApi.isConnected()) { settingsApi.connect(context); } FusedLocationProviderApiImpl fusedApi = getFusedLocationProviderApiImpl(); if (fusedApi.isConnected()) { if (connectionCallbacks != null) { connectionCallbacks.onConnected(); fusedApi.addConnectionCallbacks(connectionCallbacks); } } else if (fusedApi.isConnecting()) { if (connectionCallbacks != null) { fusedApi.addConnectionCallbacks(connectionCallbacks); } } else { fusedApi.connect(context, connectionCallbacks); } } LostApiClientImpl(Context context, ConnectionCallbacks callbacks, ClientManager clientManager); @Override void connect(); @Override void disconnect(); @Override boolean isConnected(); }
@Test public void connect_shouldBeConnectedWhenConnectionCallbackInvoked() throws Exception { callbacks.setLostClient(client); client.connect(); assertThat(callbacks.isClientConnectedOnConnect()).isTrue(); } @Test public void connect_multipleClients_shouldBeConnectedWhenConnectionCallbackInvoked() throws Exception { client.connect(); TestConnectionCallbacks callbacks = new TestConnectionCallbacks(); LostApiClient anotherClient = new LostApiClientImpl(application, callbacks, new LostClientManager()); callbacks.setLostClient(anotherClient); anotherClient.connect(); assertThat(callbacks.isClientConnectedOnConnect()).isTrue(); } @Test public void connect_shouldAddConnectionCallbacks() throws Exception { new LostApiClientImpl(application, new LostApiClient.ConnectionCallbacks() { @Override public void onConnected() { new LostApiClientImpl(application, new TestConnectionCallbacks(), new LostClientManager()).connect(); } @Override public void onConnectionSuspended() { } }, new LostClientManager()).connect(); FusedLocationProviderApiImpl api = (FusedLocationProviderApiImpl) LocationServices.FusedLocationApi; assertThat(api.getServiceConnectionManager().getConnectionCallbacks()).hasSize(2); }
LostApiClientImpl implements LostApiClient { @Override public boolean isConnected() { return getGeofencingImpl().isConnected() && getSettingsApiImpl().isConnected() && getFusedLocationProviderApiImpl().isConnected() && clientManager.containsClient(this); } LostApiClientImpl(Context context, ConnectionCallbacks callbacks, ClientManager clientManager); @Override void connect(); @Override void disconnect(); @Override boolean isConnected(); }
@Test public void isConnected_shouldReturnFalseBeforeConnected() throws Exception { assertThat(client.isConnected()).isFalse(); }
LocationRequest implements Parcelable { public int getPriority() { return priority; } private LocationRequest(); protected LocationRequest(Parcel in); static LocationRequest create(); long getInterval(); LocationRequest setInterval(long millis); long getFastestInterval(); LocationRequest setFastestInterval(long millis); float getSmallestDisplacement(); LocationRequest setSmallestDisplacement(float meters); int getPriority(); LocationRequest setPriority(int priority); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final int PRIORITY_HIGH_ACCURACY; static final int PRIORITY_BALANCED_POWER_ACCURACY; static final int PRIORITY_LOW_POWER; static final int PRIORITY_NO_POWER; static final Parcelable.Creator<LocationRequest> CREATOR; }
@Test public void getPriority_shouldReturnDefaultValue() throws Exception { assertThat(locationRequest.getPriority()).isEqualTo(PRIORITY_BALANCED_POWER_ACCURACY); }
LocationRequest implements Parcelable { public LocationRequest setPriority(int priority) { if (priority != PRIORITY_HIGH_ACCURACY && priority != PRIORITY_BALANCED_POWER_ACCURACY && priority != PRIORITY_LOW_POWER && priority != PRIORITY_NO_POWER) { throw new IllegalArgumentException("Invalid priority: " + priority); } this.priority = priority; return this; } private LocationRequest(); protected LocationRequest(Parcel in); static LocationRequest create(); long getInterval(); LocationRequest setInterval(long millis); long getFastestInterval(); LocationRequest setFastestInterval(long millis); float getSmallestDisplacement(); LocationRequest setSmallestDisplacement(float meters); int getPriority(); LocationRequest setPriority(int priority); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final int PRIORITY_HIGH_ACCURACY; static final int PRIORITY_BALANCED_POWER_ACCURACY; static final int PRIORITY_LOW_POWER; static final int PRIORITY_NO_POWER; static final Parcelable.Creator<LocationRequest> CREATOR; }
@Test(expected = IllegalArgumentException.class) public void setPriority_shouldRejectInvalidValues() throws Exception { locationRequest.setPriority(-1); }
LostClientManager implements ClientManager { @Override public int numberOfClients() { return clients.size(); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request, LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context, final Location location, final LocationAvailability availability, final LocationResult result); @Override ReportedChanges reportLocationResult(Location location, final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }
@Test public void shouldHaveZeroClientCount() { assertThat(manager.numberOfClients()).isEqualTo(0); }
LostClientManager implements ClientManager { @Override public void addListener(LostApiClient client, LocationRequest request, LocationListener listener) { throwIfClientNotAdded(client); clients.get(client).locationListeners().add(listener); listenerToLocationRequests.put(listener, request); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request, LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context, final Location location, final LocationAvailability availability, final LocationResult result); @Override ReportedChanges reportLocationResult(Location location, final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }
@Test(expected = IllegalArgumentException.class) public void addListener_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addListener(client, LocationRequest.create(), new TestLocationListener()); }
LostClientManager implements ClientManager { @Override public void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent) { throwIfClientNotAdded(client); clients.get(client).pendingIntents().add(callbackIntent); intentToLocationRequests.put(callbackIntent, request); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request, LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context, final Location location, final LocationAvailability availability, final LocationResult result); @Override ReportedChanges reportLocationResult(Location location, final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }
@Test(expected = IllegalArgumentException.class) public void addPendingIntent_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addPendingIntent(client, LocationRequest.create(), mock(PendingIntent.class)); }
LostClientManager implements ClientManager { @Override public void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper) { throwIfClientNotAdded(client); clients.get(client).locationCallbacks().add(callback); clients.get(client).looperMap().put(callback, looper); callbackToLocationRequests.put(callback, request); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request, LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context, final Location location, final LocationAvailability availability, final LocationResult result); @Override ReportedChanges reportLocationResult(Location location, final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }
@Test(expected = IllegalArgumentException.class) public void addLocationCallback_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addLocationCallback(client, LocationRequest.create(), new TestLocationCallback(), mock(Looper.class)); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public boolean isConnecting() { return serviceConnectionManager.isConnecting(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); }
@Test public void isConnecting_shouldCallConnectionManager() { api.isConnecting(); verify(connectionManager).isConnecting(); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks) { serviceConnectionManager.addCallbacks(callbacks); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); }
@Test public void addConnectionCallbacks_shouldCallConnectionManager() { TestConnectionCallbacks callbacks = new TestConnectionCallbacks(); api.addConnectionCallbacks(callbacks); verify(connectionManager).addCallbacks(callbacks); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void connect(Context context, LostApiClient.ConnectionCallbacks callbacks) { serviceConnectionManager.connect(context, callbacks); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); }
@Test public void connect_shouldCallConnectionManager() { Context context = mock(Context.class); TestConnectionCallbacks callbacks = new TestConnectionCallbacks(); api.connect(context, callbacks); verify(connectionManager).connect(context, callbacks); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void disconnect() { serviceConnectionManager.disconnect(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); }
@Test public void disconnect_shouldCallConnectionManager() { api.disconnect(); verify(connectionManager).disconnect(); }
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public boolean isConnected() { return serviceConnectionManager.isConnected(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Override void onServiceConnected(IBinder binder); @Override void onDisconnect(); @Override void onServiceConnected(ComponentName name, IBinder binder); @Override void onServiceDisconnected(ComponentName name); boolean isConnecting(); void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks); void connect(Context context, LostApiClient.ConnectionCallbacks callbacks); void disconnect(); boolean isConnected(); @Override Location getLastLocation(LostApiClient client); @Override LocationAvailability getLocationAvailability(LostApiClient client); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationListener listener, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper); @Override PendingResult<Status> requestLocationUpdates(LostApiClient client, LocationRequest request, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationListener listener); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, PendingIntent callbackIntent); @Override PendingResult<Status> removeLocationUpdates(LostApiClient client, LocationCallback callback); @Override PendingResult<Status> setMockMode(LostApiClient client, boolean isMockMode); @Override PendingResult<Status> setMockLocation(LostApiClient client, Location mockLocation); @Override PendingResult<Status> setMockTrace(LostApiClient client, String path, String filename); Map<LostApiClient, Set<LocationListener>> getLocationListeners(); }
@Test public void isConnected_shouldCallConnectionManager() { api.isConnected(); verify(connectionManager).isConnected(); }