src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
UserController { @RequestMapping(method = RequestMethod.GET, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody User userByUsername(@RequestParam("username") String username) { return repository.findByUsername(username); } @Autowired UserController(UserRepository repository); @RequestMapping(method = RequestMethod.GET, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByUsername(@RequestParam("username") String username); @RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByFullname(@RequestParam("fullname") String fullname); @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody List<User> user(); @RequestMapping(method = RequestMethod.PUT, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User update(@PathVariable("id") long id, @RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.PUT, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User updateByUsername(@RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User insertData(@ModelAttribute("insertUser") @Valid User user, BindingResult result); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.DELETE, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserByUsername(@RequestParam("username") String username); @ExceptionHandler(CustomException.class) ResponseEntity<ErrorResponse> exceptionHandler(CustomException ex); }
@Test public void userByUsername() throws Exception { mockMvc.perform(get("/user?username={username}", "samed")) .andExpect(status().isOk()) .andExpect( content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.username", is("samed"))) .andExpect(jsonPath("$.fullname", is("Samed Düzçay"))) .andExpect(jsonPath("$.email", is("[email protected]"))); verify(repo, times(1)).findByUsername("samed"); verifyNoMoreInteractions(repo); }
UserController { @RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody User userByFullname(@RequestParam("fullname") String fullname) { return repository.findByFullname(fullname); } @Autowired UserController(UserRepository repository); @RequestMapping(method = RequestMethod.GET, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByUsername(@RequestParam("username") String username); @RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByFullname(@RequestParam("fullname") String fullname); @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody List<User> user(); @RequestMapping(method = RequestMethod.PUT, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User update(@PathVariable("id") long id, @RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.PUT, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User updateByUsername(@RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User insertData(@ModelAttribute("insertUser") @Valid User user, BindingResult result); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.DELETE, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserByUsername(@RequestParam("username") String username); @ExceptionHandler(CustomException.class) ResponseEntity<ErrorResponse> exceptionHandler(CustomException ex); }
@Test public void userByFullname() throws Exception { mockMvc.perform(get("/user?fullname={fullname}", "Samed Düzçay")) .andExpect(status().isOk()) .andExpect( content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.username", is("samed"))) .andExpect(jsonPath("$.fullname", is("Samed Düzçay"))) .andExpect(jsonPath("$.email", is("[email protected]"))); verify(repo, times(1)).findByFullname("Samed Düzçay"); verifyNoMoreInteractions(repo); }
DateUtils { public static String toStandardDate(int year, int month, int day) { String yearStr = Integer.toString(year); String monthStr = Integer.toString(month); String dayStr = Integer.toString(day); if (month < 10) { monthStr = "0" + monthStr; } if (day < 10) { dayStr = "0" + dayStr; } StringBuilder builder = new StringBuilder(); builder.append(yearStr); builder.append('-'); builder.append(monthStr); builder.append('-'); builder.append(dayStr); return builder.toString(); } static String toStandardDate(int year, int month, int day); static int[] fromStandardDate(String standardDate); }
@Test public void testToStandardDate() { int y = 1990; int m = 5; int d = 3; assertEquals("1990-05-03", DateUtils.toStandardDate(y, m, d)); y = 1990; m = 11; d = 3; assertEquals("1990-11-03", DateUtils.toStandardDate(y, m, d)); y = 1990; m = 5; d = 31; assertEquals("1990-05-31", DateUtils.toStandardDate(y, m, d)); y = 2018; m = 12; d = 31; assertEquals("2018-12-31", DateUtils.toStandardDate(y, m, d)); }
CultureItem implements Parcelable { @Override public boolean equals(Object obj) { if (!(obj instanceof CultureItem)) { return false; } CultureItem other = (CultureItem)obj; return this.id == other.id && this.user == other.user && Utils.objectEquals(this.title, other.title) && Utils.objectEquals(this.description, other.description) && Utils.objectEquals(this.placeName, other.placeName) && Utils.objectEquals(this.startYear, other.startYear) && Utils.objectEquals(this.endYear, other.endYear) && Utils.objectEquals(this.latitude, other.latitude) && Utils.objectEquals(this.longitude, other.longitude) && Utils.objectEquals(this.imageList, other.imageList) && Utils.objectEquals(this.tagList, other.tagList) && Utils.objectEquals(this.commentList, other.commentList) && Utils.objectEquals(this.isFavorite, other.isFavorite) && Utils.objectEquals(this.favoriteCount, other.favoriteCount) && this.publicAccessibility == other.publicAccessibility && Utils.objectEquals(this.userInfo, other.userInfo); } CultureItem(); @SuppressWarnings("unchecked") CultureItem(Parcel in); @Override void writeToParcel(Parcel out, int flags); @Override int describeContents(); long getId(); void setId(long id); long getUser(); void setUser(long user); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getPlaceName(); void setPlaceName(String placeName); Integer getStartYear(); void setStartYear(int startYear); Integer getEndYear(); void setEndYear(int endYear); void setStartYear(Integer startYear); void setEndYear(Integer endYear); String getLatitude(); void setLatitude(String latitude); String getLongitude(); void setLongitude(String longitude); boolean isPublicAccessibility(); void setPublicAccessibility(boolean publicAccessibility); boolean isFavorite(); void setFavorite(boolean favorite); ArrayList<Image> getImageList(); void setImageList(ArrayList<Image> imageList); ArrayList<Tag> getTagList(); void setTagList(ArrayList<Tag> tagList); Boolean getPublicAccessibility(); void setPublicAccessibility(Boolean publicAccessibility); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); UserResponse getUserInfo(); void setUserInfo(UserResponse userInfo); FeedRow toFeedRow(); ArrayList<Comment> getCommentList(); void setCommentList(ArrayList<Comment> commentList); @Override boolean equals(Object obj); @SerializedName("public_accessibility") @Expose private boolean publicAccessibility; static final Parcelable.Creator<CultureItem> CREATOR; }
@Test public void testEquals() { CultureItem firstItem = new CultureItem(); CultureItem secondItem = new CultureItem(); assertEquals(firstItem, secondItem); firstItem.setId(5); assertNotEquals(firstItem, secondItem); secondItem.setId(firstItem.getId()); assertEquals(firstItem, secondItem); secondItem.setDescription(""); assertNotEquals(firstItem, secondItem); firstItem.setDescription(secondItem.getDescription()); assertEquals(firstItem, secondItem); Tag t1 = new Tag("tag1"); ArrayList<Tag> firstTagList = new ArrayList<>(); firstTagList.add(t1); firstItem.setTagList(firstTagList); assertNotEquals(firstItem, secondItem); ArrayList<Tag> secondTagList = new ArrayList<>(); secondTagList.add(new Tag(t1.getName())); secondItem.setTagList(secondTagList); assertEquals(firstItem, secondItem); }
CultureItem implements Parcelable { public void setLatitude(String latitude) { this.latitude = latitude; } CultureItem(); @SuppressWarnings("unchecked") CultureItem(Parcel in); @Override void writeToParcel(Parcel out, int flags); @Override int describeContents(); long getId(); void setId(long id); long getUser(); void setUser(long user); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getPlaceName(); void setPlaceName(String placeName); Integer getStartYear(); void setStartYear(int startYear); Integer getEndYear(); void setEndYear(int endYear); void setStartYear(Integer startYear); void setEndYear(Integer endYear); String getLatitude(); void setLatitude(String latitude); String getLongitude(); void setLongitude(String longitude); boolean isPublicAccessibility(); void setPublicAccessibility(boolean publicAccessibility); boolean isFavorite(); void setFavorite(boolean favorite); ArrayList<Image> getImageList(); void setImageList(ArrayList<Image> imageList); ArrayList<Tag> getTagList(); void setTagList(ArrayList<Tag> tagList); Boolean getPublicAccessibility(); void setPublicAccessibility(Boolean publicAccessibility); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); UserResponse getUserInfo(); void setUserInfo(UserResponse userInfo); FeedRow toFeedRow(); ArrayList<Comment> getCommentList(); void setCommentList(ArrayList<Comment> commentList); @Override boolean equals(Object obj); @SerializedName("public_accessibility") @Expose private boolean publicAccessibility; static final Parcelable.Creator<CultureItem> CREATOR; }
@Test public void testLatLongEquals() { CultureItem firstItem = new CultureItem(); CultureItem secondItem = new CultureItem(); firstItem.setLatitude("17.010010"); secondItem.setLatitude("17.010010"); assertEquals(firstItem, secondItem); }
Tag implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Tag)) { return false; } Tag other = (Tag)obj; return Utils.objectEquals(this.name, other.name); } Tag(String name); String getName(); void setName(String name); @Override boolean equals(Object obj); }
@Test public void testEquals() { Tag t1 = null; Tag t2 = null; assertEquals(t1, t2); t1 = new Tag("tag1"); assertNotEquals(t1, t2); t2 = new Tag("tag2"); assertNotEquals(t1, t2); t2.setName(t1.getName()); assertEquals(t1, t2); }
RetrofitBuilder { public RetrofitBuilder() { this.retrofitBuilder = new Retrofit.Builder(); this.okhttpBuilder = new OkHttpClient.Builder(); } RetrofitBuilder(); RetrofitBuilder baseUrl(String baseUrl); RetrofitBuilder readTimeout(long timeout, TimeUnit unit); RetrofitBuilder writeTimeout(long timeout, TimeUnit unit); RetrofitBuilder connectTimeout(long timeout, TimeUnit unit); RetrofitBuilder addConverterFactory(Converter.Factory factory); RetrofitBuilder addInterceptor(); Retrofit build(); }
@Test public void testRetrofitBuilder() { assertNotNull(retrofit); assertEquals(TEST_URL, retrofit.baseUrl().toString()); boolean inside = false; for (Converter.Factory currFactory : retrofit.converterFactories()) { if (factory == currFactory) inside = true; } assertTrue(inside); }
APIUtils { public static API serverAPI() { return serverAPI; } static API serverAPI(); static void setServerAPI(API api); }
@Test public void testServerAPI() { API api = APIUtils.serverAPI(); assertNotNull(api); }
APIUtils { public static void setServerAPI(API api) { serverAPI = api; } static API serverAPI(); static void setServerAPI(API api); }
@Test public void testSetServerAPI() { API newAPI = new RetrofitBuilder().baseUrl("http: APIUtils.setServerAPI(newAPI); assertTrue(newAPI == APIUtils.serverAPI()); }
FeedRow { public static String toYearFormat(int startYear, int endYear) { return String.format("%d/%d", startYear, endYear); } FeedRow(); FeedRow(String imageUrl, String title, String description, String location, String year, List<String> tagList, String favoriteCount, boolean isFavorite, String creatorUsername); static String toYearFormat(int startYear, int endYear); static int[] fromYearFormat(String yearFormat); String getImageUrl(); void setImageUrl(String imageUrl); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getLocation(); void setLocation(String location); String getYear(); void setYear(String year); void setTagList(List<String> tagList); List<String> getTagList(); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); String getCreatorUsername(); void setCreatorUsername(String creatorUsername); boolean isFavorite(); void setFavorite(boolean favorite); }
@Test public void testToYearFormat() { int firstYear = 0; int secondYear = 0; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "0/0"); firstYear = -5; secondYear = -30; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "-5/-30"); firstYear = 2000; secondYear = -30; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "2000/-30"); }
FeedRow { public static int[] fromYearFormat(String yearFormat) { String[] parts = yearFormat.split("/"); if (parts.length != 2) { throw new IllegalArgumentException("Given string is not in expected format: " + yearFormat); } int[] intParts = {Integer.parseInt(parts[0]), Integer.parseInt(parts[1])}; return intParts; } FeedRow(); FeedRow(String imageUrl, String title, String description, String location, String year, List<String> tagList, String favoriteCount, boolean isFavorite, String creatorUsername); static String toYearFormat(int startYear, int endYear); static int[] fromYearFormat(String yearFormat); String getImageUrl(); void setImageUrl(String imageUrl); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getLocation(); void setLocation(String location); String getYear(); void setYear(String year); void setTagList(List<String> tagList); List<String> getTagList(); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); String getCreatorUsername(); void setCreatorUsername(String creatorUsername); boolean isFavorite(); void setFavorite(boolean favorite); }
@Test public void testFromYearFormat() { String year = "-30/2000"; int[] yearPair = {-30, 2000}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); year = "0/0"; yearPair = new int[]{0, 0}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); thrown.expect(IllegalArgumentException.class); year = "5/4/"; FeedRow.fromYearFormat(year); year = "205-2077"; FeedRow.fromYearFormat(year); }
DateUtils { public static int[] fromStandardDate(String standardDate) { int[] parts = new int[3]; String[] sParts = standardDate.split("-"); for (int i = 0; i < sParts.length; ++i) { parts[i] = Integer.parseInt(sParts[i]); } return parts; } static String toStandardDate(int year, int month, int day); static int[] fromStandardDate(String standardDate); }
@Test public void testFromStandardDate() { String date = "2013-05-01"; int[] expected = new int[]{2013, 5, 1}; int[] actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "2013-11-12"; expected = new int[]{2013, 11, 12}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "1990-05-30"; expected = new int[]{1990, 5, 30}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "1990-11-01"; expected = new int[]{1990, 11, 1}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); }
Utils { public static String tokenToAuthString(String token) { return "JWT " + token; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testTokenToAuthString() { String token = ""; assertEquals("JWT " + token, Utils.tokenToAuthString(token)); token = "aoesnutda"; assertEquals("JWT " + token, Utils.tokenToAuthString(token)); }
Utils { public static boolean isLocalUrl(String url) { return url.startsWith("content: } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testIsLocalUrl() { String url = "http: assertFalse(Utils.isLocalUrl(url)); url = ""; assertFalse(Utils.isLocalUrl(url)); url = "content: assertTrue(Utils.isLocalUrl(url)); url = "content:"; assertFalse(Utils.isLocalUrl(url)); }
Utils { public static boolean isClose(double a, double b) { return Math.abs(a - b) <= Constants.DOUBLE_EQUALITY_EPSILON; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testIsClose() { double a = 5; double b = 6; assertFalse(Utils.isClose(a, b)); a = b; assertTrue(Utils.isClose(a, b)); double remainingPrecision = 1e-14/Constants.DOUBLE_EQUALITY_EPSILON; a = b + (1 - remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertTrue(Utils.isClose(a, b)); a = b - (1 - remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertTrue(Utils.isClose(a, b)); a = b + (1 + remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertFalse(Utils.isClose(a, b)); a = b - (1 + remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertFalse(Utils.isClose(a, b)); }
Utils { public static boolean objectEquals(Object a, Object b) { if (a == null && b != null) { return false; } else if (a != null && b == null) { return false; } else if (a != null && b != null) { return a.equals(b); } return true; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testObjectEquals() { Integer a = null; Integer b = new Integer(5); assertFalse(Utils.objectEquals(a, b)); assertTrue(Utils.objectEquals(a, null)); a = new Integer(6); assertFalse(Utils.objectEquals(a, b)); a = new Integer(b.intValue()); assertTrue(Utils.objectEquals(a, b)); }
Utils { public static double roundToDecimals(double num, int precision) { if (precision < 0 || precision > 8) { throw new IllegalArgumentException("Precision must be an int from 0 to 8."); } long multiplier = (long)Math.pow(10, (double)precision); return ((int)(num*multiplier))/(double)multiplier; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testRoundToDecimals() { double a = 3; assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 0))); assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 1))); a = 3.00001; assertTrue(Utils.isClose(3, Utils.roundToDecimals(a, 4))); assertFalse(Utils.isClose(3, Utils.roundToDecimals(a, 5))); a = 3.14723; assertTrue(Utils.isClose(3.14, Utils.roundToDecimals(a, 2))); assertFalse(Utils.isClose(3.14, Utils.roundToDecimals(a, 3))); assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 8))); thrown.expect(IllegalArgumentException.class); Utils.roundToDecimals(a, -1); Utils.roundToDecimals(a, 9); }
Utils { public static boolean isValidYear(String s) { int year = 0; try { year = Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return year >= Constants.MIN_YEAR && year <= Constants.MAX_YEAR; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }
@Test public void testIsValidYear() { String s = ""; assertFalse(Utils.isValidYear(s)); s = "what"; assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MIN_YEAR - 1); assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MAX_YEAR + 1); assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MIN_YEAR + Constants.MAX_YEAR)/2; assertTrue(Utils.isValidYear(s)); }
Comment implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Comment)) { return false; } Comment other = (Comment)obj; return Utils.objectEquals(this.user, other.user) && Utils.objectEquals(this.text, other.text) && Utils.objectEquals(this.createTime, other.createTime) && Utils.objectEquals(this.updateTime, other.updateTime) && Utils.objectEquals(this.itemKey, other.itemKey); } String getUser(); void setUser(String user); String getText(); void setText(String text); String getCreateTime(); void setCreateTime(String createTime); String getUpdateTime(); void setUpdateTime(String updateTime); String getItemKey(); void setItemKey(String itemKey); CommentRow toCommentRow(); UserInfo getUserInfo(); void setUserInfo(UserInfo userInfo); @Override boolean equals(Object obj); }
@Test public void testEquals() { Comment c1 = null; Comment c2 = null; assertEquals(c1, c2); c1 = new Comment(); assertNotEquals(c1, c2); c2 = new Comment(); assertEquals(c1, c2); c1.setText("comment1"); assertNotEquals(c1, c2); c2.setText(c1.getText()); assertEquals(c1, c2); c1.setUser("user1"); assertNotEquals(c1, c2); c2.setUser(c1.getUser()); assertEquals(c1, c2); }
Image implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Image)) { return false; } Image other = (Image)obj; return Utils.objectEquals(this.url, other.url); } boolean isMain(); void setMain(boolean main); String getUrl(); void setUrl(String url); ImageRow toImageRow(); @Override boolean equals(Object obj); }
@Test public void testEquals() { Image img1 = null; Image img2 = null; assertEquals(img1, img2); img1 = new Image(); assertNotEquals(img1, img2); img2 = new Image(); assertEquals(img1, img2); img1.setUrl("url1"); assertNotEquals(img1, img2); img2.setUrl(img1.getUrl()); assertEquals(img1, img2); }
UDPHeader implements TransportHeader { @Override public UDPHeader copyTo(ByteBuffer target) { raw.rewind(); ByteBuffer slice = Binary.slice(target, target.position(), getHeaderLength()); target.put(raw); return new UDPHeader(slice); } UDPHeader(ByteBuffer raw); @Override int getSourcePort(); @Override int getDestinationPort(); @Override void setSourcePort(int sourcePort); @Override void setDestinationPort(int destinationPort); @Override int getHeaderLength(); @Override void setPayloadLength(int payloadLength); @Override ByteBuffer getRaw(); @Override UDPHeader copyTo(ByteBuffer target); @Override void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload); }
@Test public void testCopyTo() { ByteBuffer buffer = createMockHeaders(); UDPHeader header = new UDPHeader(buffer); ByteBuffer target = ByteBuffer.allocate(32); target.position(12); UDPHeader copy = header.copyTo(target); copy.setSourcePort(9999); Assert.assertEquals(20, target.position()); Assert.assertEquals("Header must modify target", 9999, target.getShort(12)); Assert.assertEquals("Header must not modify buffer", 1234, buffer.getShort(0)); }
TCPHeader implements TransportHeader { @Override public void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload) { byte[] rawArray = raw.array(); int rawOffset = raw.arrayOffset(); byte[] payloadArray = payload.array(); int payloadOffset = payload.arrayOffset(); int source = ipv4Header.getSource(); int destination = ipv4Header.getDestination(); int length = ipv4Header.getTotalLength() - ipv4Header.getHeaderLength(); assert (length & ~0xffff) == 0 : "Length cannot take more than 16 bits"; int sum = source >>> 16; sum += source & 0xffff; sum += destination >>> 16; sum += destination & 0xffff; sum += IPv4Header.Protocol.TCP.getNumber(); sum += length; setChecksum((short) 0); for (int i = 0; i < headerLength / 2; ++i) { sum += ((rawArray[rawOffset + 2 * i] & 0xff) << 8) | (rawArray[rawOffset + 2 * i + 1] & 0xff); } int payloadLength = length - headerLength; assert payloadLength == payload.limit() : "Payload length does not match"; for (int i = 0; i < payloadLength / 2; ++i) { sum += ((payloadArray[payloadOffset + 2 * i] & 0xff) << 8) | (payloadArray[payloadOffset + 2 * i + 1] & 0xff); } if (payloadLength % 2 != 0) { sum += (payloadArray[payloadOffset + payloadLength - 1] & 0xff) << 8; } while ((sum & ~0xffff) != 0) { sum = (sum & 0xffff) + (sum >> 16); } setChecksum((short) ~sum); } TCPHeader(ByteBuffer raw); int getWindow(); @Override int getSourcePort(); @Override int getDestinationPort(); @Override void setSourcePort(int sourcePort); @Override void setDestinationPort(int destinationPort); int getSequenceNumber(); void setSequenceNumber(int sequenceNumber); int getAcknowledgementNumber(); void setAcknowledgementNumber(int acknowledgementNumber); @Override int getHeaderLength(); @Override void setPayloadLength(int payloadLength); int getFlags(); void setFlags(int flags); void shrinkOptions(); boolean isFin(); boolean isSyn(); boolean isRst(); boolean isPsh(); boolean isAck(); boolean isUrg(); @Override ByteBuffer getRaw(); @Override TCPHeader copyTo(ByteBuffer target); TCPHeader copy(); @Override void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload); short getChecksum(); static final int FLAG_FIN; static final int FLAG_SYN; static final int FLAG_RST; static final int FLAG_PSH; static final int FLAG_ACK; static final int FLAG_URG; }
@Test public void testComputeChecksum() { ByteBuffer buffer = createMockPacket(); buffer.flip(); IPv4Packet packet = new IPv4Packet(buffer); TCPHeader tcpHeader = (TCPHeader) packet.getTransportHeader(); buffer.putShort(36, (short) 0x79); tcpHeader.computeChecksum(packet.getIpv4Header(), packet.getPayload()); int sum = 0x1234 + 0x5678 + 0xa2a2 + 0x4242 + 0x0006 + 0x0018; sum += 0x1234 + 0x5678 + 0x0000 + 0x0111 + 0x0000 + 0x0222 + 0x5000 + 0x0000 + 0x0000 + 0x0000; sum += 0x1122 + 0xeeff; while ((sum & ~0xffff) != 0) { sum = (sum & 0xffff) + (sum >> 16); } short checksum = (short) ~sum; Assert.assertEquals(checksum, tcpHeader.getChecksum()); } @Ignore @Test public void benchComputeChecksum() { ByteBuffer buffer = createLongPacket(); buffer.flip(); IPv4Packet packet = new IPv4Packet(buffer); TCPHeader tcpHeader = (TCPHeader) packet.getTransportHeader(); long start = System.currentTimeMillis(); for (int i = 0; i < 5000000; ++i) { tcpHeader.computeChecksum(packet.getIpv4Header(), packet.getPayload()); } long duration = System.currentTimeMillis() - start; System.out.println("5000000 TCP checksums: " + duration + "ms"); }
TCPHeader implements TransportHeader { @Override public TCPHeader copyTo(ByteBuffer target) { raw.rewind(); ByteBuffer slice = Binary.slice(target, target.position(), getHeaderLength()); target.put(raw); return new TCPHeader(slice); } TCPHeader(ByteBuffer raw); int getWindow(); @Override int getSourcePort(); @Override int getDestinationPort(); @Override void setSourcePort(int sourcePort); @Override void setDestinationPort(int destinationPort); int getSequenceNumber(); void setSequenceNumber(int sequenceNumber); int getAcknowledgementNumber(); void setAcknowledgementNumber(int acknowledgementNumber); @Override int getHeaderLength(); @Override void setPayloadLength(int payloadLength); int getFlags(); void setFlags(int flags); void shrinkOptions(); boolean isFin(); boolean isSyn(); boolean isRst(); boolean isPsh(); boolean isAck(); boolean isUrg(); @Override ByteBuffer getRaw(); @Override TCPHeader copyTo(ByteBuffer target); TCPHeader copy(); @Override void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload); short getChecksum(); static final int FLAG_FIN; static final int FLAG_SYN; static final int FLAG_RST; static final int FLAG_PSH; static final int FLAG_ACK; static final int FLAG_URG; }
@Test public void testCopyTo() { ByteBuffer buffer = createMockTCPHeader(); TCPHeader header = new TCPHeader(buffer); ByteBuffer target = ByteBuffer.allocate(40); target.position(12); TCPHeader copy = header.copyTo(target); copy.setSourcePort(9999); Assert.assertEquals(32, target.position()); Assert.assertEquals("Header must modify target", 9999, target.getShort(12)); Assert.assertEquals("Header must not modify buffer", 0x1234, buffer.getShort(0)); }
CommandLineArguments { public static CommandLineArguments parse(int acceptedParameters, String... args) { CommandLineArguments arguments = new CommandLineArguments(); for (int i = 0; i < args.length; ++i) { String arg = args[i]; if ((acceptedParameters & PARAM_DNS_SERVER) != 0 && "-d".equals(arg)) { if (arguments.dnsServers != null) { throw new IllegalArgumentException("DNS servers already set"); } if (i == args.length - 1) { throw new IllegalArgumentException("Missing -d parameter"); } arguments.dnsServers = args[i + 1]; ++i; } else if ((acceptedParameters & PARAM_ROUTES) != 0 && "-r".equals(arg)) { if (arguments.routes != null) { throw new IllegalArgumentException("Routes already set"); } if (i == args.length - 1) { throw new IllegalArgumentException("Missing -r parameter"); } arguments.routes = args[i + 1]; ++i; } else if ((acceptedParameters & PARAM_PORT) != 0 && "-p".equals(arg)) { if (arguments.port != 0) { throw new IllegalArgumentException("Port already set"); } if (i == args.length - 1) { throw new IllegalArgumentException("Missing -p parameter"); } arguments.port = Integer.parseInt(args[i + 1]); if (arguments.port <= 0 || arguments.port >= 65536) { throw new IllegalArgumentException("Invalid port: " + arguments.port); } ++i; } else if ((acceptedParameters & PARAM_SERIAL) != 0 && arguments.serial == null) { arguments.serial = arg; } else { throw new IllegalArgumentException("Unexpected argument: \"" + arg + "\""); } } if (arguments.port == 0) { arguments.port = DEFAULT_PORT; } return arguments; } static CommandLineArguments parse(int acceptedParameters, String... args); String getSerial(); String getDnsServers(); String getRoutes(); int getPort(); static final int PARAM_NONE; static final int PARAM_SERIAL; static final int PARAM_DNS_SERVER; static final int PARAM_ROUTES; static final int PARAM_PORT; static final int DEFAULT_PORT; }
@Test(expected = IllegalArgumentException.class) public void testInvalidParameter() { CommandLineArguments.parse(ACCEPT_ALL, "myserial", "other"); } @Test(expected = IllegalArgumentException.class) public void testSerialWithNoDnsServersParameter() { CommandLineArguments.parse(ACCEPT_ALL, "myserial", "-d"); } @Test(expected = IllegalArgumentException.class) public void testNoDnsServersParameter() { CommandLineArguments.parse(ACCEPT_ALL, "-d"); } @Test(expected = IllegalArgumentException.class) public void testNoRoutesParameter() { CommandLineArguments.parse(ACCEPT_ALL, "-r"); }
AdbMonitor { static String readPacket(ByteBuffer input) { if (input.remaining() < LENGTH_FIELD_SIZE) { return null; } input.get(BUFFER, 0, LENGTH_FIELD_SIZE); int length = parseLength(BUFFER); if (length > BUFFER.length) { throw new IllegalArgumentException("Packet size should not be that big: " + length); } if (input.remaining() < length) { input.rewind(); return null; } input.get(BUFFER, 0, length); return new String(BUFFER, 0, length, StandardCharsets.UTF_8); } AdbMonitor(AdbDevicesCallback callback); void monitor(); }
@Test public void testReadValidPacket() { String data = "00180123456789ABCDEF\tdevice\n"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\n", result); } @Test public void testReadValidPackets() { String data = "00300123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n", result); } @Test public void testReadValidPacketWithGarbage() { String data = "00180123456789ABCDEF\tdevice\ngarbage"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\n", result); } @Test public void testReadShortPacket() { String data = "00180123456789ABCDEF\tdevi"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertNull(result); }
IPv4Header { public static int readVersion(ByteBuffer buffer) { if (buffer.limit() == 0) { return -1; } byte versionAndIHL = buffer.get(0); return (versionAndIHL & 0xf0) >> 4; } IPv4Header(ByteBuffer raw); boolean isSupported(); Protocol getProtocol(); int getHeaderLength(); int getTotalLength(); void setTotalLength(int totalLength); int getSource(); int getDestination(); void setSource(int source); void setDestination(int destination); void swapSourceAndDestination(); ByteBuffer getRaw(); IPv4Header copyTo(ByteBuffer target); IPv4Header copy(); void computeChecksum(); short getChecksum(); static int readVersion(ByteBuffer buffer); static int readLength(ByteBuffer buffer); }
@Test public void testReadIPVersionUnavailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.flip(); int firstPacketVersion = IPv4Header.readVersion(buffer); Assert.assertEquals("IPv4 packet version must be unknown", -1, firstPacketVersion); } @Test public void testReadIPVersionAvailable() { ByteBuffer buffer = ByteBuffer.allocate(20); byte versionAndIHL = (4 << 4) | 5; buffer.put(versionAndIHL); buffer.flip(); int firstPacketVersion = IPv4Header.readVersion(buffer); Assert.assertEquals("Wrong IP version field value", 4, firstPacketVersion); }
AdbMonitor { void handlePacket(String packet) { List<String> currentConnectedDevices = parseConnectedDevices(packet); for (String serial : currentConnectedDevices) { if (!connectedDevices.contains(serial)) { callback.onNewDeviceConnected(serial); } } connectedDevices = currentConnectedDevices; } AdbMonitor(AdbDevicesCallback callback); void monitor(); }
@Test public void testHandlePacketDevice() { final String[] pSerial = new String[1]; AdbMonitor monitor = new AdbMonitor((serial) -> pSerial[0] = serial); String packet = "0123456789ABCDEF\tdevice\n"; monitor.handlePacket(packet); Assert.assertEquals("0123456789ABCDEF", pSerial[0]); } @Test public void testHandlePacketOffline() { final String[] pSerial = new String[1]; AdbMonitor monitor = new AdbMonitor((serial) -> pSerial[0] = serial); String packet = "0123456789ABCDEF\toffline\n"; monitor.handlePacket(packet); Assert.assertNull(pSerial[0]); } @Test public void testMultipleConnectedDevices() { final String[] pSerials = new String[2]; AdbMonitor monitor = new AdbMonitor(new AdbMonitor.AdbDevicesCallback() { private int i; @Override public void onNewDeviceConnected(String serial) { pSerials[i++] = serial; } }); String packet = "0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; monitor.handlePacket(packet); Assert.assertEquals("0123456789ABCDEF", pSerials[0]); Assert.assertEquals("FEDCBA9876543210", pSerials[1]); } @Test @SuppressWarnings("checkstyle:MagicNumber") public void testMultipleConnectedDevicesWithDisconnection() { final String[] pSerials = new String[3]; AdbMonitor monitor = new AdbMonitor(new AdbMonitor.AdbDevicesCallback() { private int i; @Override public void onNewDeviceConnected(String serial) { pSerials[i++] = serial; } }); String packet = "0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; monitor.handlePacket(packet); packet = "0123456789ABCDEF\tdevice\n"; monitor.handlePacket(packet); packet = "0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; monitor.handlePacket(packet); Assert.assertEquals("0123456789ABCDEF", pSerials[0]); Assert.assertEquals("FEDCBA9876543210", pSerials[1]); Assert.assertEquals("FEDCBA9876543210", pSerials[2]); }
IPv4Header { public static int readLength(ByteBuffer buffer) { if (buffer.limit() < 4) { return -1; } return Short.toUnsignedInt(buffer.getShort(2)); } IPv4Header(ByteBuffer raw); boolean isSupported(); Protocol getProtocol(); int getHeaderLength(); int getTotalLength(); void setTotalLength(int totalLength); int getSource(); int getDestination(); void setSource(int source); void setDestination(int destination); void swapSourceAndDestination(); ByteBuffer getRaw(); IPv4Header copyTo(ByteBuffer target); IPv4Header copy(); void computeChecksum(); short getChecksum(); static int readVersion(ByteBuffer buffer); static int readLength(ByteBuffer buffer); }
@Test public void testReadLengthUnavailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.flip(); int firstPacketLength = IPv4Header.readLength(buffer); Assert.assertEquals("IPv4 packet length must be unknown", -1, firstPacketLength); } @Test public void testReadLengthAvailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.put(2, (byte) 0x01); buffer.put(3, (byte) 0x23); buffer.position(20); buffer.flip(); int firstPacketLength = IPv4Header.readLength(buffer); Assert.assertEquals("Wrong IP length field value", 0x123, firstPacketLength); }
IPv4Header { public void computeChecksum() { setChecksum((short) 0); byte[] rawArray = raw.array(); int rawArrayOffset = raw.arrayOffset(); int sum = 0; for (int i = 0; i < headerLength / 2; ++i) { sum += (rawArray[rawArrayOffset + 2 * i] & 0xff) << 8 | (rawArray[rawArrayOffset + 2 * i + 1] & 0xff); } while ((sum & ~0xffff) != 0) { sum = (sum & 0xffff) + (sum >> 16); } setChecksum((short) ~sum); } IPv4Header(ByteBuffer raw); boolean isSupported(); Protocol getProtocol(); int getHeaderLength(); int getTotalLength(); void setTotalLength(int totalLength); int getSource(); int getDestination(); void setSource(int source); void setDestination(int destination); void swapSourceAndDestination(); ByteBuffer getRaw(); IPv4Header copyTo(ByteBuffer target); IPv4Header copy(); void computeChecksum(); short getChecksum(); static int readVersion(ByteBuffer buffer); static int readLength(ByteBuffer buffer); }
@Test public void testComputeChecksum() { ByteBuffer buffer = createMockHeaders(); IPv4Header header = new IPv4Header(buffer); buffer.putShort(10, (short) 0x79); header.computeChecksum(); int sum = 0x4500 + 0x001c + 0x0000 + 0x0000 + 0x0011 + 0x0000 + 0x1234 + 0x5678 + 0x4242 + 0x4242; while ((sum & ~0xffff) != 0) { sum = (sum & 0xffff) + (sum >> 16); } short checksum = (short) ~sum; Assert.assertEquals(checksum, header.getChecksum()); } @Ignore @Test public void benchComputeChecksum() { ByteBuffer buffer = createMockHeaders(); IPv4Header header = new IPv4Header(buffer); long start = System.currentTimeMillis(); for (int i = 0; i < 5000000; ++i) { header.computeChecksum(); } long duration = System.currentTimeMillis() - start; System.out.println("5000000 IP checksums: " + duration + "ms"); }
IPv4Packet { public ByteBuffer getPayload() { int headersLength = ipv4Header.getHeaderLength() + transportHeader.getHeaderLength(); raw.position(headersLength); return raw.slice(); } IPv4Packet(ByteBuffer raw); boolean isValid(); IPv4Header getIpv4Header(); TransportHeader getTransportHeader(); void swapSourceAndDestination(); ByteBuffer getRaw(); int getRawLength(); ByteBuffer getPayload(); int getPayloadLength(); void computeChecksums(); @SuppressWarnings("checkstyle:MagicNumber") static final int MAX_PACKET_LENGTH; }
@Test public void testPayload() { ByteBuffer buffer = createMockPacket(); IPv4Packet packet = new IPv4Packet(buffer); ByteBuffer payload = packet.getPayload(); Assert.assertEquals(0x11223344, payload.getInt(0)); }
Packetizer { public IPv4Packet packetize(ReadableByteChannel channel, int maxChunkSize) throws IOException { payloadBuffer.limit(maxChunkSize).position(0); int payloadLength = channel.read(payloadBuffer); if (payloadLength == -1) { return null; } payloadBuffer.flip(); return inflate(); } Packetizer(IPv4Header ipv4Header, TransportHeader transportHeader); IPv4Header getResponseIPv4Header(); TransportHeader getResponseTransportHeader(); IPv4Packet packetizeEmptyPayload(); IPv4Packet packetize(ReadableByteChannel channel, int maxChunkSize); IPv4Packet packetize(ReadableByteChannel channel); }
@Test public void testMergeHeadersAndPayload() throws IOException { IPv4Packet referencePacket = new IPv4Packet(createMockPacket()); IPv4Header ipv4Header = referencePacket.getIpv4Header(); TransportHeader transportHeader = referencePacket.getTransportHeader(); byte[] data = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88}; ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream(data)); Packetizer packetizer = new Packetizer(ipv4Header, transportHeader); IPv4Packet packet = packetizer.packetize(channel); Assert.assertEquals(36, packet.getIpv4Header().getTotalLength()); ByteBuffer packetPayload = packet.getPayload(); Assert.assertEquals(8, packetPayload.remaining()); Assert.assertEquals(0x1122334455667788L, packetPayload.getLong()); } @Test public void testPacketizeChunks() throws IOException { IPv4Packet originalPacket = new IPv4Packet(createMockPacket()); IPv4Header ipv4Header = originalPacket.getIpv4Header(); TransportHeader transportHeader = originalPacket.getTransportHeader(); byte[] data = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88}; ReadableByteChannel channel = Channels.newChannel(new ByteArrayInputStream(data)); Packetizer packetizer = new Packetizer(ipv4Header, transportHeader); IPv4Packet packet = packetizer.packetize(channel, 2); ByteBuffer packetPayload = packet.getPayload(); Assert.assertEquals(30, packet.getIpv4Header().getTotalLength()); Assert.assertEquals(2, packetPayload.remaining()); Assert.assertEquals(0x1122, Short.toUnsignedInt(packetPayload.getShort())); packet = packetizer.packetize(channel, 3); packetPayload = packet.getPayload(); Assert.assertEquals(31, packet.getIpv4Header().getTotalLength()); Assert.assertEquals(3, packetPayload.remaining()); Assert.assertEquals(0x33, packetPayload.get()); Assert.assertEquals(0x44, packetPayload.get()); Assert.assertEquals(0x55, packetPayload.get()); packet = packetizer.packetize(channel, 1024); packetPayload = packet.getPayload(); Assert.assertEquals(31, packet.getIpv4Header().getTotalLength()); Assert.assertEquals(3, packetPayload.remaining()); Assert.assertEquals(0x66, packetPayload.get()); Assert.assertEquals(0x77, packetPayload.get()); Assert.assertEquals((byte) 0x88, packetPayload.get()); }
AlternativeUriNavigator { @Deprecated public List<String> listAlternativeUris(String uri) { String canonicalURI = uriMapping.getCanonicalURI(uri); List<String> alternativeURIs = getAlternativeUriMap().get(canonicalURI); if (alternativeURIs == null) { return Collections.singletonList(uri); } else { return alternativeURIs; } } AlternativeUriNavigator(UriMappingIterable uriMapping); @Deprecated List<String> listAlternativeUris(String uri); List<URI> listAlternativeUris(URI uri); @Deprecated boolean hasAlternativeUris(String uri); boolean hasAlternativeUris(URI uri); }
@Test public void listsAlternativesCorrectly() throws Exception { UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(ImmutableSet.of( "http: "http: "http: )); uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: Set<String> setA = ImmutableSet.of("http: Set<String> setB = ImmutableSet.of("http: Set<String> setC = ImmutableSet.of("http: Set<String> setD = ImmutableSet.of("http: AlternativeUriNavigator alternativeURINavigator = new AlternativeUriNavigator(uriMapping); assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: assertThat(ImmutableSet.copyOf(alternativeURINavigator.listAlternativeUris("http: }
ResourceDescriptionConflictResolverImpl implements ResourceDescriptionConflictResolver { @Override public Collection<ResolvedStatement> resolveConflicts(ResourceDescription resourceDescription) throws ConflictResolutionException { int inputStatementCount = resourceDescription.getDescribingStatements().size(); long startTime = logStarted(inputStatementCount); ConflictClustersMap conflictClustersMap = ConflictClustersMap.fromCollection(resourceDescription.getDescribingStatements(), uriMapping); ResolvedResult totalResult = new ResolvedResult(); Resource canonicalResource = uriMapping.mapResource(resourceDescription.getResource()); Collection<ResolvedStatement> resourceResolvedStatements = resolveResource( conflictClustersMap.getResourceStatementsMap(canonicalResource), canonicalResource, totalResult, conflictClustersMap, new HashSet<Resource>(1)); totalResult.addToResult(resourceResolvedStatements); logFinished(startTime, inputStatementCount, totalResult); return totalResult.getResult(); } ResourceDescriptionConflictResolverImpl( ResolutionFunctionRegistry resolutionFunctionRegistry, ConflictResolutionPolicy conflictResolutionPolicy, UriMapping uriMapping, Model metadata, String resolvedGraphsURIPrefix, // TODO: replace with UriGenerator class generating uris both for contexts and generated dependent resources NestedResourceDescriptionQualityCalculator nestedResourceDescriptionQualityCalculator); @Override Collection<ResolvedStatement> resolveConflicts(ResourceDescription resourceDescription); static final ResolutionStrategy DEFAULT_RESOLUTION_STRATEGY; static final String DEFAULT_RESOLVED_GRAPHS_URI_PREFIX; }
@Test public void resolvesStatementWithEmptyGraph() throws Exception { Resource resource = createHttpUri("s"); ResourceDescriptionConflictResolver resolver = createResolver(); Statement inputStatement = createHttpStatement("s", "p", "o", null); Collection<Statement> testInput = ImmutableList.of(inputStatement); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); ResolvedStatement resultStatement = Iterables.getOnlyElement(result); assertThat(resultStatement, resolvedStatementMatchesStatement(inputStatement)); } @Test public void resolvesDependentPropertiesTogether() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d2", "oa2", "bad"), createHttpStatement("sa", "d3", "oa3", "good"), createHttpStatement("sb", "d1", "ob1", "bad"), createHttpStatement("sb", "d2", "ob2", "good"), createHttpStatement("sb", "d3", "ob3", "bad"), createHttpStatement("sa", "d4", "oa4", "bad"), createHttpStatement("sb", "d4", "ob4", "good") ); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d3"))) .with(createHttpUri("d2"), resolutionStrategyWithDependsOn(createHttpUri("d3"))) .build(); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of( createHttpStatement("sx", "d1", "oa1"), createHttpStatement("sx", "d2", "oa2"), createHttpStatement("sx", "d3", "oa3"), createHttpStatement("sx", "d4", "ob4")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void mapsStatementsWithDependentPropertiesCorrectly() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "pa", "oa", "ga"), createHttpStatement("sb", "pb", "ob", "gb") ); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("dpa"), resolutionStrategyWithDependsOn(createHttpUri("pb"))) .build(); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, new MockNoneResolutionFunction()); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of(createHttpStatement("sx", "px", "ox")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void resolvesDependentPropertyGroupsCorrectly() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d2", "oa2", "good"), createHttpStatement("sa", "d3", "oa3", "bad"), createHttpStatement("sa", "d4", "oa4", "good"), createHttpStatement("sa", "d5", "oa5", "bad"), createHttpStatement("sb", "d1", "ob1", "bad"), createHttpStatement("sb", "d2", "ob2", "bad"), createHttpStatement("sb", "d3", "ob3", "good"), createHttpStatement("sb", "d4", "ob4", "bad"), createHttpStatement("sb", "d5", "ob5", "good") ); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .with(createHttpUri("d3"), resolutionStrategyWithDependsOn(createHttpUri("d4"))) .with(createHttpUri("d4"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .build(); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of( createHttpStatement("sx", "d1", "oa1"), createHttpStatement("sx", "d2", "oa2"), createHttpStatement("sx", "d3", "oa3"), createHttpStatement("sx", "d4", "oa4"), createHttpStatement("sx", "d5", "ob5")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void choosesBestStatementForDependentProperties() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d1", "oa1", "bad"), createHttpStatement("sa", "d2", "oa2", "good"), createHttpStatement("sb", "d1", "ob1", "good"), createHttpStatement("sb", "d2", "ob2", "good")); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .build(); ResolutionFunction resolutionFunction = MockNoneResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of( createHttpStatement("sx", "d1", "ob1"), createHttpStatement("sx", "d2", "ob2")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void removesDuplicatesWithDependentProperties() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa", "ga"), createHttpStatement("sa", "d1", "oa", "ga"), createHttpStatement("sb", "d1", "ob", "gb"), createHttpStatement("sb", "d1", "ob", "gb")); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .build(); ResolutionFunction resolutionFunction = new MockNoneResolutionFunction(); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of(createHttpStatement("sx", "d1", "ox")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void resolvesWithDependentPropertiesCorrectlyWhenSomePropertiesMissing() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d3", "oa3", "good"), createHttpStatement("sb", "d1", "ob1", "good"), createHttpStatement("sb", "d2", "ob2", "good"), createHttpStatement("sb", "d3", "ob3", "bad"), createHttpStatement("sa", "d4", "oa4", "good"), createHttpStatement("sb", "d5", "ob5", "bad")); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d3"))) .with(createHttpUri("d2"), resolutionStrategyWithDependsOn(createHttpUri("d3"))) .with(createHttpUri("d4"), resolutionStrategyWithDependsOn(createHttpUri("d5"))) .build(); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of( createHttpStatement("sx", "d1", "ob1"), createHttpStatement("sx", "d2", "ob2"), createHttpStatement("sx", "d3", "ob3"), createHttpStatement("sx", "d4", "oa4")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } } @Test public void resolvesIntraSourceConflictsWithDependentProperties() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "bad"), createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d2", "oa2", "good"), createHttpStatement("sb", "d1", "ob1", "bad"), createHttpStatement("sb", "d1", "ob1", "good"), createHttpStatement("sb", "d2", "ob2", "bad")); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .build(); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.of( createHttpStatement("sx", "d1", "oa1"), createHttpStatement("sx", "d2", "oa2")); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } for (ResolvedStatement resolvedStatement : result) { assertThat(resolvedStatement.getSourceGraphNames(), is((Collection<Resource>) Collections.singleton((Resource) createHttpUri("good")))); } } @Test public void usesCorrectConflictingStatementsWithDependentProperties() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa1", "good"), createHttpStatement("sa", "d1", "oa2", "bad"), createHttpStatement("sb", "d1", "ob1", "bad"), createHttpStatement("sb", "d1", "ob2", "bad"), createHttpStatement("s1", "d1", "o11", "bad")); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))) .build(); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, new MockNoneResolutionFunction()); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Map<URI, Collection<Statement>> expectedConflictingStatementsMap = new HashMap<>(); expectedConflictingStatementsMap.put(createHttpUri("sx"), ImmutableList.of( createHttpStatement("sx", "d1", "oa1", "good"), createHttpStatement("sx", "d1", "oa2", "bad"), createHttpStatement("sx", "d1", "ob1", "bad"), createHttpStatement("sx", "d1", "ob2", "bad"))); expectedConflictingStatementsMap.put(createHttpUri("s1"), ImmutableList.of( createHttpStatement("s1", "d1", "o11", "bad"))); assertThat(result, hasSize(expectedConflictingStatementsMap.size())); for (ResolvedStatement resolvedStatement : result) { MockResolvedStatement mockResolvedStatement = (MockResolvedStatement) resolvedStatement; Collection<Statement> expectedConflictingStatements = expectedConflictingStatementsMap.get(resolvedStatement.getStatement().getSubject()); assertThat(mockResolvedStatement.getConflictingStatements(), containsInAnyOrder(expectedConflictingStatements.toArray())); } } @Test public void contextConflictingStatementsAreMapped() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "p1", "oa", "good"), createHttpStatement("sb", "p1", "ob", "bad")); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy().build(); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); MockResolvedStatement resolvedStatement = (MockResolvedStatement) Iterables.getOnlyElement(result); Collection<Statement> expectedConflictingStatements = ImmutableList.of( createHttpStatement("sx", "p1", "ox", "good"), createHttpStatement("sx", "p1", "ox", "bad")); Collection<Statement> actualConflictingStatements = resolvedStatement.getConflictingStatements(); assertThat(actualConflictingStatements, containsInAnyOrder(expectedConflictingStatements.toArray())); } @Test public void contextConflictingStatementsAreMappedWithDependentProperties() throws Exception { Resource resource = createHttpUri("sx"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "d1", "oa", "good"), createHttpStatement("sb", "d1", "ob", "bad"), createHttpStatement("sa", "d2", "o1", "bad")); ResolutionFunction resolutionFunction = MockBestResolutionFunctionWithQuality.newResolutionFunction() .withQuality(createHttpUri("good"), 0.9) .withQuality(createHttpUri("bad"), 0.2); ConflictResolutionPolicy conflictResolutionPolicy = ConflictResolutionPolicyBuilder.newPolicy() .with(createHttpUri("d1"), resolutionStrategyWithDependsOn(createHttpUri("d2"))).build(); ResourceDescriptionConflictResolver resolver = createResolver(conflictResolutionPolicy, resolutionFunction); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); MockResolvedStatement resolvedStatement = (MockResolvedStatement) getFirstStatementWithProperty(result, createHttpUri("d1")); Collection<Statement> expectedConflictingStatements = ImmutableList.of( createHttpStatement("sx", "d1", "ox", "good"), createHttpStatement("sx", "d1", "ox", "bad")); Collection<Statement> actualConflictingStatements = resolvedStatement.getConflictingStatements(); assertThat(actualConflictingStatements, containsInAnyOrder(expectedConflictingStatements.toArray())); } @Test public void splitsToCorrectConflictClusters() throws Exception { Resource resource = createHttpUri("s4"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s4", "p1", "o1", "g1"), createHttpStatement("s4", "p1", "o1", "g2"), createHttpStatement("s4", "p2", "o1", "g1"), createHttpStatement("s4", "p2", "o2", "g2"), createHttpStatement("s4", "p3", "o1", "g1"), createHttpStatement("s4", "p3", "o2", "g2"), createHttpStatement("s4", "p3", "o2", "g2") ); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Collection<MockResolvedStatement>> conflictClusters = getConflictClusters(result); for (Collection<MockResolvedStatement> conflictCluster : conflictClusters) { MockResolvedStatement first = conflictCluster.iterator().next(); for (MockResolvedStatement mockResolvedStatement : conflictCluster) { assertThat(mockResolvedStatement.getStatement().getSubject(), is(first.getStatement().getSubject())); assertThat(mockResolvedStatement.getStatement().getPredicate(), is(first.getStatement().getPredicate())); } } } @Test public void processesAllConflictClusters() throws Exception { Resource resource = createHttpUri("s4"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s4", "p1", "o1", "g1"), createHttpStatement("s4", "p1", "o1", "g2"), createHttpStatement("s4", "p2", "o1", "g1"), createHttpStatement("s4", "p2", "o2", "g2"), createHttpStatement("s4", "p3", "o1", "g1"), createHttpStatement("s4", "p3", "o2", "g2"), createHttpStatement("s4", "p3", "o2", "g2") ); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Set<Pair<Resource, URI>> expectedClusterSubjectPredicates = new HashSet<>(); expectedClusterSubjectPredicates.add(Pair.create((Resource) createHttpUri("s4"), createHttpUri("p1"))); expectedClusterSubjectPredicates.add(Pair.create((Resource) createHttpUri("s4"), createHttpUri("p2"))); expectedClusterSubjectPredicates.add(Pair.create((Resource) createHttpUri("s4"), createHttpUri("p3"))); Set<Pair<Resource, URI>> actualClusterSubjectPredicates = new HashSet<>(); for (ResolvedStatement resolvedStatement : result) { actualClusterSubjectPredicates.add(Pair.create( resolvedStatement.getStatement().getSubject(), resolvedStatement.getStatement().getPredicate())); } assertThat(actualClusterSubjectPredicates, is(expectedClusterSubjectPredicates)); } @Test public void processesAllConflictClustersWithUriMapping() throws Exception { Resource resource = createHttpUri("sa"); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "pa", "oa", "g1"), createHttpStatement("sb", "pb", "ob", "g1"), createHttpStatement("sa", "p1", "oa", "ga") ); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Set<Pair<Resource, URI>> expectedClusterSubjectPredicates = new HashSet<>(); expectedClusterSubjectPredicates.add(Pair.create((Resource) createHttpUri("sx"), createHttpUri("px"))); expectedClusterSubjectPredicates.add(Pair.create((Resource) createHttpUri("sx"), createHttpUri("p1"))); Set<Pair<Resource, URI>> actualClusterSubjectPredicates = new HashSet<>(); for (ResolvedStatement resolvedStatement : result) { actualClusterSubjectPredicates.add(Pair.create( resolvedStatement.getStatement().getSubject(), resolvedStatement.getStatement().getPredicate())); } assertThat(actualClusterSubjectPredicates, is(expectedClusterSubjectPredicates)); } @Test public void resolvesOnlySpecifiedResource() throws Exception { Resource resource = createHttpUri("sx"); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s2", "p2", "o1", "g1"), createHttpStatement("sa", "p1", "oa", "g1"), createHttpStatement("sb", "p2", "oa", "g1"), createHttpStatement("oa", "pa", "o1"), createHttpStatement("o1", "p1", "oa") ); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); for (ResolvedStatement resolvedStatement : result) { assertThat(resolvedStatement.getStatement().getSubject(), is(resource)); } assertThat(result, hasSize(2)); } @Test public void removesDuplicates() throws Exception { Resource resource = createHttpUri("sx"); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "pa", "oa", "g1"), createHttpStatement("sb", "pb", "ob", "g1"), createHttpStatement("sa", "p1", "oa", "ga"), createHttpStatement("sx", "p1", "o1", "g1"), createHttpStatement("sx", "p1", "o1", "g1"), createHttpStatement("sx", "p1", "o1", "g2") ); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); List<ResolvedStatement> expectedStatements = ImmutableList.of( (ResolvedStatement) new ResolvedStatementImpl(createHttpStatement("sx", "px", "ox"), 0, ImmutableSet.of((Resource) createHttpUri("g1"))), new ResolvedStatementImpl(createHttpStatement("sx", "p1", "ox"), 0, ImmutableSet.of((Resource) createHttpUri("ga"))), new ResolvedStatementImpl(createHttpStatement("sx", "p1", "o1"), 0, ImmutableSet.of((Resource) createHttpUri("g1"))), new ResolvedStatementImpl(createHttpStatement("sx", "p1", "o1"), 0, ImmutableSet.of((Resource) createHttpUri("g2")))); assertThat(result, hasSize(expectedStatements.size())); for (ResolvedStatement expectedStatement : expectedStatements) { assertThat(result, hasItem(allOf( resolvedStatementMatchesStatement(expectedStatement.getStatement()), resolvedStatementMatchesSources((Set<Resource>) expectedStatement.getSourceGraphNames())))); } } @Test public void mapsUris() throws Exception { Resource resource = createHttpUri("sx"); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<Statement> testInput = ImmutableList.of( createHttpStatement("sa", "pa", "oa", "g1"), createHttpStatement("sb", "pb", "ob", "g2"), createHttpStatement("sa", "p1", "oa", "ga") ); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); List<ResolvedStatement> expectedStatements = ImmutableList.of( (ResolvedStatement) new ResolvedStatementImpl(createHttpStatement("sx", "px", "ox"), 0, ImmutableSet.of((Resource) createHttpUri("g1"))), new ResolvedStatementImpl(createHttpStatement("sx", "px", "ox"), 0, ImmutableSet.of((Resource) createHttpUri("g2"))), new ResolvedStatementImpl(createHttpStatement("sx", "p1", "ox"), 0, ImmutableSet.of((Resource) createHttpUri("ga")))); assertThat(result, hasSize(expectedStatements.size())); for (ResolvedStatement expectedStatement : expectedStatements) { assertThat(result, hasItem(allOf( resolvedStatementMatchesStatement(expectedStatement.getStatement()), resolvedStatementMatchesSources((Set<Resource>) expectedStatement.getSourceGraphNames())))); } } @Test public void resolvesEmptyInput() throws Exception { Resource resource = createHttpUri("sx"); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<Statement> testInput = ImmutableList.of(); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); assertThat(result, empty()); } @Test public void resolvesBlankNodes() throws Exception { Resource resource = VF.createBNode("bnode1"); ResourceDescriptionConflictResolver resolver = createResolver(); Collection<Statement> testInput = ImmutableList.of( VF.createStatement(resource, createHttpUri("p1"), VF.createLiteral("a"), createHttpUri("g1")), VF.createStatement(resource, createHttpUri("p1"), resource, createHttpUri("g1")) ); Collection<ResolvedStatement> result = resolver.resolveConflicts(new ResourceDescriptionImpl(resource, testInput)); Collection<Statement> expectedStatements = ImmutableList.copyOf(testInput); assertThat(result, hasSize(expectedStatements.size())); for (Statement expectedStatement : expectedStatements) { assertThat(result, hasItem(resolvedStatementMatchesStatement(expectedStatement))); } }
AlternativeUriNavigator { @Deprecated public boolean hasAlternativeUris(String uri) { String canonicalURI = uriMapping.getCanonicalURI(uri); List<String> alternativeURIs = getAlternativeUriMap().get(canonicalURI); return alternativeURIs != null && alternativeURIs.size() > 1; } AlternativeUriNavigator(UriMappingIterable uriMapping); @Deprecated List<String> listAlternativeUris(String uri); List<URI> listAlternativeUris(URI uri); @Deprecated boolean hasAlternativeUris(String uri); boolean hasAlternativeUris(URI uri); }
@Test public void hasAlternativeUrisWorksCorrectly() throws Exception { UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(ImmutableSet.of( "http: "http: "http: )); uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: Set<String> setA = ImmutableSet.of("http: Set<String> setB = ImmutableSet.of("http: Set<String> setC = ImmutableSet.of("http: Set<String> setD = ImmutableSet.of("http: AlternativeUriNavigator alternativeURINavigator = new AlternativeUriNavigator(uriMapping); assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: }
LDFusionToolExecutor implements FusionExecutor { @Override public void fuse(ResourceDescriptionConflictResolver conflictResolver, InputLoader inputLoader, CloseableRDFWriter rdfWriter) throws LDFusionToolException, ConflictResolutionException, IOException { long outputTriples = 0; long inputTriples = 0; boolean checkMaxOutputTriples = maxOutputTriples != null && maxOutputTriples >= 0; LOG.info("Starting conflict resolution"); timeProfiler.startCounter(EnumFusionCounters.BUFFERING); while (!isCanceled() && inputLoader.hasNext()) { timeProfiler.stopAddCounter(EnumFusionCounters.BUFFERING); timeProfiler.startCounter(EnumFusionCounters.QUAD_LOADING); ResourceDescription resourceDescription = inputLoader.next(); inputTriples += resourceDescription.getDescribingStatements().size(); timeProfiler.stopAddCounter(EnumFusionCounters.QUAD_LOADING); timeProfiler.startCounter(EnumFusionCounters.INPUT_FILTERING); boolean accept = this.resourceDescriptionFilter.accept(resourceDescription); timeProfiler.stopAddCounter(EnumFusionCounters.INPUT_FILTERING); if (!accept) { LOG.debug("Resource {} doesn't match filter, skipping", resourceDescription.getResource()); timeProfiler.startCounter(EnumFusionCounters.BUFFERING); continue; } timeProfiler.startCounter(EnumFusionCounters.CONFLICT_RESOLUTION); Collection<ResolvedStatement> resolvedQuads = conflictResolver.resolveConflicts(resourceDescription); timeProfiler.stopAddCounter(EnumFusionCounters.CONFLICT_RESOLUTION); LOG.debug("Resolved {} quads resulting in {} quads (processed totally {} quads)", new Object[] {resourceDescription.getDescribingStatements().size(), resolvedQuads.size(), inputTriples}); if (checkMaxOutputTriples && outputTriples + resolvedQuads.size() > maxOutputTriples) { break; } outputTriples += resolvedQuads.size(); timeProfiler.startCounter(EnumFusionCounters.BUFFERING); inputLoader.updateWithResolvedStatements(resolvedQuads); timeProfiler.stopAddCounter(EnumFusionCounters.BUFFERING); timeProfiler.startCounter(EnumFusionCounters.OUTPUT_WRITING); rdfWriter.writeResolvedStatements(resolvedQuads); timeProfiler.stopAddCounter(EnumFusionCounters.OUTPUT_WRITING); memoryProfiler.capture(); fixVirtuosoOpenedStatements(); timeProfiler.startCounter(EnumFusionCounters.BUFFERING); } timeProfiler.stopAddCounter(EnumFusionCounters.BUFFERING); if (isCanceled()) { LOG.warn("The execution was canceled!"); } LOG.info(String.format("Processed %,d quads which were resolved to %,d output quads.", inputTriples, outputTriples)); } LDFusionToolExecutor( boolean hasVirtuosoSource, Long maxOutputTriples, ResourceDescriptionFilter resourceDescriptionFilter, ProfilingTimeCounter<EnumFusionCounters> timeProfiler, MemoryProfiler memoryProfiler); @Override void fuse(ResourceDescriptionConflictResolver conflictResolver, InputLoader inputLoader, CloseableRDFWriter rdfWriter); Long getMaxOutputTriples(); ResourceDescriptionFilter getResourceDescriptionFilter(); void setIsCanceledCallback(IsCanceledCallback isCanceledCallback); }
@Test public void processesAllInputStatements() throws Exception { FusionExecutor executor = getLDFusionToolExecutor(Long.MAX_VALUE, false); TestInputLoader inputLoader = new TestInputLoader(ImmutableList.of( (Collection<Statement>) ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g2")), ImmutableList.of( createHttpStatement("s2", "p2", "o1", "g3"), createHttpStatement("s2", "p2", "o2", "g3")) )); TestRDFWriter rdfWriter = new TestRDFWriter(); executor.fuse(new TestConflictResolver(), inputLoader, rdfWriter); List<ResolvedStatement> resolvedStatements = rdfWriter.getCollectedResolvedStatements(); assertThat(resolvedStatements.get(0).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s1", "p1", "o1", "g1"))); assertThat(resolvedStatements.get(1).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s1", "p1", "o1", "g2"))); assertThat(resolvedStatements.get(2).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s2", "p2", "o1", "g3"))); assertThat(resolvedStatements.get(3).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s2", "p2", "o2", "g3"))); } @Test public void respectsMaxOutputTriples() throws Exception { long maxOutputTriples = 5; FusionExecutor executor = getLDFusionToolExecutor(maxOutputTriples, false); TestInputLoader inputLoader = new TestInputLoader(ImmutableList.<Collection<Statement>>of( ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g2")), ImmutableList.of( createHttpStatement("s2", "p1", "o1", "g1"), createHttpStatement("s2", "p1", "o1", "g2")), ImmutableList.of( createHttpStatement("s3", "p1", "o1", "g1"), createHttpStatement("s3", "p1", "o1", "g2")) )); TestRDFWriter rdfWriter = new TestRDFWriter(); executor.fuse(new TestConflictResolver(), inputLoader, rdfWriter); List<ResolvedStatement> resolvedStatements = rdfWriter.getCollectedResolvedStatements(); Assert.assertTrue(resolvedStatements.size() <= maxOutputTriples); Assert.assertTrue(resolvedStatements.size() >= maxOutputTriples % 2); } @Test public void suppliesAllQuadsInClusterToConflictResolver() throws Exception { long maxOutputTriples = 5; FusionExecutor executor = getLDFusionToolExecutor(maxOutputTriples, false); ImmutableList<Collection<Statement>> inputStatements = ImmutableList.<Collection<Statement>>of( ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g2"), createHttpStatement("s1", "p1", "o1", "g3")), ImmutableList.of( createHttpStatement("s2", "p1", "o1", "g1")), ImmutableList.of( createHttpStatement("s3", "p1", "o1", "g1"), createHttpStatement("s3", "p1", "o1", "g2")) ); TestInputLoader inputLoader = new TestInputLoader(inputStatements); CloseableRDFWriter rdfWriter = Mockito.mock(CloseableRDFWriter.class); TestConflictResolver conflictResolver = new TestConflictResolver(); executor.fuse(conflictResolver, inputLoader, rdfWriter); assertThat(conflictResolver.getCollectedStatements().size(), equalTo(inputStatements.size())); for (int i = 0; i < inputStatements.size(); i++) { assertThat(conflictResolver.getCollectedStatements().get(i), equalTo(inputStatements.get(i))); } } @Test public void updatesInputLoaderWithResolvedStatements() throws Exception { long maxOutputTriples = 5; FusionExecutor executor = getLDFusionToolExecutor(maxOutputTriples, false); ImmutableList<Collection<Statement>> inputStatements = ImmutableList.<Collection<Statement>>of( ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g2"), createHttpStatement("s1", "p1", "o1", "g3")), ImmutableList.of( createHttpStatement("s2", "p1", "o1", "g1")), ImmutableList.of( createHttpStatement("s3", "p1", "o1", "g1"), createHttpStatement("s3", "p1", "o1", "g2")) ); TestInputLoader inputLoader = new TestInputLoader(inputStatements); TestRDFWriter rdfWriter = new TestRDFWriter(); TestConflictResolver conflictResolver = new TestConflictResolver(); executor.fuse(conflictResolver, inputLoader, rdfWriter); assertThat(inputLoader.getCollectedResolvedStatements(), equalTo(rdfWriter.collectedResolvedStatements)); } @Test public void processesAllInputStatementsWhenHasVirtuosoSource() throws Exception { FusionExecutor executor = getLDFusionToolExecutor(Long.MAX_VALUE, true); TestInputLoader inputLoader = new TestInputLoader(ImmutableList.of( (Collection<Statement>) ImmutableList.<Statement>of(), ImmutableList.of( createHttpStatement("s1", "p1", "o1", "g1"), createHttpStatement("s1", "p1", "o1", "g2")), ImmutableList.of( createHttpStatement("s2", "p2", "o1", "g3"), createHttpStatement("s2", "p2", "o2", "g3")) )); TestRDFWriter rdfWriter = new TestRDFWriter(); executor.fuse(new TestConflictResolver(), inputLoader, rdfWriter); List<ResolvedStatement> resolvedStatements = rdfWriter.getCollectedResolvedStatements(); assertThat(resolvedStatements.get(0).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s1", "p1", "o1", "g1"))); assertThat(resolvedStatements.get(1).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s1", "p1", "o1", "g2"))); assertThat(resolvedStatements.get(2).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s2", "p2", "o1", "g3"))); assertThat(resolvedStatements.get(3).getStatement(), contextAwareStatementIsEqual(createHttpStatement("s2", "p2", "o2", "g3"))); }
LDFusionToolUtils { public static <E extends Exception> void closeQuietly(Closeable<E> resource) { if (resource != null) { try { resource.close(); } catch (Exception ignore) { } } } private LDFusionToolUtils(); static String humanReadableSize(long byteCount); static String formatTime(long timeInMs); static File ensureParentsExists(File file); static String getVirtuosoConnectionString(String host, String port); static RDFFormat getSesameSerializationFormat(String serializationFormat, String fileName); static File createTempFile(File directory, String filePrefix); static void closeQuietly(Closeable<E> resource); static Set<URI> getResourceDescriptionProperties(ConfigConflictResolution config); static String buildPrefixDecl(Map<String, String> prefixes); static final int KB_BYTES; static final long MB_BYTES; static final long GB_BYTES; }
@Test public void closeQuietlyClosesResourceAndSwallowsException() throws Exception { Closeable<Exception> closeable = mock(Closeable.class); Mockito.doThrow(new Exception("test exception")).when(closeable).close(); LDFusionToolUtils.closeQuietly(closeable); Mockito.verify(closeable).close(); } @Test public void closeQuietlyDoesNotThrowForNullResource() throws Exception { LDFusionToolUtils.closeQuietly(null); }
StatementSizeEstimator { public static long estimatedSizeOf(Statement statement) { Value object = statement.getObject(); Resource context = statement.getContext(); long result = STATEMENT_OVERHEAD + 2 * URI_BNODE_OVERHEAD + OBJ_REF + StringSizeEstimator.estimatedSizeOf(statement.getSubject().stringValue()) + StringSizeEstimator.estimatedSizeOf(statement.getPredicate().stringValue()); if (object instanceof Literal) { Literal literal = (Literal) object; result += LITERAL_OVERHEAD + StringSizeEstimator.estimatedSizeOf(literal.stringValue()); if (literal.getLanguage() != null) { result += StringSizeEstimator.estimatedSizeOf(literal.getLanguage()); } if (literal.getDatatype() != null) { result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(literal.getDatatype().stringValue()); } } else { result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(object.stringValue()); } if (context != null) { result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(context.stringValue()); } return result; } static long estimatedSizeOf(Statement statement); }
@Test public void estimatedSizeOfWithLiteral() throws Exception { Statement statement = VALUE_FACTORY.createStatement( VALUE_FACTORY.createBNode("http: VALUE_FACTORY.createURI("http: VALUE_FACTORY.createLiteral("abc", VALUE_FACTORY.createURI("http: VALUE_FACTORY.createURI("http: long size = StatementSizeEstimator.estimatedSizeOf(statement); long stringsSize = 4 * StringSizeEstimator.estimatedSizeOf("http: long minOverhead = 6 * 8 + 12 * 4 + 4 * 8; long maxOverhead = 6 * 16 + 12 * 8 + 4 * 8; assertTrue(size <= maxOverhead + stringsSize); assertTrue(size >= minOverhead + stringsSize); } @Test public void estimatedSizeOfWithoutLiteral() throws Exception { Statement statement = VALUE_FACTORY.createStatement( VALUE_FACTORY.createBNode("http: VALUE_FACTORY.createURI("http: VALUE_FACTORY.createURI("http: VALUE_FACTORY.createURI("http: long size = StatementSizeEstimator.estimatedSizeOf(statement); long stringsSize = 4 * StringSizeEstimator.estimatedSizeOf("http: long minOverhead = 5 * 8 + 9 * 4 + 4 * 8; long maxOverhead = 5 * 16 + 9 * 8 + 4 * 8; assertTrue(size <= maxOverhead + stringsSize); assertTrue(size >= minOverhead + stringsSize); }
SplitFileNameGenerator { public File nextFile() { String suffix = Integer.toString(fileCount.incrementAndGet()); return addFileNameSuffix(baseFileName, suffix); } SplitFileNameGenerator(File baseFileName); File nextFile(); static final String SUFFIX_SEPARATOR; }
@Test public void generatesNamesWhenFileWithExtensionGiven() throws Exception { File file = new File(directory, "abc.txt"); String pathPrefix = directory.getAbsolutePath() + File.separatorChar; SplitFileNameGenerator generator = new SplitFileNameGenerator(file); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-1.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-2.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-3.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-4.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-5.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-6.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-7.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-8.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-9.txt")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-10.txt")); } @Test public void generatesNamesWhenFileWithoutExtensionGiven() throws Exception { File file = new File(directory, "abc"); String pathPrefix = directory.getAbsolutePath() + File.separatorChar; SplitFileNameGenerator generator = new SplitFileNameGenerator(file); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-1")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-2")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-3")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-4")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-5")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-6")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-7")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-8")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-9")); assertThat(generator.nextFile().getAbsolutePath(), equalTo(pathPrefix + "abc-10")); }
NTuplesFileMerger { public void merge(Reader leftReader, Reader rightReader, Writer outputWriter) throws IOException, NTupleMergeTransformException { NTuplesParser leftParser = new NTuplesParser(leftReader, parserConfig); NTuplesParser rightParser = new NTuplesParser(rightReader, parserConfig); NTuplesWriter output = new NTuplesWriter(outputWriter); List<List<Value>> rightBuffer = new ArrayList<List<Value>>(); try { while (leftParser.hasNext() && rightParser.hasNext()) { boolean wasEqual = NTuplesParserUtils.skipLessThan(leftParser, rightParser.peek().get(0), NTuplesParserUtils.VALUE_COMPARATOR); if (!wasEqual && leftParser.hasNext()) { wasEqual = NTuplesParserUtils.skipLessThan(rightParser, leftParser.peek().get(0), NTuplesParserUtils.VALUE_COMPARATOR); } if (wasEqual) { rightBuffer.clear(); readToBuffer(rightParser, rightBuffer); mergeWithBuffer(leftParser.next(), rightBuffer, output); while (leftParser.hasNext() && !rightBuffer.isEmpty() && compare(leftParser.peek(), rightBuffer.get(0)) == 0) { mergeWithBuffer(leftParser.next(), rightBuffer, output); } } } } finally { output.close(); leftParser.close(); rightParser.close(); } } NTuplesFileMerger(NTupleMergeTransform transform, ParserConfig parserConfig); void merge(Reader leftReader, Reader rightReader, Writer outputWriter); }
@Test public void mergesMatchingRecords() throws Exception { String leftInputStr = "<http: "<http: "<http: "<http: "<http: "<http: "<http: String rightInputStr = "<http: "<http: "<http: "<http: "<http: "<http: "<http: ByteArrayOutputStream output = new ByteArrayOutputStream(); InputStream leftInput = new ByteArrayInputStream(leftInputStr.getBytes()); InputStream rightInput = new ByteArrayInputStream(rightInputStr.getBytes()); NTuplesFileMerger merger = new NTuplesFileMerger(transform, new ParserConfig()); merger.merge(new InputStreamReader(leftInput), new InputStreamReader(rightInput), new OutputStreamWriter(output)); String expectedOutput = "<http: "<http: "<http: "<http: "<http: "<http: "<http: "<http: "<http: NTuplesParser outputParser = new NTuplesParser(new InputStreamReader(new ByteArrayInputStream(output.toByteArray())), new ParserConfig()); NTuplesParser expectedOutputParser = new NTuplesParser(new InputStreamReader(new ByteArrayInputStream(expectedOutput.getBytes())), new ParserConfig()); while (outputParser.hasNext() || expectedOutputParser.hasNext()) { assertThat(outputParser.hasNext(), is(expectedOutputParser.hasNext())); assertThat(outputParser.next(), is(expectedOutputParser.next())); } }
NTuplesParser extends ThrowingAbstractIterator<List<Value>, IOException> implements Closeable<IOException> { @Override public void close() throws IOException { if (internalParser != null) { internalParser.close(); } } NTuplesParser(Reader inputReader, ParserConfig parserConfig); @Override void close(); }
@Test public void parsesCorrectlyAllValueTypes() throws Exception { String inputString = "<http: "<http: "<http: ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes()); ParserConfig parserConfig = new ParserConfig(); parserConfig.set(BasicParserSettings.PRESERVE_BNODE_IDS, true); NTuplesParser parser = new NTuplesParser(new InputStreamReader(inputStream), parserConfig); List<List<Value>> result = new ArrayList<>(); try { while (parser.hasNext()) { result.add(parser.next()); } } finally { parser.close(); } assertThat(result.get(0), is(Arrays.asList( VF.createURI("http: VF.createBNode("bnode1"), VF.createLiteral("literal"), VF.createLiteral(123)))); assertThat(result.get(1), is(Arrays.asList( (Value) VF.createURI("http: assertThat(result.get(2), is(Arrays.asList( (Value) VF.createURI("http: VF.createURI("http: } @Test public void skipsCommentsAndNewlines() throws Exception { String inputString = "<http: + "# comment\n" + "<http: + "\n\n\n" + "<http: ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes()); ParserConfig parserConfig = new ParserConfig(); parserConfig.set(BasicParserSettings.PRESERVE_BNODE_IDS, true); NTuplesParser parser = new NTuplesParser(new InputStreamReader(inputStream), parserConfig); List<List<Value>> result = new ArrayList<>(); try { while (parser.hasNext()) { result.add(parser.next()); } } finally { parser.close(); } assertThat(result.get(0), is(Arrays.asList((Value) VF.createURI("http: assertThat(result.get(1), is(Arrays.asList((Value) VF.createURI("http: assertThat(result.get(2), is(Arrays.asList((Value) VF.createURI("http: } @Test(expected = IOException.class) public void throwsExceptionOnParseError() throws Exception { String inputString = "<http: ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes()); NTuplesParser parser = new NTuplesParser(new InputStreamReader(inputStream), new ParserConfig()); try { while (parser.hasNext()) { parser.next(); } } finally { parser.close(); } } @Test public void skipsErrorWhenFailOnNTriplesInvalidLinesSettingIsNonFatal() throws Exception { String inputString = "<http: ByteArrayInputStream inputStream = new ByteArrayInputStream(inputString.getBytes()); ParserConfig parserConfig = new ParserConfig(); parserConfig.addNonFatalError(NTriplesParserSettings.FAIL_ON_NTRIPLES_INVALID_LINES); NTuplesParser parser = new NTuplesParser(new InputStreamReader(inputStream), parserConfig); List<List<Value>> tuples = new ArrayList<>(); try { while (parser.hasNext()) { tuples.add(parser.next()); } } finally { parser.close(); } assertThat(tuples, contains((List<Value>) ImmutableList.of((Value) LDFusionToolTestUtils.createHttpUri("uri2"), LDFusionToolTestUtils.createHttpUri("uri3")))); }
NTuplesParserUtils { public static Resource parseValidResource(String str) throws RDFParseException { int length = str.length(); if (length < 3) { throw new RDFParseException("String '" + str + "' is not a valid URI nor blank node"); } char firstChar = str.charAt(0); if (firstChar == '<') { int endIndex = str.indexOf('>', 1); if (endIndex < 0) { throw new RDFParseException("Expected '>' but none found in '" + str + "'"); } String uri = str.substring(1, endIndex); return VF.createURI(uri); } else if (firstChar == '_' && str.charAt(1) == ':') { int endIndex = 2; while (endIndex < length && str.charAt(endIndex) != ' ' && str.charAt(endIndex) != '\t') { endIndex++; } while (str.charAt(endIndex - 1) == '.') { endIndex--; } String nodeId = str.substring(2, endIndex); return VF.createBNode(nodeId); } else { throw new RDFParseException(String.format("Expected '>' or '_:' but found '%s' in '%s'", str.charAt(0), str)); } } static boolean hasMatchingRecord(NTuplesParser parser, Value comparedFirstValue); static boolean skipLessThan(NTuplesParser parser, Value comparedFirstValue, Comparator<Value> valueComparator); static Resource parseValidResource(String str); static final ValueComparator VALUE_COMPARATOR; }
@Test public void parseValidResourceParsesUri() throws Exception { assertThat(NTuplesParserUtils.parseValidResource("<http: assertThat(NTuplesParserUtils.parseValidResource("<http: assertThat(NTuplesParserUtils.parseValidResource("<http: } @Test public void parseValidResourceParsesBlankNode() throws Exception { assertThat(NTuplesParserUtils.parseValidResource("_:abc"), is((Resource) VF.createBNode("abc"))); assertThat(NTuplesParserUtils.parseValidResource("_:a_b-c "), is((Resource) VF.createBNode("a_b-c"))); assertThat(NTuplesParserUtils.parseValidResource("_:abc.."), is((Resource) VF.createBNode("abc"))); } @Test(expected = RDFParseException.class) public void parseValidResourceThrowsWhenUriIsEmpty() throws Exception { NTuplesParserUtils.parseValidResource("<>"); } @Test(expected = RDFParseException.class) public void parseValidResourceThrowsWhenBlankNodeIsEmpty() throws Exception { NTuplesParserUtils.parseValidResource("_:"); } @Test(expected = RDFParseException.class) public void parseValidResourceThrowsWhenNotAResource() throws Exception { NTuplesParserUtils.parseValidResource("\"a\""); }
RdfFileLoader { public void read(RDFHandler rdfHandler) throws LDFusionToolException, RDFHandlerException { String label = dataSourceConfig.getName() != null ? dataSourceConfig.getName() : dataSourceConfig.getType().toString(); String displayPath = paramReader.getStringValue(ConfigParameters.DATA_SOURCE_FILE_PATH, ""); try { loadFile(label, rdfHandler); } catch (IOException e) { throw new LDFusionToolApplicationException(LDFusionToolErrorCodes.RDF_FILE_LOADER_READ, "I/O Error while reading input file " + displayPath, e); } catch (RDFParseException e) { throw new LDFusionToolApplicationException(LDFusionToolErrorCodes.RDF_FILE_LOADER_PARSE, "Error parsing input file " + displayPath, e); } } RdfFileLoader(SourceConfig sourceConfig, ParserConfig parserConfig); void read(RDFHandler rdfHandler); }
@Test public void loadsAllStatementsWhenTrigFileGiven() throws Exception { DataSourceConfig dataSource = createFileDataSource(testInput1, EnumSerializationFormat.TRIG); List<Statement> result = new ArrayList<Statement>(); RdfFileLoader loader = new RdfFileLoader(dataSource, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); loader.read(new StatementCollector(result)); assertThat(result.size(), equalTo(testInput1.size())); for (int i = 0; i < testInput1.size(); i++) { assertThat(result.get(i), contextAwareStatementIsEqual(testInput1.get(i))); } } @Test public void loadsAllStatementsWhenRdfXmlFileGiven() throws Exception { DataSourceConfig dataSource = createFileDataSource(testInput1, EnumSerializationFormat.RDF_XML); List<Statement> result = new ArrayList<Statement>(); RdfFileLoader loader = new RdfFileLoader(dataSource, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); loader.read(new StatementCollector(result)); assertThat(result.size(), equalTo(testInput1.size())); for (int i = 0; i < testInput1.size(); i++) { assertThat(result.get(i), equalTo(testInput1.get(i))); } } @Test public void returnsEmptyResultWhenInputFileEmpty() throws Exception { Collection<Statement> statements = ImmutableList.of(); DataSourceConfig dataSource = createFileDataSource(statements, EnumSerializationFormat.RDF_XML); RdfFileLoader loader = new RdfFileLoader(dataSource, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); List<Statement> result = new ArrayList<Statement>(0); loader.read(new StatementCollector(result)); assertThat(result.size(), equalTo(0)); } @Test public void callsStartRDFAndEndRDFOnGivenHandler() throws Exception { RDFHandler rdfHandler = Mockito.mock(RDFHandler.class); Collection<Statement> statements = ImmutableList.of( createHttpStatement("s1", "p", "o", "g1") ); DataSourceConfig dataSource = createFileDataSource(statements, EnumSerializationFormat.RDF_XML); RdfFileLoader loader = new RdfFileLoader(dataSource, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); loader.read((rdfHandler)); Mockito.verify(rdfHandler).startRDF(); Mockito.verify(rdfHandler).endRDF(); } @Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenDataSourceHasNotTypeFile() throws Exception { DataSourceConfig dataSourceConfig = new DataSourceConfigImpl(EnumDataSourceType.SPARQL, ""); RdfFileLoader loader = new RdfFileLoader(dataSourceConfig, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); loader.read(new StatementCollector()); } @Test(expected = RDFHandlerException.class) public void throwsRDFHandlerExceptionWhenHandlerFails() throws Exception { RDFHandler rdfHandler = Mockito.mock(RDFHandler.class); doThrow(new RDFHandlerException("")).when(rdfHandler).handleStatement(any(Statement.class)); Collection<Statement> statements = ImmutableList.of( createHttpStatement("s1", "p", "o", "g1") ); DataSourceConfig dataSource = createFileDataSource(statements, EnumSerializationFormat.RDF_XML); RdfFileLoader loader = new RdfFileLoader(dataSource, LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG); loader.read((rdfHandler)); }
LDFusionToolComponentFactory implements FusionComponentFactory { protected static Set<String> getPreferredURIs( Set<URI> settingsPreferredURIs, File canonicalURIsInputFile, Collection<String> preferredCanonicalURIs) throws IOException { Set<String> preferredURIs = new HashSet<>(settingsPreferredURIs.size()); for (URI uri : settingsPreferredURIs) { preferredURIs.add(uri.stringValue()); } if (canonicalURIsInputFile != null) { new CanonicalUriFileHelper().readCanonicalUris(canonicalURIsInputFile, preferredURIs); } preferredURIs.addAll(preferredCanonicalURIs); return preferredURIs; } LDFusionToolComponentFactory(Config config); @Override LDFusionToolExecutor getExecutor(UriMappingIterable uriMapping); @Override InputLoader getInputLoader(); @Override Model getMetadata(); @Override UriMappingIterable getUriMapping(); @Override CloseableRDFWriter getRDFWriter(); @Override ResourceDescriptionConflictResolver getConflictResolver(Model metadata, UriMappingIterable uriMapping); @Override UriMappingWriter getCanonicalUriWriter(UriMappingIterable uriMapping); @Override UriMappingWriter getSameAsLinksWriter(); ProfilingTimeCounter<EnumFusionCounters> getExecutorTimeProfiler(); MemoryProfiler getExecutorMemoryProfiler(); }
@Test public void getsPreferredUris() throws Exception { Set<URI> settingsURIs = ImmutableSet.of(LDFusionToolTestUtils.createHttpUri("s1"), LDFusionToolTestUtils.createHttpUri("s2")); File canonicalUriFile = temporaryFolder.newFile(); Files.write(canonicalUriFile.toPath(), ImmutableList.of("http: Set<String> preferredURIs = ImmutableSet.of(LDFusionToolTestUtils.createHttpUri("p1").stringValue(), LDFusionToolTestUtils.createHttpUri("p2").stringValue()); Set<String> actualUris = LDFusionToolComponentFactory.getPreferredURIs(settingsURIs, canonicalUriFile, preferredURIs); Set<String> expectedUris = ImmutableSet.of( LDFusionToolTestUtils.createHttpUri("s1").stringValue(), LDFusionToolTestUtils.createHttpUri("s2").stringValue(), "http: "http: LDFusionToolTestUtils.createHttpUri("p1").stringValue(), LDFusionToolTestUtils.createHttpUri("p2").stringValue()); assertThat(actualUris, is(expectedUris)); } @Test public void getsPreferredUrisWithoutFile() throws Exception { Set<URI> settingsURIs = ImmutableSet.of(LDFusionToolTestUtils.createHttpUri("s1"), LDFusionToolTestUtils.createHttpUri("s2")); Set<String> preferredURIs = ImmutableSet.of(LDFusionToolTestUtils.createHttpUri("p1").stringValue(), LDFusionToolTestUtils.createHttpUri("p2").stringValue()); Set<String> actualUris = LDFusionToolComponentFactory.getPreferredURIs(settingsURIs, null, preferredURIs); Set<String> expectedUris = ImmutableSet.of( LDFusionToolTestUtils.createHttpUri("s1").stringValue(), LDFusionToolTestUtils.createHttpUri("s2").stringValue(), LDFusionToolTestUtils.createHttpUri("p1").stringValue(), LDFusionToolTestUtils.createHttpUri("p2").stringValue()); assertThat(actualUris, is(expectedUris)); }
ConfigReader { public static Config parseConfigXml(File configFile) throws InvalidInputException { ConfigReader instance = new ConfigReader(); return instance.parseConfigXmlImpl(configFile); } private ConfigReader(); static Config parseConfigXml(File configFile); }
@Test public void parsesMinimalConfigFile() throws Exception { File configFile = getResourceFile("/config/sample-config-minimal.xml"); Config config = ConfigReader.parseConfigXml(configFile); assertThat(config.getCanonicalURIsInputFile(), nullValue()); assertThat(config.getCanonicalURIsOutputFile(), nullValue()); assertThat(config.getDefaultResolutionStrategy(), notNullValue()); assertThat(config.getDefaultResolutionStrategy().getResolutionFunctionName(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getAggregationErrorStrategy(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getCardinality(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getDependsOn(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getParams(), notNullValue()); assertThat(config.getDefaultResolutionStrategy().getParams().size(), equalTo(0)); assertThat(config.getEnableFileCache(), equalTo(false)); assertThat(config.getMaxOutputTriples(), nullValue()); assertThat(config.getMetadataSources(), equalTo(Collections.<ConstructSourceConfig>emptyList())); assertThat(config.getSameAsSources().size(), equalTo(0)); assertThat(config.getPrefixes(), equalTo(Collections.<String, String>emptyMap())); assertThat(config.getRequiredClassOfProcessedResources(), nullValue()); assertThat(config.getPropertyResolutionStrategies(), equalTo(Collections.<URI, ResolutionStrategy>emptyMap())); assertThat(config.isLocalCopyProcessing(), equalTo(true)); assertThat(config.getDataSources().size(), equalTo(1)); DataSourceConfig dataSourceConfig = config.getDataSources().get(0); assertThat(dataSourceConfig.getName(), nullValue()); assertThat(dataSourceConfig.getType(), equalTo(EnumDataSourceType.VIRTUOSO)); assertThat(dataSourceConfig.getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_HOST), equalTo("localhost")); assertThat(dataSourceConfig.getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_PORT), equalTo("1111")); assertThat(dataSourceConfig.getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_USERNAME), equalTo("dba")); assertThat(dataSourceConfig.getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_PASSWORD), equalTo("dba2")); assertThat(dataSourceConfig.getNamedGraphRestriction(), notNullValue()); assertThat(dataSourceConfig.getNamedGraphRestriction().getPattern(), equalTo("")); assertThat(config.getOutputs().size(), equalTo(1)); Output output = config.getOutputs().get(0); assertThat(output.getType(), equalTo(EnumOutputType.FILE)); assertThat(output.getDataContext(), nullValue()); assertThat(output.getMetadataContext(), nullValue()); assertThat(output.getName(), nullValue()); assertThat(output.getParams().get(ConfigParameters.DATA_SOURCE_FILE_PATH), equalTo("out.n3")); assertThat(output.getParams().get(ConfigParameters.DATA_SOURCE_FILE_FORMAT), equalTo("ntriples")); assertThat(config.getMaxDateDifference(), equalTo(LDFTConfigConstants.MAX_DATE_DIFFERENCE)); assertThat(config.getOutputMappedSubjectsOnly(), equalTo(false)); assertThat(config.getPreferredCanonicalURIs(), equalTo(LDFTConfigConstants.DEFAULT_PREFERRED_CANONICAL_URIS)); assertThat(config.getTempDirectory(), equalTo(LDFTConfigConstants.DEFAULT_TEMP_DIRECTORY)); assertThat(config.getResultDataURIPrefix(), notNullValue()); assertThat(config.getPublisherScoreWeight(), equalTo(LDFTConfigConstants.PUBLISHER_SCORE_WEIGHT)); assertThat(config.getAgreeCoefficient(), equalTo(LDFTConfigConstants.AGREE_COEFFICIENT)); assertThat(config.getQueryTimeout(), equalTo(LDFTConfigConstants.DEFAULT_QUERY_TIMEOUT)); assertThat(config.getScoreIfUnknown(), equalTo(LDFTConfigConstants.SCORE_IF_UNKNOWN)); assertThat(config.isProfilingOn(), equalTo(false)); assertThat(config.getMaxFreeMemoryUsage(), equalTo(LDFTConfigConstants.MAX_FREE_MEMORY_USAGE)); assertThat(config.getMemoryLimit(), equalTo(null)); assertThat(config.getParserConfig(), equalTo(LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); assertThat(config.getSameAsLinkTypes(), is(LDFTConfigConstants.SAME_AS_LINK_TYPES)); } @Test public void parsesFullConfigFile() throws Exception { File configFile = getResourceFile("/config/sample-config-full.xml"); Config config = ConfigReader.parseConfigXml(configFile); Map<String, String> expectedPrefixes = ImmutableMap.<String, String>builder() .put("rdf", "http: .put("rdfs", "http: .put("xsd", "http: .put("owl", "http: .put("odcs", "http: .put("fb", "http: .put("pc", "http: .build(); assertThat(config.getPrefixes(), equalTo(expectedPrefixes)); assertThat(config.getDataSources().size(), equalTo(3)); assertThat(config.getDataSources().get(0).getName(), equalTo("virtuoso_local")); assertThat(config.getDataSources().get(0).getType(), equalTo(EnumDataSourceType.VIRTUOSO)); assertThat(config.getDataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_HOST), equalTo("localhost")); assertThat(config.getDataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_PORT), equalTo("1111")); assertThat(config.getDataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_USERNAME), equalTo("dba")); assertThat(config.getDataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_VIRTUOSO_PASSWORD), equalTo("dba")); assertThat(config.getDataSources().get(0).getNamedGraphRestriction().getPattern(), equalTo( "{ SELECT ?g WHERE {?g odcs:metadataGraph ?m} }\n" + " UNION { SELECT ?g WHERE {?a odcs:attachedGraph ?g} }" )); assertThat(config.getDataSources().get(0).getNamedGraphRestriction().getVar(), equalTo("g")); assertThat(config.getDataSources().get(1).getName(), nullValue()); assertThat(config.getDataSources().get(1).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getDataSources().get(1).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_ENDPOINT), equalTo("http: assertThat(config.getDataSources().get(1).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_MIN_QUERY_INTERVAL), equalTo("1000")); assertThat(config.getDataSources().get(1).getNamedGraphRestriction().getPattern(), equalTo("")); assertThat(config.getDataSources().get(2).getType(), equalTo(EnumDataSourceType.FILE)); assertThat(config.getDataSources().get(2).getName(), nullValue()); assertThat(config.getDataSources().get(2).getParams().get(ConfigParameters.DATA_SOURCE_FILE_PATH), equalTo("data.rdf")); assertThat(config.getDataSources().get(2).getParams().get(ConfigParameters.DATA_SOURCE_FILE_BASE_URI), equalTo("http: assertThat(config.getDataSources().get(2).getParams().get(ConfigParameters.DATA_SOURCE_FILE_FORMAT), equalTo("ntriples")); assertThat(config.getDataSources().get(2).getNamedGraphRestriction().getPattern(), equalTo("")); assertThat(config.getMetadataSources().size(), equalTo(1)); assertThat(config.getMetadataSources().get(0).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getMetadataSources().get(0).getName(), equalTo("metadata-local")); assertThat(config.getMetadataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_ENDPOINT), equalTo("http: assertThat(config.getMetadataSources().get(0).getConstructQuery().trim(), equalTo("CONSTRUCT {?g odcs:score ?s } WHERE { ?g odcs:score ?s }")); assertThat(config.getSameAsSources().size(), equalTo(1)); assertThat(config.getSameAsSources().get(0).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getSameAsSources().get(0).getName(), equalTo("sameAs-local")); assertThat(config.getSameAsSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_ENDPOINT), equalTo("http: assertThat(config.getSameAsSources().get(0).getConstructQuery().trim(), equalTo("CONSTRUCT {?s owl:sameAs ?o} WHERE { ?s owl:sameAs ?o }")); assertThat(config.getCanonicalURIsInputFile(), equalTo(new File("output/canonicalUris.txt"))); assertThat(config.getCanonicalURIsOutputFile(), equalTo(new File("output/canonicalUris2.txt"))); assertThat(config.getMaxOutputTriples(), equalTo(999l)); assertThat(config.getEnableFileCache(), equalTo(true)); assertThat(config.isLocalCopyProcessing(), equalTo(true)); assertThat(config.getRequiredClassOfProcessedResources(), equalTo((URI) new URIImpl("http: assertThat(config.getDefaultResolutionStrategy(), notNullValue()); assertThat(config.getDefaultResolutionStrategy().getResolutionFunctionName(), equalTo("ALL")); assertThat(config.getDefaultResolutionStrategy().getAggregationErrorStrategy(), equalTo(EnumAggregationErrorStrategy.RETURN_ALL)); assertThat(config.getDefaultResolutionStrategy().getCardinality(), equalTo(EnumCardinality.MANYVALUED)); assertThat(config.getPropertyResolutionStrategies().size(), equalTo(3)); assertThat(config.getPropertyResolutionStrategies().get(RDFS.LABEL).getResolutionFunctionName(), equalTo("BEST")); assertThat(config.getPropertyResolutionStrategies().get(RDFS.LABEL).getDependsOn(), nullValue()); assertThat(config.getPropertyResolutionStrategies().get(RDFS.LABEL).getParams(), equalTo((Map<String, String>) ImmutableMap.of("name", "value"))); assertThat(config.getPropertyResolutionStrategies().get(FB_LONGITUDE).getResolutionFunctionName(), equalTo("AVG")); assertThat(config.getPropertyResolutionStrategies().get(FB_LONGITUDE).getDependsOn(), equalTo(FB_LATITUDE)); assertThat(config.getPropertyResolutionStrategies().get(FB_LATITUDE).getResolutionFunctionName(), equalTo("AVG")); assertThat(config.getPropertyResolutionStrategies().get(FB_LATITUDE).getParams(), equalTo((Map<String, String>) ImmutableMap.<String, String>of())); assertThat(config.getPropertyResolutionStrategies().get(FB_LATITUDE).getDependsOn(), equalTo(FB_LATITUDE)); assertThat(config.getOutputs().size(), equalTo(3)); assertThat(config.getOutputs().get(0).getName(), equalTo("n3-output")); assertThat(config.getOutputs().get(0).getType(), equalTo(EnumOutputType.FILE)); assertThat(config.getOutputs().get(0).getMetadataContext(), equalTo((URI) new URIImpl("http: assertThat(config.getOutputs().get(0).getDataContext(), equalTo((URI) new URIImpl("http: assertThat(config.getOutputs().get(0).getParams().size(), equalTo(6)); assertThat(config.getOutputs().get(1).getName(), equalTo("virtuoso-output")); assertThat(config.getOutputs().get(1).getType(), equalTo(EnumOutputType.VIRTUOSO)); assertThat(config.getOutputs().get(1).getMetadataContext(), nullValue()); assertThat(config.getOutputs().get(1).getDataContext(), equalTo((URI) new URIImpl("http: assertThat(config.getOutputs().get(1).getParams().size(), equalTo(5)); assertThat(config.getOutputs().get(2).getName(), equalTo("sparql-output")); assertThat(config.getOutputs().get(2).getType(), equalTo(EnumOutputType.SPARQL)); assertThat(config.getOutputs().get(2).getMetadataContext(), nullValue()); assertThat(config.getOutputs().get(2).getDataContext(), equalTo((URI) new URIImpl("http: assertThat(config.getOutputs().get(2).getParams().size(), equalTo(4)); assertThat(config.getMaxDateDifference(), equalTo(LDFTConfigConstants.MAX_DATE_DIFFERENCE)); assertThat(config.getOutputMappedSubjectsOnly(), equalTo(false)); assertThat(config.getPreferredCanonicalURIs(), equalTo(LDFTConfigConstants.DEFAULT_PREFERRED_CANONICAL_URIS)); assertThat(config.getTempDirectory(), equalTo(LDFTConfigConstants.DEFAULT_TEMP_DIRECTORY)); assertThat(config.getResultDataURIPrefix(), notNullValue()); assertThat(config.getPublisherScoreWeight(), equalTo(LDFTConfigConstants.PUBLISHER_SCORE_WEIGHT)); assertThat(config.getAgreeCoefficient(), equalTo(LDFTConfigConstants.AGREE_COEFFICIENT)); assertThat(config.getQueryTimeout(), equalTo(LDFTConfigConstants.DEFAULT_QUERY_TIMEOUT)); assertThat(config.getScoreIfUnknown(), equalTo(LDFTConfigConstants.SCORE_IF_UNKNOWN)); assertThat(config.isProfilingOn(), equalTo(false)); assertThat(config.getMaxFreeMemoryUsage(), equalTo(LDFTConfigConstants.MAX_FREE_MEMORY_USAGE)); assertThat(config.getMemoryLimit(), equalTo(null)); assertThat(config.getParserConfig(), equalTo(LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG)); assertThat(config.getSameAsLinkTypes(), is(LDFTConfigConstants.SAME_AS_LINK_TYPES)); } @Test public void parsesFullConfigFile2() throws Exception { File configFile = getResourceFile("/config/sample-config-full2.xml"); Config config = ConfigReader.parseConfigXml(configFile); assertThat(config.getDataSources().size(), equalTo(2)); assertThat(config.getDataSources().get(0).getName(), nullValue()); assertThat(config.getDataSources().get(0).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getDataSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_RESULT_MAX_ROWS), equalTo("100000")); assertThat(config.getDataSources().get(1).getName(), nullValue()); assertThat(config.getDataSources().get(1).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getDataSources().get(1).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_RESULT_MAX_ROWS), equalTo("100000")); assertThat(config.getSameAsSources().size(), equalTo(1)); assertThat(config.getSameAsSources().get(0).getType(), equalTo(EnumDataSourceType.SPARQL)); assertThat(config.getSameAsSources().get(0).getName(), nullValue()); assertThat(config.getSameAsSources().get(0).getParams().get(ConfigParameters.DATA_SOURCE_SPARQL_ENDPOINT), equalTo("http: assertThat(config.getSameAsSources().get(0).getConstructQuery().trim(), equalTo("CONSTRUCT {?s owl:sameAs ?o} WHERE { ?s owl:sameAs ?o }")); assertThat(config.getRequiredClassOfProcessedResources(), nullValue()); assertThat(config.getDefaultResolutionStrategy(), notNullValue()); assertThat(config.getDefaultResolutionStrategy().getResolutionFunctionName(), equalTo("NONE")); assertThat(config.getDefaultResolutionStrategy().getAggregationErrorStrategy(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getCardinality(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getDependsOn(), nullValue()); assertThat(config.getDefaultResolutionStrategy().getParams(), equalTo((Map<String, String>) ImmutableMap.of("name", "value"))); assertThat(config.getOutputs().size(), equalTo(1)); assertThat(config.getOutputs().get(0).getName(), nullValue()); assertThat(config.getOutputs().get(0).getType(), equalTo(EnumOutputType.SPARQL)); assertThat(config.getOutputs().get(0).getMetadataContext(), nullValue()); assertThat(config.getOutputs().get(0).getDataContext(), nullValue()); assertThat(config.getOutputs().get(0).getParams().size(), equalTo(3)); } @Test(expected = InvalidInputException.class) public void throwsInvalidInputExceptionWhenInputFileInvalid() throws Exception { File configFile = getResourceFile("/config/sample-config-invalid.xml"); ConfigReader.parseConfigXml(configFile); }
ExternalSortingInputLoader implements InputLoader { @Override public void close() throws LDFusionToolException { LOG.debug("Deleting input loader temporary files"); if (dataFileIterator != null) { try { dataFileIterator.close(); dataFileIterator = null; } catch (IOException e) { } } if (mergedAttributeFileIterator != null) { try { mergedAttributeFileIterator.close(); mergedAttributeFileIterator = null; } catch (IOException e) { } } for (File temporaryFile : temporaryFiles) { try { if (temporaryFile.exists()) { temporaryFile.delete(); } } catch (Exception e) { LOG.error("Error deleting temporary file " + temporaryFile.getName(), e); } } temporaryFiles.clear(); } ExternalSortingInputLoader( Collection<AllTriplesLoader> dataSources, Set<URI> resourceDescriptionProperties, File cacheDirectory, ParserConfig parserConfig, long maxMemoryLimit); @Override void initialize(UriMappingIterable uriMapping); @Override boolean hasNext(); @Override ResourceDescription next(); @Override void updateWithResolvedStatements(Collection<ResolvedStatement> resolvedStatements); @Override void close(); static final boolean USE_GZIP; }
@Test public void iteratesOverAllStatementsWithoutAppliedUriMapping() throws Exception { SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput1, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void readsMultipleInputFiles() throws Exception { SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = new ExternalSortingInputLoader( createFileAllTriplesLoader(testInput1, testInput2), Collections.singleton(resourceDescriptionProperty), testDir.getRoot(), LDFTConfigConstants.DEFAULT_FILE_PARSER_CONFIG, Long.MAX_VALUE); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput1); expectedStatementsSet.addAll(testInput2); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void iteratesOverAllStatementsWithDependentResources() throws Exception { SortedSet<Statement> result = new TreeSet<>(SPOG_COMPARATOR); ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); try { collectResult(inputLoader, result); } finally { inputLoader.close(); } SortedSet<Statement> expectedStatementsSet = new TreeSet<>(SPOG_COMPARATOR); expectedStatementsSet.addAll(testInput3); assertThat(result.size(), equalTo(expectedStatementsSet.size())); Statement[] expectedStatements = expectedStatementsSet.toArray(new Statement[0]); Statement[] actualStatements = result.toArray(new Statement[0]); for (int i = 0; i < expectedStatements.length; i++) { assertThat(actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } @Test public void includesCorrectDependentResourcesInResourceDescriptions() throws Exception { Map<Resource, TreeSet<Statement>> result; ExternalSortingInputLoader inputLoader = createExternalSortingInputLoader(testInput3, false); try { result = collectResourceDescriptions(inputLoader); } finally { inputLoader.close(); } assertThat(result.size(), is(conflictClusters3.size())); for (Map.Entry<Resource, TreeSet<Statement>> entry : conflictClusters3.entrySet()) { Statement[] expectedStatements = entry.getValue().toArray(new Statement[0]); Statement[] actualStatements = result.get(entry.getKey()).toArray(new Statement[0]); String errorMessage = "Statements for resource " + entry.getKey() + " do not match"; assertThat(errorMessage, actualStatements.length, is(expectedStatements.length)); for (int i = 0; i < expectedStatements.length; i++) { assertThat(errorMessage, actualStatements[i], contextAwareStatementIsEqual(expectedStatements[i])); } } }
FederatedResourceDescriptionFilter implements ResourceDescriptionFilter { @Override public boolean accept(ResourceDescription resourceDescription) { for (ResourceDescriptionFilter filter : filters) { if (!filter.accept(resourceDescription)) { return false; } } return true; } protected FederatedResourceDescriptionFilter(ResourceDescriptionFilter... filters); static ResourceDescriptionFilter fromList(List<ResourceDescriptionFilter> inputFilters); @Override boolean accept(ResourceDescription resourceDescription); }
@Test public void acceptsAllForNoFilter() throws Exception { FederatedResourceDescriptionFilter filter = new FederatedResourceDescriptionFilter(); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(0))); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(1))); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(2))); } @Test public void filtersByFilterForOneFilter() throws Exception { ResourceDescriptionFilter innerFilter = mock(ResourceDescriptionFilter.class); when(innerFilter.accept(RESOURCE_DESCRIPTIONS.get(0))).thenReturn(true); when(innerFilter.accept(RESOURCE_DESCRIPTIONS.get(1))).thenReturn(false); when(innerFilter.accept(RESOURCE_DESCRIPTIONS.get(2))).thenReturn(true); FederatedResourceDescriptionFilter filter = new FederatedResourceDescriptionFilter(innerFilter); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(0))); assertFalse(filter.accept(RESOURCE_DESCRIPTIONS.get(1))); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(2))); } @Test public void filtersByAnyFilterForMultipleFilters() throws Exception { ResourceDescriptionFilter innerFilter1 = mock(ResourceDescriptionFilter.class); when(innerFilter1.accept(RESOURCE_DESCRIPTIONS.get(0))).thenReturn(true); when(innerFilter1.accept(RESOURCE_DESCRIPTIONS.get(1))).thenReturn(false); when(innerFilter1.accept(RESOURCE_DESCRIPTIONS.get(2))).thenReturn(true); when(innerFilter1.accept(RESOURCE_DESCRIPTIONS.get(3))).thenReturn(true); ResourceDescriptionFilter innerFilter2 = mock(ResourceDescriptionFilter.class); when(innerFilter2.accept(RESOURCE_DESCRIPTIONS.get(0))).thenReturn(true); when(innerFilter2.accept(RESOURCE_DESCRIPTIONS.get(1))).thenReturn(true); when(innerFilter2.accept(RESOURCE_DESCRIPTIONS.get(2))).thenReturn(true); when(innerFilter2.accept(RESOURCE_DESCRIPTIONS.get(3))).thenReturn(false); FederatedResourceDescriptionFilter filter = new FederatedResourceDescriptionFilter(innerFilter1, innerFilter2); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(0))); assertFalse(filter.accept(RESOURCE_DESCRIPTIONS.get(1))); assertTrue(filter.accept(RESOURCE_DESCRIPTIONS.get(2))); assertFalse(filter.accept(RESOURCE_DESCRIPTIONS.get(3))); }
CloseableRepositoryConnection implements AutoCloseable { @Override public void close() throws RepositoryException { connection.close(); } CloseableRepositoryConnection(RepositoryConnection connection); RepositoryConnection get(); @Override void close(); void closeQuietly(); }
@Test public void closesConnection() throws Exception { RepositoryConnection connection = mock(RepositoryConnection.class); CloseableRepositoryConnection closeableRepositoryConnection = new CloseableRepositoryConnection(connection); closeableRepositoryConnection.close(); verify(connection).close(); }
ClusterIterator implements Iterator<List<T>> { @Override public List<T> next() { int fromIndex = cursor; T first = nextElement(); while (hasNextElement()) { T next = peekNextElement(); if (comparator.compare(first, next) == 0) { nextElement(); } else { break; } } return new SubList(fromIndex, cursor); } @SuppressWarnings("unchecked") ClusterIterator(List<T> elements, Comparator<T> comparator); @Override boolean hasNext(); @Override List<T> next(); @Override void remove(); }
@Test public void iteratesOverCorrectClustersWithPartialMatch() throws Exception { List<Statement> elements = ImmutableList.of( LDFusionToolTestUtils.createHttpStatement("s3", "p", "o1"), LDFusionToolTestUtils.createHttpStatement("s1", "p", "o2"), LDFusionToolTestUtils.createHttpStatement("s2", "p", "o3"), LDFusionToolTestUtils.createHttpStatement("s1", "p", "o4"), LDFusionToolTestUtils.createHttpStatement("s2", "p", "o5"), LDFusionToolTestUtils.createHttpStatement("s1", "p", "o6")); Comparator<Statement> comparator = new Comparator<Statement>() { @Override public int compare(Statement o1, Statement o2) { return o1.getSubject().stringValue().compareTo(o2.getSubject().stringValue()); } }; ClusterIterator<Statement> clusterIterator = new ClusterIterator<Statement>(elements, comparator); Map<URI, List<Statement>> expectedClusters = new HashMap<>(); expectedClusters.put(LDFusionToolTestUtils.createHttpUri("s1"), ImmutableList.of( LDFusionToolTestUtils.createHttpStatement("s1", "p", "o2"), LDFusionToolTestUtils.createHttpStatement("s1", "p", "o4"), LDFusionToolTestUtils.createHttpStatement("s1", "p", "o6"))); expectedClusters.put(LDFusionToolTestUtils.createHttpUri("s2"), ImmutableList.of(LDFusionToolTestUtils.createHttpStatement("s2", "p", "o3"), LDFusionToolTestUtils.createHttpStatement("s2", "p", "o5"))); expectedClusters.put(LDFusionToolTestUtils.createHttpUri("s3"), ImmutableList.of(LDFusionToolTestUtils.createHttpStatement("s3", "p", "o1"))); for (int i = 0; i < 3; i++) { List<Statement> actualCluster = clusterIterator.next(); List<Statement> expectedCluster = expectedClusters.get(actualCluster.get(0).getSubject()); assertThat(actualCluster, containsInAnyOrder(expectedCluster.toArray())); } }
ClusterIterator implements Iterator<List<T>> { @Override public boolean hasNext() { return hasNextElement(); } @SuppressWarnings("unchecked") ClusterIterator(List<T> elements, Comparator<T> comparator); @Override boolean hasNext(); @Override List<T> next(); @Override void remove(); }
@Test public void iteratesOverEmptyCollection() throws Exception { List<String> elements = Collections.emptyList(); ClusterIterator<String> clusterIterator = new ClusterIterator<String>(elements, String.CASE_INSENSITIVE_ORDER); assertThat(clusterIterator.hasNext(), is(false)); }
ParamReader { public String getStringValue(String paramName) { return params.get(paramName); } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test public void returnsStringValueWhenStringParamPresent() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "value1"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1"); assertThat(result, equalTo("value1")); } @Test() public void returnsNullWhenNonRequiredStringParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1"); assertThat(result, nullValue()); } @Test public void returnsStringValueWhenStringParamPresentAndDefaultGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "value1"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1", "default"); assertThat(result, equalTo("value1")); } @Test public void returnsDefaultValueWhenStringParamNotPresentAndDefaultGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1", "default"); assertThat(result, equalTo("default")); }
ParamReader { public String getRequiredStringValue(String paramName) throws LDFusionToolException { return getRequiredValue(paramName); } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredStringParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredStringValue("key1"); } @Test(expected = LDFusionToolException.class) public void throwsWhenRequiredStringParamEmpty() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", ""); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredStringValue("key1"); }
ParamReader { public Integer getIntValue(String paramName) { String value = params.get(paramName); if (value == null) { return null; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { String message = getNumberFormatErrorMessage(paramName, value); LOG.error(message); return null; } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test public void returnsIntValueWhenValidIntParamPresent() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Integer result = paramReader.getIntValue("key1"); assertThat(result, equalTo(123)); } @Test() public void returnsNullWhenNonRequiredIntParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Integer result = paramReader.getIntValue("key1"); assertThat(result, nullValue()); } @Test public void returnsNullWhenNonRequiredIntParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Integer result = paramReader.getIntValue("key1"); assertThat(result, nullValue()); } @Test public void returnsIntValueWhenValidIntParamPresentAndDefaultValueGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Integer result = paramReader.getIntValue("key1", 1000); assertThat(result, equalTo(123)); } @Test public void returnsDefaultValueWhenMalformedIntParamAndDefaultValueGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "12s3"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Integer result = paramReader.getIntValue("key1", 1000); assertThat(result, equalTo(1000)); }
ParamReader { public Integer getRequiredIntValue(String paramName) throws LDFusionToolException { String value = getRequiredValue(paramName); try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new LDFusionToolException(getNumberFormatErrorMessage(paramName, value)); } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredIntParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredIntValue("key1"); } @Test(expected = LDFusionToolException.class) public void throwsWhenRequiredIntParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredIntValue("key1"); }
ParamReader { public Long getLongValue(String paramName) { String value = params.get(paramName); if (value == null) { return null; } try { return Long.parseLong(value); } catch (NumberFormatException e) { String message = getNumberFormatErrorMessage(paramName, value); LOG.error(message); return null; } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test public void returnsLongValueWhenValidLongParamPresent() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Long result = paramReader.getLongValue("key1"); assertThat(result, equalTo(123l)); } @Test() public void returnsNullWhenNonRequiredLongParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Long result = paramReader.getLongValue("key1"); assertThat(result, nullValue()); } @Test public void returnsNullWhenNonRequiredLongParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Long result = paramReader.getLongValue("key1"); assertThat(result, nullValue()); } @Test public void returnsLongValueWhenValidLongParamPresentAndDefaultValueGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Long result = paramReader.getLongValue("key1", 1000l); assertThat(result, equalTo(123l)); } @Test public void returnsDefaultValueWhenMalformedLongParamAndDefaultValueGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "12s3"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); Long result = paramReader.getLongValue("key1", 1000l); assertThat(result, equalTo(1000l)); }
ParamReader { public Long getRequiredLongValue(String paramName) throws LDFusionToolException { String value = getRequiredValue(paramName); try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new LDFusionToolException(getNumberFormatErrorMessage(paramName, value)); } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredLongParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredLongValue("key1"); } @Test(expected = LDFusionToolException.class) public void throwsWhenRequiredLongParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredLongValue("key1"); }
CloseableRepository implements AutoCloseable { @Override public void close() throws RepositoryException { repository.shutDown(); } CloseableRepository(Repository repository); Repository get(); @Override void close(); }
@Test public void shutsDownRepository() throws Exception { Repository repository = mock(Repository.class); CloseableRepository closeableRepository = new CloseableRepository(repository); closeableRepository.close(); verify(repository).shutDown(); }
DeepLinkAnnotationCompiler extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("[FlowR]: generating deep Link Handler..."); MethodSpec.Builder constructorBuilder = generateConstructor(); for (Element element : roundEnv.getElementsAnnotatedWith(DeepLink.class)) { String[] value = element.getAnnotation(DeepLink.class).value(); for (String url : value) { constructorBuilder.addStatement(deeplinkFormat, url, ClassName.get(element.asType())); } } for (Element element : roundEnv.getElementsAnnotatedWith(DeepLinkHandler.class)) { String packageName = processingEnv.getElementUtils().getPackageOf(element) .getQualifiedName().toString(); String className = element.getAnnotation(DeepLinkHandler.class).value(); if (className.isEmpty()) { className = element.getSimpleName().toString() + HANDLER_FILE_NAME_POST_FIX; } generateDeepLinkHandler(packageName, className, constructorBuilder); } return true; } @Override boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv); }
@Test public void process() throws Exception { assertAbout(javaSources()) .that(Arrays.asList(TEST_DEEP_LINK_FRAGMENT, TEST_DEEP_LINK_HANDLER)) .processedWith(new DeepLinkAnnotationCompiler()) .compilesWithoutError() .and() .generatesSources(TEST_DEEP_GENERATED_HANDLER); }
OwmClient { public WeatherStatusResponse currentWeatherAroundPoint (float lat, float lon, int cnt) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/station?lat=%f&lon=%f&cnt=%d&cluster=yes", Float.valueOf (lat), Float.valueOf (lon), Integer.valueOf (cnt)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherAroundPoint () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AROUND_POINT); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAroundPoint (55f, 37f, 10); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), 10); }
OwmClient { public WeatherForecastResponse forecastWeatherAtCity (int cityId) throws JSONException, IOException { String subUrl = String.format (Locale.ROOT, "forecast/city/%d?type=json&units=metric", cityId); JSONObject response = doQuery (subUrl); return new WeatherForecastResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testForecastAtCityId () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.FORECAST_WEATHER_AT_CITY_ID_LISBON); OwmClient owm = new OwmClient (mockHttpClient); WeatherForecastResponse forecastResponse = owm.forecastWeatherAtCity (524901); City lisbon = forecastResponse.getCity (); assertNotNull (lisbon); assertTrue ("PT".equalsIgnoreCase (lisbon.getCountryCode ())); assertTrue ("Lisbon".equalsIgnoreCase (lisbon.getName ())); OwmClientTest.assertForecastWeatherDataList (forecastResponse.getForecasts (), Integer.MAX_VALUE); } @Test public void testForecastAtCityName () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.FORECAST_WEATHER_AT_CITY_NAME_LISBON); OwmClient owm = new OwmClient (mockHttpClient); WeatherForecastResponse forecastResponse = owm.forecastWeatherAtCity ("Lisbon"); City lisbon = forecastResponse.getCity (); assertNotNull (lisbon); assertTrue ("PT".equalsIgnoreCase (lisbon.getCountryCode ())); assertTrue ("Lisbon".equalsIgnoreCase (lisbon.getName ())); OwmClientTest.assertForecastWeatherDataList (forecastResponse.getForecasts (), Integer.MAX_VALUE); }
OwmClient { public WeatherHistoryCityResponse historyWeatherAtCity (int cityId, HistoryType type) throws JSONException, IOException { if (type == HistoryType.UNKNOWN) throw new IllegalArgumentException("Can't do a historic request for unknown type of history."); String subUrl = String.format (Locale.ROOT, "history/city/%d?type=%s", cityId, type); JSONObject response = doQuery (subUrl); return new WeatherHistoryCityResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testHourHistoryWeatherAtCity () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_CITY_ID); OwmClient owm = new OwmClient (mockHttpClient); WeatherHistoryCityResponse history = owm.historyWeatherAtCity (2885679, HistoryType.HOUR); assertEquals (0.0186d, history.getCalcTime (), 0.0001d); assertEquals (0.0056d, history.getCalcTimeFetch (), 0.0001d); assertEquals (0.0131d, history.getCalcTimeFind (), 0.0001d); assertEquals (2885679, history.getCityId ()); assertTrue (history.hasHistory ()); }
OwmClient { public WeatherHistoryStationResponse historyWeatherAtStation (int stationId, HistoryType type) throws JSONException, IOException { if (type == HistoryType.UNKNOWN) throw new IllegalArgumentException("Can't do a historic request for unknown type of history."); String subUrl = String.format (Locale.ROOT, "history/station/%d?type=%s", stationId, type); JSONObject response = doQuery (subUrl); return new WeatherHistoryStationResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testTickHistoryWeatherAtStation () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_STATION_ID_BY_TICK); OwmClient owm = new OwmClient (mockHttpClient); WeatherHistoryStationResponse history = owm.historyWeatherAtStation (9040, HistoryType.TICK); assertEquals (1.5991d, history.getCalcTime (), 0.0001d); assertEquals (0.0456d, history.getCalcTimeTick (), 0.0001d); assertEquals (9040, history.getStationId ()); assertEquals (OwmClient.HistoryType.TICK, history.getType ()); assertTrue (history.hasHistory ()); } @Test public void testHourlyHistoryWeatherAtStation () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.HISTORY_WEATHER_AT_STATION_ID_BY_HOUR); OwmClient owm = new OwmClient (mockHttpClient); WeatherHistoryStationResponse historyResponse = owm.historyWeatherAtStation (9040, HistoryType.HOUR); assertNotNull (historyResponse); List<AbstractWeatherData> history = historyResponse.getHistory (); assertNotNull (history); assertTrue (history.size () == 14); AbstractWeatherData weather = history.get (0); assertNotNull (weather); assertEquals (289.26f, weather.getTemp (), 0.001f); assertEquals (1019f, weather.getPressure (), 0.01f); assertEquals (99f, weather.getHumidity (), 0.01f); assertEquals (0f, weather.getWindSpeed (), 0.01f); assertEquals (0f, weather.getWindGust (), 0.01f); assertEquals (Integer.MIN_VALUE, weather.getWindDeg ()); assertEquals (0, weather.getRain ()); assertEquals (Integer.MIN_VALUE, weather.getSnow ()); assertEquals (0, weather.getPrecipitation ()); }
OwmClient { public WeatherStatusResponse currentWeatherAtCity (float lat, float lon, int cnt) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&cnt=%d&cluster=yes", Float.valueOf (lat), Float.valueOf (lon), Integer.valueOf (cnt)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherAroundCity () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AROUND_CITY_COORD); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAtCity (55f, 37f, 10); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), 10); } @Test public void testCurrentWeatherAtCityId () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_ID_MOSKOW); OwmClient owm = new OwmClient (mockHttpClient); StatusWeatherData weatherData = owm.currentWeatherAtCity (524901); assertEquals ("Moscow", weatherData.getName ()); assertEquals (524901, weatherData.getId ()); OwmClientTest.assertWeatherData (weatherData); } @Test public void testCurrentWeatherAtCityName () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_NAME_LONDON); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAtCity ("london"); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); for (StatusWeatherData weather : currentWeather.getWeatherStatus ()) { assertTrue ("london".equalsIgnoreCase (weather.getName ())); } } @Test public void testCurrentWeatherAtCityNameWithCountryCode () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_CITY_NAME_LONDON_COUNTRY_CODE_UK); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAtCity ("london", "UK"); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); for (StatusWeatherData weather : currentWeather.getWeatherStatus ()) { assertTrue ("london".equalsIgnoreCase (weather.getName ())); } }
OwmClient { public WeatherStatusResponse currentWeatherInBoundingBox (float northLat, float westLon, float southLat, float eastLon) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/station?bbox=%f,%f,%f,%f&cluster=yes", Float.valueOf (northLat), Float.valueOf (westLon), Float.valueOf (southLat), Float.valueOf (eastLon)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherInBoundingBox () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_BBOX); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherInBoundingBox (12f, 32f, 15f, 37f); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); }
OwmClient { public WeatherStatusResponse currentWeatherAtCityBoundingBox (float northLat, float westLon, float southLat, float eastLon) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/city?bbox=%f,%f,%f,%f&cluster=yes", Float.valueOf (northLat), Float.valueOf (westLon), Float.valueOf (southLat), Float.valueOf (eastLon)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherAtCityBoundingBox () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CITY_BBOX); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAtCityBoundingBox (12f, 32f, 15f, 37f); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); }
OwmClient { public WeatherStatusResponse currentWeatherInCircle (float lat, float lon, float radius) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/station?lat=%f&lon=%f&radius=%f&cluster=yes", Float.valueOf (lat), Float.valueOf (lon), Float.valueOf (radius)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherInCircle () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CIRCLE); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherInCircle (55.5f, 37.5f, 40f); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); }
OwmClient { public WeatherStatusResponse currentWeatherAtCityCircle (float lat, float lon, float radius) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&radius=%f&cluster=yes", Float.valueOf (lat), Float.valueOf (lon), Float.valueOf (radius)); JSONObject response = doQuery (subUrl); return new WeatherStatusResponse (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherAtCityInCircle () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_IN_CIRCLE); OwmClient owm = new OwmClient (mockHttpClient); WeatherStatusResponse currentWeather = owm.currentWeatherAtCityCircle (55.5f, 37.5f, 40f); assertTrue (currentWeather.hasWeatherStatus ()); OwmClientTest.assertWeatherDataList (currentWeather.getWeatherStatus (), Integer.MAX_VALUE); }
OwmClient { public StatusWeatherData currentWeatherAtStation (int stationId) throws IOException, JSONException { String subUrl = String.format (Locale.ROOT, "weather/station/%d?type=json", Integer.valueOf (stationId)); JSONObject response = doQuery (subUrl); return new StatusWeatherData (response); } OwmClient(); OwmClient(HttpClient httpClient); void setAPPID(String appid); WeatherStatusResponse currentWeatherAroundPoint(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherAtCity(float lat, float lon, int cnt); WeatherStatusResponse currentWeatherInBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherAtCityBoundingBox(float northLat, float westLon, float southLat, float eastLon); WeatherStatusResponse currentWeatherInCircle(float lat, float lon, float radius); WeatherStatusResponse currentWeatherAtCityCircle(float lat, float lon, float radius); StatusWeatherData currentWeatherAtCity(int cityId); StatusWeatherData currentWeatherAtStation(int stationId); WeatherStatusResponse currentWeatherAtCity(String cityName); WeatherStatusResponse currentWeatherAtCity(String cityName, String countryCode); WeatherForecastResponse forecastWeatherAtCity(int cityId); WeatherForecastResponse forecastWeatherAtCity(String cityName); WeatherHistoryCityResponse historyWeatherAtCity(int cityId, HistoryType type); WeatherHistoryStationResponse historyWeatherAtStation(int stationId, HistoryType type); }
@Test public void testCurrentWeatherAtStationId () throws IOException, JSONException { HttpClient mockHttpClient = createHttpClientThatRespondsWith (TestData.CURRENT_WEATHER_AT_STATION_ID_9040); OwmClient owm = new OwmClient (mockHttpClient); StatusWeatherData weatherData = owm.currentWeatherAtStation (9040); assertEquals ("CT1AKV-10", weatherData.getName ()); assertEquals (9040, weatherData.getId ()); assertEquals (1360924205, weatherData.getDateTime ()); assertTrue (weatherData.hasMain ()); assertEquals ( 281.48f, weatherData.getMain ().getTemp (), 0.001f); assertEquals ( 99f, weatherData.getMain ().getHumidity (), 0.001f); assertEquals (1016f, weatherData.getMain ().getPressure (), 0.001f); assertTrue (weatherData.hasWind ()); assertEquals (0f, weatherData.getWind ().getSpeed (), 0.001f); assertEquals (0f, weatherData.getWind ().getGust (), 0.001f); assertEquals (0, weatherData.getWind ().getDeg ()); assertTrue (weatherData.hasRain ()); assertEquals (2, weatherData.getRainObj ().measurements ().size ()); assertEquals (0f, weatherData.getRainObj ().getMeasure (1), 0.001f); assertEquals (0f, weatherData.getRainObj ().getMeasure (24), 0.001f); assertEquals (0, weatherData.getRainObj ().getToday ()); assertTrue (weatherData.hasCoord ()); assertTrue (weatherData.getCoord ().hasLongitude ()); assertTrue (weatherData.getCoord ().hasLatitude ()); assertEquals (-8.7363f, weatherData.getCoord ().getLongitude (), 0.00001f); assertEquals (39.1862f, weatherData.getCoord ().getLatitude (), 0.00001f); assertTrue (weatherData.hasStation ()); assertEquals (7, weatherData.getStation ().getZoom ()); }
Form extends MultiValueMap<String, String> { public Form fromString(String s) { for (String param : s.split("&")) { String[] nv = param.split("=", 2); if (nv.length == 2) { try { add(URLDecoder.decode(nv[0], "UTF-8"), URLDecoder.decode(nv[1], "UTF-8")); } catch (UnsupportedEncodingException uee) { throw new IllegalStateException(uee); } } } return this; } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }
@Test public void fromString() { Form f = new Form().fromString("x=%3D&y=z"); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("z"); }
FieldMap implements FullMap<String, Object> { @Override public boolean containsKey(Object key) { return fields.containsKey(key); } FieldMap(); FieldMap(Object object); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override int size(); @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void clear(); }
@Test public void notContainsNonExistentField() { assertThat(map.containsKey("notField")).isFalse(); } @Test public void containsField() { assertThat(map.containsKey("stringField")).isTrue(); } @Test public void notContainsStaticField() { assertThat(map.containsKey("staticField")).isFalse(); } @Test public void notContainsPrimitiveField() { assertThat(map.containsKey("primitiveField")).isFalse(); } @Test public void notContainsPrivateField() { assertThat(map.containsKey("privateField")).isFalse(); }
FieldMap implements FullMap<String, Object> { @Override public Object get(Object key) { try { return fields.get(key).get(object); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); } catch (NullPointerException npe) { } return null; } FieldMap(); FieldMap(Object object); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override int size(); @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void clear(); }
@Test public void booleanType() { assertThat(map.get("booleanField")).isInstanceOf(Boolean.class); } @Test public void booleanFieldValue() { assertThat(map.get("booleanField")).isEqualTo(fields.booleanField); } @Test public void stringFieldValue() { assertThat(map.get("stringField")).isEqualTo(fields.stringField); }
URIUtil { public static URI create(String scheme, String rawUserInfo, String host, int port, String rawPath, String rawQuery, String rawFragment) throws URISyntaxException { StringBuilder sb = new StringBuilder(); if (scheme != null) { sb.append(scheme).append(':'); } if (host != null) { sb.append(" } if (rawUserInfo != null) { sb.append(rawUserInfo).append('@'); } if (host != null) { sb.append(host); if (port != -1) { sb.append(':').append(Integer.toString(port)); } } if (rawPath != null) { sb.append(rawPath); } if (rawQuery != null) { sb.append('?').append(rawQuery); } if (rawFragment != null) { sb.append("#").append(rawFragment); } return new URI(sb.toString()); } private URIUtil(); static URI create(String scheme, String rawUserInfo, String host, int port, String rawPath, String rawQuery, String rawFragment); static URI rebase(URI uri, URI base); }
@Test public void toURIandBack() throws URISyntaxException { URI u1 = URIUtil.create("a", "b", "c", 4, "/e%3D", "x=%3D", "g%3D"); URI u2 = URIUtil.create(u1.getScheme(), u1.getRawUserInfo(), u1.getHost(), u1.getPort(), u1.getRawPath(), u1.getRawQuery(), u1.getRawFragment()); assertThat(u1).isEqualTo(u2); } @Test public void rawParams() throws URISyntaxException { URI uri = URIUtil.create("http", "user", "example.com", 80, "/raw%3Dpath", "x=%3D", "frag%3Dment"); assertThat(uri.toString()).isEqualTo("http: }
URIUtil { public static URI rebase(URI uri, URI base) throws URISyntaxException { if (base == null) { return uri; } String scheme = base.getScheme(); String host = base.getHost(); int port = base.getPort(); if (scheme == null || host == null) { return uri; } return create(scheme, uri.getRawUserInfo(), host, port, uri.getRawPath(), uri.getRawQuery(), uri.getRawFragment()); } private URIUtil(); static URI create(String scheme, String rawUserInfo, String host, int port, String rawPath, String rawQuery, String rawFragment); static URI rebase(URI uri, URI base); }
@Test public void rebase() throws URISyntaxException { URI uri = new URI("https: URI base = new URI("http: URI rebased = URIUtil.rebase(uri, base); assertThat(rebased.toString()).isEqualTo("http: }
BranchingStreamWrapper extends BranchingInputStream { @Override public int read() throws IOException { byte[] b = new byte[1]; return (read(b, 0, 1) > 0 ? (b[0] & 0xff) : -1); } BranchingStreamWrapper(InputStream in, Factory<Buffer> bufferFactory); @Override BranchingStreamWrapper branch(); @Override boolean isClosed(); @Override BranchingStreamWrapper getParent(); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); @Override long skip(long n); @Override int available(); @Override void close(); @Override void closeBranches(); @Override void finalize(); }
@Test public void noBranch_byteAtATime() throws IOException { for (int n = 0; n < BUFSIZE; n++) { assertThat(trunk.read()).isEqualTo(bytes[n] & 0xff); } assertThat(trunk.read()).isEqualTo(-1); } @Test public void noBranch_allBytes() throws IOException { assertThat(trunk.read(buffers[0])).isEqualTo(BUFSIZE); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read(buffers[0])).isEqualTo(-1); } @Test public void noBranch_bytesLength() throws IOException { assertThat(trunk.read(buffers[0], 0, BUFSIZE)).isEqualTo(BUFSIZE); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read(buffers[0], 0, BUFSIZE)).isEqualTo(-1); } @Test public void noBranch_twoReads() throws IOException { int length1 = BUFSIZE / 2; int length2 = BUFSIZE - length1; assertThat(trunk.read(buffers[0], 0, length1)).isEqualTo(length1); assertThat(trunk.read(buffers[0], length1, length2)).isEqualTo(length2); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read()).isEqualTo(-1); }
Form extends MultiValueMap<String, String> { public Form fromRequestQuery(Request request) { String query = request.uri.getRawQuery(); if (query != null) { fromString(query); } return this; } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }
@Test public void fromRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form().fromRequestQuery(request); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("?"); assertThat(f.get("z").get(0)).isEqualTo("a"); }
AssignmentFilter extends GenericFilter { private void eval(Binding binding, Exchange exchange) { if (binding.condition == null || Boolean.TRUE.equals(binding.condition.eval(exchange))) { binding.target.set(exchange, binding.value != null ? binding.value.eval(exchange) : null); } } @Override void filter(Exchange exchange, Handler next); final List<Binding> onRequest; final List<Binding> onResponse; }
@Test public void onRequest() throws ExpressionException, HandlerException, IOException { AssignmentFilter filter = new AssignmentFilter(); AssignmentFilter.Binding binding = new AssignmentFilter.Binding(); binding.target = new Expression("${exchange.newAttr}"); binding.value = new Expression("${exchange.request.method}"); filter.onRequest.add(binding); Exchange exchange = new Exchange(); exchange.request = new Request(); exchange.request.method = "DELETE"; Chain chain = new Chain(); chain.filters.add(filter); StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 200; chain.handler = handler; assertThat(binding.target.eval(exchange)).isNull(); chain.handle(exchange); assertThat(exchange.get("newAttr")).isEqualTo("DELETE"); } @Test public void onResponse() throws ExpressionException, HandlerException, IOException { AssignmentFilter filter = new AssignmentFilter(); AssignmentFilter.Binding binding = new AssignmentFilter.Binding(); binding.target = new Expression("${exchange.newAttr}"); binding.value = new Expression("${exchange.response.status}"); filter.onResponse.add(binding); Exchange exchange = new Exchange(); Chain chain = new Chain(); chain.filters.add(filter); StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 200; chain.handler = handler; assertThat(binding.target.eval(exchange)).isNull(); chain.handle(exchange); assertThat(exchange.get("newAttr")).isEqualTo(200); }
StaticResponseHandler extends GenericHandler { @Override public void handle(Exchange exchange) throws HandlerException, IOException { LogTimer timer = logger.getTimer().start(); Response response = new Response(); response.status = this.status; response.reason = this.reason; if (response.reason == null) { response.reason = HttpUtil.getReason(response.status); } if (response.reason == null) { response.reason = "Uncertain"; } if (this.version != null) { response.version = this.version; } for (String key : this.headers.keySet()) { for (Expression expression : this.headers.get(key)) { String eval = expression.eval(exchange, String.class); if (eval != null) { response.headers.add(key, eval); } } } if (this.entity != null) { HttpUtil.toEntity(response, entity, null); } exchange.response = response; timer.stop(); } @Override void handle(Exchange exchange); public Integer status; public String reason; public String version; final MultiValueMap<String, Expression> headers; public String entity; }
@Test public void redirect() throws ExpressionException, HandlerException, IOException { StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 302; handler.reason = "Found"; handler.headers.add("Location", new Expression("http: Exchange exchange = new Exchange(); handler.handle(exchange); assertThat(exchange.response.status).isEqualTo(302); assertThat(exchange.response.reason).isEqualTo("Found"); assertThat(exchange.response.headers.getFirst("Location")).isEqualTo("http: }
Expression { public Object eval(Object scope) { try { return valueExpression.getValue(new XLContext(scope)); } catch (ELException ele) { return null; } } Expression(String expression); Object eval(Object scope); @SuppressWarnings("unchecked") T eval(Object scope, Class<T> type); void set(Object scope, Object value); }
@Test public void bool() throws ExpressionException { Expression expr = new Expression("${1==1}"); Object o = expr.eval(null); assertThat(o).isInstanceOf(Boolean.class); assertThat(o).isEqualTo(true); } @Test public void empty() throws ExpressionException { Expression expr = new Expression("string-literal"); Object o = expr.eval(null); assertThat(o).isInstanceOf(String.class); assertThat(o).isEqualTo("string-literal"); } @Test public void scope() throws ExpressionException { HashMap<String, String> scope = new HashMap<String, String>(); scope.put("a", "foo"); Expression expr = new Expression("${a}bar"); Object o = expr.eval(scope); assertThat(o).isInstanceOf(String.class); assertThat(o).isEqualTo("foobar"); } @Test public void exchangeRequestHeader() throws ExpressionException { Exchange exchange = new Exchange(); exchange.request = new Request(); exchange.request.headers.putSingle("Host", "www.example.com"); Expression expr = new Expression("${exchange.request.headers['Host'][0]}"); String host = expr.eval(exchange, String.class); assertThat(host).isEqualTo("www.example.com"); }
Form extends MultiValueMap<String, String> { public void toRequestQuery(Request request) { try { request.uri = URIUtil.create(request.uri.getScheme(), request.uri.getRawUserInfo(), request.uri.getHost(), request.uri.getPort(), request.uri.getRawPath(), toString(), request.uri.getRawFragment()); } catch (URISyntaxException use) { throw new IllegalArgumentException(use); } } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }
@Test void toRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form(); f.add("foo", "bar"); f.toRequestQuery(request); assertThat(f.get("x")).isNull(); assertThat(f.get("y")).isNull(); assertThat(f.get("z")).isNull(); assertThat(f.get("foo").get(0)).isEqualTo("bar"); assertThat(request.uri.toString()).isEqualTo("http: }
Form extends MultiValueMap<String, String> { public void appendRequestQuery(Request request) { StringBuilder sb = new StringBuilder(); String uriQuery = request.uri.getRawQuery(); if (uriQuery != null && uriQuery.length() > 0) { sb.append(uriQuery); } String toAppend = toString(); if (toAppend != null && toAppend.length() > 0) { if (sb.length() > 0) { sb.append('&'); } sb.append(toAppend); } String newQuery = sb.toString(); if (newQuery.length() == 0) { newQuery = null; } try { request.uri = URIUtil.create(request.uri.getScheme(), request.uri.getRawUserInfo(), request.uri.getHost(), request.uri.getPort(), request.uri.getRawPath(), newQuery, request.uri.getRawFragment()); } catch (URISyntaxException use) { throw new IllegalArgumentException(use); } } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }
@Test void appendRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form(); f.add("foo", "bar"); f.appendRequestQuery(request); f.fromRequestQuery(request); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("?"); assertThat(f.get("z").get(0)).isEqualTo("a"); assertThat(f.get("foo").get(0)).isEqualTo("bar"); assertThat(request.uri.toString()).isEqualTo("http: }
CaseInsensitiveMap extends MapDecorator<String, V> { @Override public V put(String key, V value) { V removed = remove(key); lc.put(key.toLowerCase(), key); super.put(key, value); return removed; } CaseInsensitiveMap(); CaseInsensitiveMap(Map<String, V> map); void sync(); @Override void clear(); @Override boolean containsKey(Object key); @Override V put(String key, V value); @Override void putAll(Map<? extends String, ? extends V> m); @Override V get(Object key); @Override V remove(Object key); }
@Test public void upperPut_keyRetainsCase() { map.put(upper, value1); assertThat(map.keySet().iterator().next()).isEqualTo(upper); } @Test public void lowerPut_keyRetainsCase() { map.put(lower, value1); assertThat(map.keySet().iterator().next()).isEqualTo(lower); }
Consumer extends Relationship { public static Consumer by(Component consumer) { return new Consumer(consumer); } @JsonCreator Consumer(@JsonProperty("component") Component component); static Consumer by(Component consumer); @Override int hashCode(); @Override boolean equals(Object o); }
@Test public void testToString() { String toString = Consumer.by(Component.of("wolverine", "xmen")).toString(); Assert.assertTrue(toString.contains("wolverine")); Assert.assertTrue(toString.contains("xmen")); } @Test public void staticFactoryMethodShouldReturnSameResultAsConstructor() { Component a = TestHelper.componentA(); Consumer expected = new Consumer(a); Consumer actual = Consumer.by(a); Assert.assertEquals(expected, actual); }
Node { public static Node of(Component component) { return Node.of(component, randomSize()); } static Node create(String id, String label); static Node of(Component component); static Node of(Component component, int size); static Node of(ComponentRelationships rel); @Override boolean equals(Object o); @Override int hashCode(); static int randomSize(); static int randomCoordinate(); }
@Test public void nodeFromComponent() { Node node = Node.of(Component.of("apocalypse", "villain")); Assert.assertEquals("villain:apocalypse", node.getId()); Assert.assertEquals("villain:apocalypse", node.getLabel()); Assert.assertTrue(node.getSize() > 2); Assert.assertTrue(node.getX() >= 0); Assert.assertTrue(node.getY() >= 0); }
Node { public static Node create(String id, String label) { return Node.create(id, label, randomCoordinate(), randomCoordinate(), randomSize()); } static Node create(String id, String label); static Node of(Component component); static Node of(Component component, int size); static Node of(ComponentRelationships rel); @Override boolean equals(Object o); @Override int hashCode(); static int randomSize(); static int randomCoordinate(); }
@Test(expected = NullPointerException.class) public void nullIdShouldThrowNpe() { Node.create(null, "label", 1, 2, 3); } @Test(expected = NullPointerException.class) public void nullLabelShouldThrowNpe() { Node.create("id", null, 1, 2, 3); } @Test public void randomCoordinatesAndSize() { Node node = Node.create("id", "label"); Assert.assertTrue(node.getX() >= 0); Assert.assertTrue(node.getY() >= 0); Assert.assertTrue(node.getSize() > 0); }
Edge { public static Edge from(Component component, Consumer consumer) { String to = component.asString().toLowerCase(); String from = consumer.getComponent().asString().toLowerCase(); return Edge.create(from + "-to-" + to, from, to); } static Edge to(Component component, Dependency dependency); static Edge from(Component component, Consumer consumer); }
@Test public void consumerToComponent() { Edge actual = Edge.from(Component.of("phoenix", "superhero"), Consumer.by(Component.of("cyclop", "superhero"))); Edge expected = Edge.create("superhero:cyclop-to-superhero:phoenix", "superhero:cyclop", "superhero:phoenix"); Assert.assertEquals(expected, actual); }
Edge { public static Edge to(Component component, Dependency dependency) { String from = component.asString().toLowerCase(); String to = dependency.getComponent().asString().toLowerCase(); return Edge.create(from + "-to-" + to, from, to); } static Edge to(Component component, Dependency dependency); static Edge from(Component component, Consumer consumer); }
@Test public void componentToDependency() { Edge actual = Edge.to(Component.of("phoenix", "superhero"), Dependency.on(Component.of("xavier", "superhero"))); Edge expected = Edge.create("superhero:phoenix-to-superhero:xavier", "superhero:phoenix", "superhero:xavier"); Assert.assertEquals(expected, actual); }
SimpleSystemResolver implements SystemResolver { @Override public System resolve(String systemName, SnitchRegistry snitchRegistry) { Set<SystemFragment> frags = new HashSet<>(); Set<ResolutionError> errors = new HashSet<>(); for (Snitch snitch : snitchRegistry.getAll()) { try { frags.add(snitch.snitch()); } catch (SnitchingException e) { LOGGER.error("Snitch error caught while resolving system at URI : " + e.getSnitchUri(), e); errors.add(ResolutionError.translate(e)); } catch (RuntimeException e) { LOGGER.error("Technical error caught while resolving system at URI : " + snitch.getUri(), e); errors.add(ResolutionError.of(snitch.getUri(), DEFAULT_ERROR_MESSAGE)); } } return resolveBuilder(systemName, frags).errors(errors).build(); } @Override System resolve(String systemName, SnitchRegistry snitchRegistry); @Override System resolve(String systemName, Collection<SystemFragment> fragments); }
@Test public void resolvingEmptySnitchRegistryShouldReturnEmptySystem() { System actual = resolver.resolve(SYSTEM_NAME, StaticSnitchRegistry.of()); Assertions.assertThat(actual).isEqualTo(System.empty(SYSTEM_NAME)); } @Test public void resolvingComponentRelationshipsShouldCreateInvertedRelationshipOnRelatedComponents() { ComponentRelationships wolverineRels = ComponentRelationships.builder() .component(WOLVERINE) .addDependency(Dependency.on(PHOENIX)) .addConsumer(Consumer.by(SABRETOOTH)) .build(); Snitch snitch1 = StaticSnitch.of(URI.create("fake: System actual = resolver.resolve(SYSTEM_NAME, StaticSnitchRegistry.of(snitch1)); ComponentRelationships wolverineResolved = ComponentRelationships.builder() .component(WOLVERINE) .addDependency(Dependency.on(PHOENIX)) .addConsumer(Consumer.by(SABRETOOTH)) .build(); ComponentRelationships phoenixResolved = ComponentRelationships.builder() .component(PHOENIX) .addConsumer(Consumer.by(WOLVERINE)) .build(); ComponentRelationships sabretoothResolved = ComponentRelationships.builder() .component(SABRETOOTH) .addDependency(Dependency.on(WOLVERINE)) .build(); System expected = System.of(SYSTEM_NAME, wolverineResolved, phoenixResolved, sabretoothResolved); Assertions.assertThat(actual).isEqualTo(expected); } @Test public void resolveBidirectionalRelationship() { ComponentRelationships cyclopRels = ComponentRelationships.builder() .component(CYCLOP) .addDependency(Dependency.on(PHOENIX)) .addDependency(Dependency.on(XAVIER)) .build(); ComponentRelationships phoenixRels = ComponentRelationships.builder() .component(PHOENIX) .addDependency(Dependency.on(CYCLOP)) .addDependency(Dependency.on(XAVIER)) .build(); Snitch snitch1 = StaticSnitch.of(URI.create("fake: Snitch snitch2 = StaticSnitch.of(URI.create("fake: SnitchRegistry registry = StaticSnitchRegistry.of(snitch1, snitch2); System actual = resolver.resolve(SYSTEM_NAME, registry); ComponentRelationships cyclopResolved = ComponentRelationships.builder() .component(CYCLOP) .addDependency(Dependency.on(PHOENIX)) .addDependency(Dependency.on(XAVIER)) .addConsumer(Consumer.by(PHOENIX)) .build(); ComponentRelationships phoenixResolved = ComponentRelationships.builder() .component(PHOENIX) .addDependency(Dependency.on(CYCLOP)) .addDependency(Dependency.on(XAVIER)) .addConsumer(Consumer.by(CYCLOP)) .build(); ComponentRelationships xavierResolved = ComponentRelationships.builder() .component(XAVIER) .addConsumer(Consumer.by(CYCLOP)) .addConsumer(Consumer.by(PHOENIX)) .build(); System expected = System.of(SYSTEM_NAME, cyclopResolved, phoenixResolved, xavierResolved); Assertions.assertThat(actual).isEqualTo(expected); } @Test public void resolveSelfRelationship() { ComponentRelationships cable = ComponentRelationships.builder() .component(CABLE) .addConsumer(Consumer.by(CABLE)) .build(); ComponentRelationships cableResolved = ComponentRelationships.builder() .component(CABLE) .addConsumer(Consumer.by(CABLE)) .addDependency(Dependency.on(CABLE)) .build(); Snitch snitch1 = StaticSnitch.of(URI.create("fake: System actual = resolver.resolve(SYSTEM_NAME, StaticSnitchRegistry.of(snitch1)); System expected = System.of(SYSTEM_NAME, cableResolved); Assertions.assertThat(actual).isEqualTo(expected); } @Test public void snitchingExceptionShouldBeTranslatedToError() { Snitch snitchMock = Mockito.mock(Snitch.class); URI uri = URI.create("http: String message = "nope"; Mockito.when(snitchMock.getUri()).thenReturn(uri); SnitchingException snitchingExceptionMock = Mockito.mock(SnitchingException.class); Mockito.when(snitchingExceptionMock.getMessage()).thenReturn(message); Mockito.when(snitchingExceptionMock.getSnitchUri()).thenReturn(uri); Mockito.when(snitchMock.snitch()).thenThrow(snitchingExceptionMock); System actual = resolver.resolve(SYSTEM_NAME, StaticSnitchRegistry.of(snitchMock)); ResolutionError error = ResolutionError.of(uri, message); System expected = System.of(SYSTEM_NAME, new HashSet<>(), new HashSet<>(Arrays.asList(error))); Assertions.assertThat(actual).isEqualTo(expected); } @Test public void runtimeExceptionShouldBeTranslatedToError() { Snitch snitchMock = Mockito.mock(Snitch.class); URI uri = URI.create("http: String message = "nope"; Mockito.when(snitchMock.getUri()).thenReturn(uri); RuntimeException exceptionMock = Mockito.mock(RuntimeException.class); Mockito.when(exceptionMock.getMessage()).thenReturn(message); Mockito.when(snitchMock.snitch()).thenThrow(exceptionMock); System actual = resolver.resolve(SYSTEM_NAME, StaticSnitchRegistry.of(snitchMock)); ResolutionError error = ResolutionError.of(uri, "Could not access or process Snitch"); System expected = System.of(SYSTEM_NAME, new HashSet<>(), new HashSet<>(Arrays.asList(error))); Assertions.assertThat(actual).isEqualTo(expected); } @Test public void resolutionUsingFragmentsShouldNotReturnErrors() { System system = resolver.resolve(SYSTEM_NAME, new HashSet<>()); Assertions.assertThat(system).isEqualTo(System.empty(SYSTEM_NAME)); }
StaticSnitchRegistry implements SnitchRegistry { @Override public List<Snitch> getAll() { return new ArrayList<>(registry); } StaticSnitchRegistry(Snitch... snitches); StaticSnitchRegistry(Collection<Snitch> snitches); static SnitchRegistry of(Snitch... snitches); static SnitchRegistry of(Collection<Snitch> snitches); static List<Snitch> filterDuplicateLocations(Collection<Snitch> snitches); @Override List<Snitch> getAll(); }
@Test public void getAll() { Snitch snitch1 = Mockito.mock(Snitch.class); Mockito.when(snitch1.getUri()).thenReturn(URI.create("fake: Snitch snitch2 = Mockito.mock(Snitch.class); Mockito.when(snitch2.getUri()).thenReturn(URI.create("fake: Snitch snitchDuplicate2 = Mockito.mock(Snitch.class); Mockito.when(snitchDuplicate2.getUri()).thenReturn(URI.create("fake: SnitchRegistry registry = StaticSnitchRegistry.of(snitch1, snitch2); List<Snitch> actual = registry.getAll(); List<Snitch> expected = new ArrayList<>(Arrays.asList(snitch1, snitch2)); Assert.assertEquals(expected, actual); }
StaticSnitchRegistry implements SnitchRegistry { public static SnitchRegistry of(Snitch... snitches) { return new StaticSnitchRegistry(snitches); } StaticSnitchRegistry(Snitch... snitches); StaticSnitchRegistry(Collection<Snitch> snitches); static SnitchRegistry of(Snitch... snitches); static SnitchRegistry of(Collection<Snitch> snitches); static List<Snitch> filterDuplicateLocations(Collection<Snitch> snitches); @Override List<Snitch> getAll(); }
@Test public void testToString() { String uri = "fake: Snitch fakeSnitch = StaticSnitch.of(URI.create(uri)); SnitchRegistry registry = StaticSnitchRegistry.of(fakeSnitch); Assert.assertTrue(registry.toString().contains(uri)); }
ResolutionError { public static ResolutionError of(URI snitchUri, String message, Throwable cause) { return new ResolutionError(snitchUri, message, cause); } ResolutionError(URI snitchUri, String message, Throwable cause); static ResolutionError translate(SnitchingException e); static ResolutionError of(URI snitchUri, String message, Throwable cause); static ResolutionError of(URI snitchUri, String message); @Override int hashCode(); @Override boolean equals(Object obj); String getMessage(); URI getSnitchUri(); boolean hasCause(); @JsonIgnore Optional<Throwable> getCause(); Optional<String> getCauseStackTraceString(); }
@Test public void testToString() { ResolutionError of = ResolutionError.of(SNITCH_URI, MESSAGE, new RuntimeException("whatever")); Assertions.assertThat(of.toString()).isNotEmpty(); }
ResolutionError { static void closeQuietly(Closeable... closeables) { for (Closeable closeable : closeables) { try { closeable.close(); } catch (IOException e) { LOGGER.error("Error while closing writer after printing StackTrace", e); } } } ResolutionError(URI snitchUri, String message, Throwable cause); static ResolutionError translate(SnitchingException e); static ResolutionError of(URI snitchUri, String message, Throwable cause); static ResolutionError of(URI snitchUri, String message); @Override int hashCode(); @Override boolean equals(Object obj); String getMessage(); URI getSnitchUri(); boolean hasCause(); @JsonIgnore Optional<Throwable> getCause(); Optional<String> getCauseStackTraceString(); }
@Test public void close() throws IOException { Closeable closeableMock = Mockito.mock(Closeable.class); Mockito.doThrow(Mockito.mock(IOException.class)).when(closeableMock).close(); ResolutionError.closeQuietly(closeableMock); }
CompositeSnitchRegistry implements SnitchRegistry { @Override public List<Snitch> getAll() { return registries.stream() .map(SnitchRegistry::getAll) .flatMap(Collection::stream) .collect(Collectors.toList()); } CompositeSnitchRegistry(Collection<SnitchRegistry> registries); static SnitchRegistry of(SnitchRegistry... registries); static SnitchRegistry of(Collection<SnitchRegistry> registries); @Override List<Snitch> getAll(); }
@Test public void getAll() { Snitch s1 = new StaticSnitch(URI.create("fake: Snitch s2 = new StaticSnitch(URI.create("fake: ArrayList<SnitchRegistry> registries = Lists.newArrayList(StaticSnitchRegistry.of(s1), StaticSnitchRegistry.of(s2)); SnitchRegistry composite = CompositeSnitchRegistry.of(registries); List<Snitch> expected = Arrays.asList(s1, s2); Assert.assertEquals(expected, composite.getAll()); }
DefaultSystemService implements SystemService { @Override @CacheResult(cacheName = "io.cereebro.system") public System get() { return systemResolver.resolve(name, snitchRegistry); } DefaultSystemService(String name, SystemResolver systemResolver, SnitchRegistry snitchRegistry); @Override @CacheResult(cacheName = "io.cereebro.system") System get(); }
@Test public void getSystem() { Mockito.when(systemResolver.resolve(NAME, snitchRegistry)).thenReturn(System.empty(NAME)); Assert.assertEquals(System.empty(NAME), service.get()); }
SystemFragment { public static SystemFragment empty() { return new SystemFragment(new HashSet<>()); } @JsonCreator SystemFragment(@JsonProperty("componentRelationships") Set<ComponentRelationships> rels); static SystemFragment of(Set<ComponentRelationships> rels); static SystemFragment of(ComponentRelationships... rels); static SystemFragment empty(); @Override boolean equals(Object o); @Override int hashCode(); Set<ComponentRelationships> getComponentRelationships(); }
@Test public void testToString() { Assert.assertNotNull(SystemFragment.empty().toString()); }
SnitchingException extends RuntimeException { public URI getSnitchUri() { return snitchUri; } SnitchingException(URI snitch, String message, Throwable cause); SnitchingException(URI snitch, String message); SnitchingException(URI snitch, Throwable cause); URI getSnitchUri(); }
@Test public void uriAndMessageConstructor() { URI uri = URI.create("fake: String message = "test"; SnitchingException e = new SnitchingException(uri, message); Assert.assertEquals(uri, e.getSnitchUri()); Assert.assertEquals(message, e.getMessage()); } @Test public void throwableAndUriConstructor() { URI uri = URI.create("fake: Throwable cause = new RuntimeException("unit test"); SnitchingException e = new SnitchingException(uri, cause); Assert.assertEquals(uri, e.getSnitchUri()); Assert.assertEquals(cause, e.getCause()); }
StaticSnitch implements Snitch { @Override public URI getUri() { return uri; } StaticSnitch(URI uri); StaticSnitch(URI uri, SystemFragment systemFragment); static Snitch of(URI uri); static Snitch of(URI uri, SystemFragment systemFragment); @Override int hashCode(); @Override boolean equals(Object obj); @Override URI getUri(); @Override SystemFragment snitch(); }
@Test public void getLocation() { Assert.assertEquals(SNITCH_URI, snitch.getUri()); }
StaticSnitch implements Snitch { @Override public SystemFragment snitch() { return systemFragment; } StaticSnitch(URI uri); StaticSnitch(URI uri, SystemFragment systemFragment); static Snitch of(URI uri); static Snitch of(URI uri, SystemFragment systemFragment); @Override int hashCode(); @Override boolean equals(Object obj); @Override URI getUri(); @Override SystemFragment snitch(); }
@Test public void snitch() { SystemFragment actual = snitch.snitch(); Assert.assertEquals(SystemFragment.empty(), actual); }
Dependency extends Relationship { public static Dependency on(Component component) { return new Dependency(component); } @JsonCreator Dependency(@JsonProperty("component") Component component); static Dependency on(Component component); Set<Relationship> asRelationshipSet(); @Override int hashCode(); @Override boolean equals(Object o); }
@Test public void testToString() { String toString = Dependency.on(Component.of("storm", "xmen")).toString(); Assert.assertTrue(toString.contains("storm")); Assert.assertTrue(toString.contains("xmen")); } @Test public void staticFactoryMethodShouldReturnSameAsConstructor() { Component b = TestHelper.componentB(); Dependency expected = new Dependency(b); Dependency actual = Dependency.on(b); Assert.assertEquals(expected, actual); }
System { public static System of(String name, Collection<ComponentRelationships> rels) { return new System(name, rels); } System(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); System(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); static System of(String name, ComponentRelationships... rels); static System empty(String name); boolean hasErrors(); @Override boolean equals(Object o); @Override int hashCode(); String getName(); Set<ComponentRelationships> getComponentRelationships(); Set<ResolutionError> getErrors(); static SystemBuilder builder(); }
@Test(expected = NullPointerException.class) public void constructorWithNullNameShouldThrowNullPointerException() { ComponentRelationships c = ComponentRelationships.of(TestHelper.componentA(), TestHelper.relationshipSetOfDependencyBAndConsumerC()); new System(null, new HashSet<>(Arrays.asList(c))); }
Dependency extends Relationship { public Set<Relationship> asRelationshipSet() { return new HashSet<>(Arrays.asList(this)); } @JsonCreator Dependency(@JsonProperty("component") Component component); static Dependency on(Component component); Set<Relationship> asRelationshipSet(); @Override int hashCode(); @Override boolean equals(Object o); }
@Test public void asRelationshipSet() { Dependency dependency = Dependency.on(Component.of("x", "y")); Set<Relationship> rels = dependency.asRelationshipSet(); Assertions.assertThat(rels).isEqualTo(new HashSet<>(Arrays.asList(dependency))); }
FixedRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return new HashSet<>(relationships); } FixedRelationshipDetector(Collection<Relationship> rels); @Override Set<Relationship> detect(); }
@Test public void constructorShouldCopyCollection() { Dependency a = Dependency.on(TestHelper.componentA()); List<Relationship> originalCollection = new ArrayList<>(); originalCollection.add(a); FixedRelationshipDetector detector = new FixedRelationshipDetector(originalCollection); Dependency b = Dependency.on(TestHelper.componentB()); originalCollection.add(b); Set<Relationship> actual = detector.detect(); Set<Relationship> expected = new HashSet<>(); expected.add(a); Assert.assertEquals(expected, actual); }