method2testcases
stringlengths
118
3.08k
### Question: NamedExtension implements Extension<T> { @Override public String getKey() { return key; } NamedExtension(String key); @Override String getKey(); @Override boolean equals(Object o); boolean equals(NamedExtension<?> o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void named_extensions_returns_its_own_key() { assertEquals("my.extension", Extension.key("my.extension").getKey()); } @Test(expected = UnsupportedOperationException.class) public void anonymous_throws_if_try_to_get_the_key() { Extension.anonymous().getKey(); }
### Question: LocalRrCache implements Storage, Debuggable { @Override public List<Integer> getCacheIds() { List<Integer> ids = new ArrayList<>(); for (CacheElement cacheElement : cacheStorage) { if (cacheElement != null) { ids.add(cacheElement.getId()); } } return ids; } LocalRrCache(Storage backendStore, int cacheSize); @Override boolean store(int id, String value); @Override String load(int id); @Override ClusterStatus getCurrentClusterStatus(); @Override boolean getCurrentNodeStatus(InetAddress ia); @Override List<Integer> getCacheIds(); }### Answer: @Test public void testStorage() { storeAndLoad(1000); storeAndLoad(1001); storeAndLoad(1002); Assertions.assertEquals(Arrays.asList(1000, 1001, 1002), localRrCache.getCacheIds()); storeAndLoad(1003); storeAndLoad(1004); Assertions.assertEquals(Arrays.asList(1000, 1001, 1002, 1003, 1004), localRrCache.getCacheIds()); for (int i = 1000; i < 1010; i++) { storeAndLoad(i); } }
### Question: Part02Transform { public Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress) { return Mono.zip(phoneNumber, deliveryAddress, (p, d) -> new Order(p, d)); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void combineValues() { Mono<String> phoneNumber = Mono.just("076123456"); Mono<String> deliveryAddress = Mono.just("Paradeplatz Zurich"); Mono<Order> order = workshop.combineValues(phoneNumber, deliveryAddress); StepVerifier.create(order).expectNext(new Order("076123456", "Paradeplatz Zurich")); order = workshop.combineValues(Mono.empty(), deliveryAddress); StepVerifier.create(order).verifyComplete(); order = workshop.combineValues(Mono.error(new RuntimeException()), deliveryAddress); StepVerifier.create(order).verifyError(); }
### Question: Part03Filtering { Flux<Integer> filterEven(Flux<Integer> flux) { return flux.filter(i -> i % 2 == 0).log(); } }### Answer: @Test public void filterEven() { Flux<Integer> flux = workshop.filterEven(Flux.just(1, 2, 3, 4, 5)); StepVerifier.create(flux) .expectNext(2, 4) .verifyComplete(); }
### Question: Part03Filtering { Flux<Integer> ignoreDuplicates(Flux<Integer> flux) { return flux.distinct().log(); } }### Answer: @Test public void ignoreDuplicates() { Flux<Integer> flux = workshop.ignoreDuplicates(Flux.just(1, 1, 2, 2, 3, 4)); StepVerifier.create(flux) .expectNext(1, 2, 3, 4) .verifyComplete(); }
### Question: Part03Filtering { Mono<Integer> emitLast(Flux<Integer> flux) { return flux.last(100).log(); } }### Answer: @Test public void takeAtMostOne() { Mono<Integer> mono = workshop.emitLast(Flux.just(51, 61, 12)); StepVerifier.create(mono) .expectNext(12) .verifyComplete(); mono = workshop.emitLast(Flux.empty()); StepVerifier.create(mono).expectNext(100).verifyComplete(); }
### Question: Part03Filtering { Flux<Integer> ignoreUntil(Flux<Integer> flux) { return flux.skipUntil(integer -> integer > 10).log(); } }### Answer: @Test public void ignoreUntil() { Flux<Integer> flux = workshop.ignoreUntil(Flux.just(1, 3, 15, 5, 10)); StepVerifier.create(flux) .expectNext(15, 5, 10) .verifyComplete(); StepVerifier.create(workshop.ignoreUntil(Flux.just(1, 3, 5))).verifyComplete(); StepVerifier.create(workshop.ignoreUntil(Flux.empty())).verifyComplete(); }
### Question: Part03Filtering { Mono<Integer> expectAtMostOneOrEmpty(Flux<Integer> flux) { return flux.singleOrEmpty().log(); } }### Answer: @Test public void expectAtMostOneOrEmpty() { Mono<Integer> mono = workshop.expectAtMostOneOrEmpty(Flux.just(1, 2, 3)); StepVerifier.create(mono) .expectError() .verify(); StepVerifier.create(Flux.just(1)).expectNext(1).verifyComplete(); StepVerifier.create(Flux.empty()).verifyComplete(); }
### Question: Part03Filtering { Mono<Boolean> asyncFilter(Integer integer) { return Mono.just(integer % 2 == 0).delayElement(Duration.ofMillis(500)); } }### Answer: @Test public void asyncFilter() { Flux<Integer> flux = workshop.asyncComputedFilter(Flux.just(1, 2, 3, 4, 5)); StepVerifier.create(flux) .expectNext(2, 4) .verifyComplete(); }
### Question: SimpleArrayList extends AbstractList<E> implements List<E> { @Override public E remove(int index) { E old = get(index); while (index + 1 < size) { counter += 2; arr[index] = arr[index + 1]; index++; } counter++; arr[size] = null; size--; return old; } @Override int size(); @SuppressWarnings("unchecked") @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); long getCounter(); }### Answer: @Test public void testRemove() { int[] numbers = new int[10]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i; list.add(i, i); } assertListValues(numbers); list.remove(1); list.remove(0); int[] remainingNumbers = Arrays.copyOfRange(numbers, 2, numbers.length); assertListValues(remainingNumbers); }
### Question: Matrix { public boolean equals(Matrix matrix) { return height == matrix.height && width == matrix.width && Arrays.equals(data, matrix.data); } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testEquals() { Matrix matrix1 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix2 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix3 = new Matrix(2, 3, new double[]{1, 2, 3, 4, 5, 6}); Matrix matrix4 = new Matrix(0, 0, new double[]{}); Assert.assertTrue(matrix1.equals(matrix1)); Assert.assertTrue(matrix1.equals(matrix2)); Assert.assertFalse(matrix1.equals(matrix3)); Assert.assertFalse(matrix1.equals(matrix4)); }
### Question: Matrix { public Matrix multiply(Matrix matrix) { if (width != matrix.height) { throw new IllegalArgumentException("Invalid sizes"); } int index1 = 0, index3 = 0; Matrix newmatrix = new Matrix(height, matrix.width, null); for (int i = 0; i < height; i++) { for (int j = 0; j < matrix.width; j++) { double counter = 0.0; int index2 = 0; for (int k = 0; k < width; k++) { counter += data[index1 + k] * matrix.data[index2 + j]; index2 += matrix.width; } newmatrix.data[index3 + j] = counter; } index1 += width; index3 += matrix.width; } return newmatrix; } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testMultiply() { Matrix matrix1 = new Matrix(2, 3, new double[]{1, 2, 3, 4, 5, 6}); Matrix matrix2 = new Matrix(3, 2, new double[]{3, 6, 2, 5, 1, 4}); Matrix matrix3 = new Matrix(2, 2, new double[]{10, 28, 28, 73}); Matrix matrix4 = matrix1.multiply(matrix2); Assert.assertTrue(matrix3.equals(matrix4)); Matrix matrix5 = matrix1.multiplyNative(matrix2); Assert.assertTrue(matrix3.equals(matrix5)); }
### Question: Matrix { public Matrix power(int k) { if (height != width) { throw new IllegalArgumentException("Matrix is not a square"); } if (k < 1) { throw new IllegalArgumentException("Invalid power"); } if (k == 1) { return this; } Matrix matrix = this; for (int i = 1; i < k; i++) { matrix = multiply(matrix); } return matrix; } Matrix(int height, int width, double[] data); Matrix(int height, int width); Matrix(int height, int width, double value); boolean equals(Matrix matrix); Matrix multiplyWithTime(Matrix matrix); Matrix multiply(Matrix matrix); Matrix multiplyNativeWithTime(Matrix matrix); Matrix multiplyNative(Matrix matrix); Matrix powerWithTime(int k); Matrix power(int k); Matrix powerNativeWithTime(int k); Matrix powerNative(int k); }### Answer: @Test public void testPower() { Matrix matrix1 = new Matrix(2, 2, new double[]{1, 2, 3, 4}); Matrix matrix2 = matrix1.powerNative(1); Assert.assertTrue(matrix1.equals(matrix2)); Matrix matrix3 = new Matrix(2, 2, new double[]{7, 10, 15, 22}); Matrix matrix4 = matrix1.power(2); Assert.assertTrue(matrix3.equals(matrix4)); Matrix matrix5 = new Matrix(2, 2, new double[]{37, 54, 81, 118}); Matrix matrix6 = matrix1.power(3); Assert.assertTrue(matrix5.equals(matrix6)); Matrix matrix7 = matrix1.powerNative(1); Assert.assertTrue(matrix1.equals(matrix7)); Matrix matrix8 = new Matrix(2, 2, new double[]{7, 10, 15, 22}); Matrix matrix9 = matrix1.powerNative(2); Assert.assertTrue(matrix8.equals(matrix9)); Matrix matrix10 = new Matrix(2, 2, new double[]{37, 54, 81, 118}); Matrix matrix11 = matrix1.powerNative(3); Assert.assertTrue(matrix10.equals(matrix11)); }
### Question: DataSet { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((movieList == null) ? 0 : movieList.hashCode()); result = prime * result + ((rentalList == null) ? 0 : rentalList.hashCode()); result = prime * result + ((userList == null) ? 0 : userList.hashCode()); return result; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testHashCode() throws Exception { DataSet ds2 = new DataSet(MovieRentalView.getDateFormatter()); assertEquals(ds.hashCode(), ds2.hashCode()); List<Movie> ml = ds2.getMovieList(); ml.clear(); ml.add(new Movie("Bla", RegularPriceCategory.getInstance())); assertTrue(ds.hashCode() != ds2.hashCode()); }
### Question: DataSet { public DataSet(DateFormat dateFormat) throws Exception { this.dateFormat = dateFormat; db = new Database(); db.initDatabase(); initLists(); } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testDataSet() throws Exception { assertNotNull(ds); }
### Question: DataSet { public List<IUser> getUserList() { return this.userList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterUserList() { assertNotNull(ds.getUserList()); }
### Question: DataSet { public Object[][] getUserListAsObject() { int listSize = userList != null ? userList.size() : 0; Object[][] userArray = new Object[listSize][3]; if (userList != null) { int i = 0; for (IUser u : userList) { userArray[i][0] = u.getId(); userArray[i][1] = u.getName(); userArray[i][2] = u.getFirstName(); i++; } } return userArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetUserListAsObject() { Object[][] arr = ds.getUserListAsObject(); assertNotNull(arr); assertEquals(arr.length, ds.getUserList().size()); assertEquals(3, arr[0].length); }
### Question: DataSet { public IUser getUserByName(String name) { for (IUser c : userList) { if (c.getName().equalsIgnoreCase(name)) { return c; } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetUserByName() { User userNotFound = (User) ds.getUserByName("doesNotExist"); assertNull(userNotFound); User user = (User) ds.getUserByName("Meier"); assertNotNull(user); assertTrue(user.hasRentals()); }
### Question: DataSet { public IUser getUserById(int id) { for (IUser c : userList) { if (c.getId() == id) { return c; } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testRentalsOfUser() { User user = (User) ds.getUserById(1); assertNotNull(user); assertTrue(user.hasRentals()); }
### Question: DataSet { public List<Movie> getMovieList() { return this.movieList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterMovieList() { assertNotNull(ds.getMovieList()); }
### Question: DataSet { public Object[][] getMovieListAsObject(boolean rented, boolean available) { ArrayList<Movie> movieArray = null; if (movieList != null) { movieArray = prepareMovieArray(rented, available); } Object[][] movieObjArray = new Object[movieArray.size()][5]; int i = 0; for (Movie m : movieArray) { movieObjArray[i++] = fillInMovieArrayElement(m); } return movieObjArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetMovieListAsObjectBooleanBoolean() { Object[][] arr = ds.getMovieListAsObject(false, false); assertNotNull(arr); arr = ds.getMovieListAsObject(false, true); assertNotNull(arr); arr = ds.getMovieListAsObject(true, false); assertNotNull(arr); arr = ds.getMovieListAsObject(true, true); assertNotNull(arr); } @Test public void testGetMovieListAsObject() { Object[][] arr = ds.getMovieListAsObject(); assertNotNull(arr); }
### Question: DataSet { public Movie getMovieById(long id) { for (int i = 0; i < movieList.size(); i++) { if (movieList.get(i).getId() == id) { return movieList.get(i); } } return null; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetMovieById() { Movie m = ds.getMovieById(1); assertNotNull(m); assertEquals(1, m.getId()); m = ds.getMovieById(-1000); assertNull(m); }
### Question: DataSet { public void updateMovie(Movie movie) { for (int i = 0; i < movieList.size(); i++) { if (movieList.get(i).getId() == movie.getId()) { movieList.get(i).setRented(movie.isRented()); movieList.get(i).setPriceCategory(movie.getPriceCategory()); } } } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testUpdateMovie() { Movie m1 = ds.getMovieById(1); m1.setRented(!m1.isRented()); ds.updateMovie(m1); Movie m2 = ds.getMovieById(1); assertEquals(m1, m2); }
### Question: DataSet { public List<Rental> getRentalList() { return this.rentalList; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetterGetterRentalList() { assertNotNull(ds.getRentalList()); }
### Question: DataSet { public Object[][] getRentalListAsObject() { int listSize = rentalList != null ? rentalList.size() : 0; Object[][] rentalArray = new Object[listSize][8]; if (rentalList != null) { int i = 0; for (Rental r : rentalList) { rentalArray[i][0] = r.getId(); rentalArray[i][1] = r.getRentalDays(); rentalArray[i][2] = dateFormat.format(r.getRentalDate()); rentalArray[i][3] = r.getUser().getName(); rentalArray[i][4] = r.getUser().getFirstName(); rentalArray[i][5] = r.getMovie().getTitle(); rentalArray[i][6] = r.calcRemainingDaysOfRental(new Date(Calendar.getInstance().getTimeInMillis())); rentalArray[i][7] = r.getRentalFee(); r.setRentalDays((Integer) rentalArray[i][1]); i++; } } return rentalArray; } DataSet(DateFormat dateFormat); List<IUser> getUserList(); IUser getUserById(int id); IUser getUserByName(String name); void updateRentalsWithUser(User user); Object[][] getUserListAsObject(); List<Movie> getMovieList(); Object[][] getMovieListAsObject(boolean rented, boolean available); Movie getMovieById(long id); void updateMovie(Movie movie); Object[][] getMovieListAsObject(); List<Rental> getRentalList(); Object[][] getRentalListAsObject(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testGetRentalListAsObject() { Object[][] arr = ds.getRentalListAsObject(); assertNotNull(arr); assertEquals(arr.length, ds.getRentalList().size()); assertEquals(8, arr[0].length); }
### Question: SQLUserDAO implements UserDAO { @Override public void delete(IUser user) { try { PreparedStatement ps = connection.prepareStatement(DELETE_SQL); ps.setInt(1, user.getId()); ps.execute(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testDelete() throws Exception { Statement s = connection.createStatement(); ResultSet r = s.executeQuery(COUNT_SQL); r.next(); int rows = r.getInt(1); assertEquals(3, rows); UserDAO dao = new SQLUserDAO(connection); User user = new User("Denzler", "Christoph"); user.setId(42); dao.delete(user); IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("CLIENTS"); InputStream stream = this.getClass().getResourceAsStream("UserDaoTestResult.xml"); IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(stream); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); assertEquals(expectedTable, actualTable); connection.close(); dao.delete(user); }
### Question: SQLUserDAO implements UserDAO { @Override public List<IUser> getAll() { try { List<IUser> result = new LinkedList<IUser>(); PreparedStatement ps = connection.prepareStatement(GET_ALL_SQL); ResultSet r = ps.executeQuery(); while (r.next()) { result.add(readUser(r)); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetAll() throws DatabaseUnitException, SQLException, Exception { UserDAO dao = new SQLUserDAO(connection); List<IUser> userlist = dao.getAll(); ITable actualTable = (ITable) userlist; InputStream stream = this.getClass().getResourceAsStream("UserDaoTestData.xml"); IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(stream); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); assertEquals(expectedTable, actualTable); stream = this.getClass().getResourceAsStream("UserDaoSingleRowTest.xml"); IDataSet dataSet = new FlatXmlDataSetBuilder().build(stream); DatabaseOperation.CLEAN_INSERT.execute(tester.getConnection(), dataSet); dao = new SQLUserDAO(tester.getConnection().getConnection()); userlist = dao.getAll(); assertEquals(1, userlist.size()); assertEquals("Bond", userlist.get(0).getName()); stream = this.getClass().getResourceAsStream("UserDaoEmpty.xml"); dataSet = new XmlDataSet(stream); DatabaseOperation.CLEAN_INSERT.execute(tester.getConnection(), dataSet); Connection conn = tester.getConnection().getConnection(); dao = new SQLUserDAO(conn); userlist = dao.getAll(); assertNotNull(userlist); assertEquals(0, userlist.size()); conn.close(); dao.getAll(); }
### Question: SQLUserDAO implements UserDAO { @Override public IUser getById(int id) { try { User result = null; PreparedStatement ps = connection.prepareStatement(GET_BY_ID_SQL); ps.setInt(1, id); ResultSet r = ps.executeQuery(); if (r.next()) { result = readUser(r); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetById() throws SQLException { UserDAO dao = new SQLUserDAO(connection); IUser user = dao.getById(42); assertEquals("Micky", user.getFirstName()); assertEquals("Mouse", user.getName()); assertEquals(42, user.getId()); connection.close(); dao.getById(42); }
### Question: SQLUserDAO implements UserDAO { @Override public List<IUser> getByName(String name) { try { List<IUser> result = new LinkedList<IUser>(); PreparedStatement ps = connection.prepareStatement(GET_BY_NAME_SQL); ps.setString(1, name); ResultSet r = ps.executeQuery(); while (r.next()) { result.add(readUser(r)); } r.close(); ps.close(); return result; } catch (SQLException e) { throw new RuntimeException(e); } } SQLUserDAO(Connection c); @Override void delete(IUser user); @Override List<IUser> getAll(); @Override IUser getById(int id); @Override List<IUser> getByName(String name); @Override void saveOrUpdate(IUser user); }### Answer: @Test(expected = RuntimeException.class) public void testGetByName() throws SQLException { UserDAO dao = new SQLUserDAO(connection); List<IUser> userlist = dao.getByName("Duck"); assertEquals(2, userlist.size()); connection.close(); dao.getByName("Duck"); }
### Question: Database { public void initDatabase() throws Exception { connection = DatabaseJdbcDriver.loadDriver(); createDatabaseModel(); importData(); } void initDatabase(); List<IUser> initUserList(); List<Movie> initMovieList(); List<Rental> initRentalList(); }### Answer: @Test public void testInitDatabase() { try { database.initDatabase(); } catch (Exception e) { fail(e.getMessage()); } }
### Question: Rental { public Rental(IUser aUser, Movie aMovie, int nofRentalDays) { this(aUser, aMovie, nofRentalDays, new Date(Calendar.getInstance().getTimeInMillis())); if (aMovie.isRented()) { throw new IllegalStateException("movie is already rented!"); } aMovie.setRented(true); } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testRental() throws InterruptedException { Date before = new Date(Calendar.getInstance().getTimeInMillis()); Thread.sleep(10); Rental r = new Rental(u1, m1, 42); assertNotNull(r); assertTrue(u1.getRentals().contains(r)); assertTrue(m1.isRented()); assertEquals(42, r.getRentalDays()); Thread.sleep(10); Date after = new Date(Calendar.getInstance().getTimeInMillis()); assertTrue(before.before(r.getRentalDate())); assertTrue(after.after(r.getRentalDate())); assertEquals(u1, r.getUser()); assertEquals(m1, r.getMovie()); }
### Question: Rental { public int calcRemainingDaysOfRental(Date date) { if (date == null) { throw new NullPointerException("given date is not set!"); } Long diff = ((rentalDate.getTime() - date.getTime()) / 86400000) + rentalDays; setRentalDays(Math.abs(diff.intValue())); return diff.intValue(); } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testCalcRemainingDaysOfRental() { Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2008, 10, 05); Date today = new Date(cal.getTimeInMillis()); cal.clear(); cal.set(2008, 10, 06); Date tomorrow = new Date(cal.getTimeInMillis()); Rental r = new Rental(u1, m1, 1); r.setRentalDate(today); int remaining = r.calcRemainingDaysOfRental(tomorrow); assertEquals(0, remaining); try { r.calcRemainingDaysOfRental(null); fail(); } catch (NullPointerException npe) { assertEquals("given date is not set!", npe.getMessage()); } }
### Question: Rental { @Override public boolean equals(Object o) { boolean result = this == o; if (!result) { if (o instanceof Rental) { Rental other = (Rental) o; result = initialized ? id == other.id : initialized == other.initialized; result &= this.movie.equals(other.movie); result &= this.user.equals(other.user); } } return result; } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @Ignore public void testEquals() { }
### Question: Rental { @Override public int hashCode() { int result = initialized ? id : 0; result = result * 19 + movie.hashCode(); result = result * 19 + user.hashCode(); return result; } Rental(IUser aUser, Movie aMovie, int nofRentalDays); private Rental(IUser aUser, Movie aMovie, int nofRentalDays, Date rentaldate); static Rental createRentalFromDb(IUser aUser, Movie aMovie, int nofRentalDays, Date rentalDate); int calcRemainingDaysOfRental(Date date); double getRentalFee(); int getId(); Movie getMovie(); IUser getUser(); Date getRentalDate(); int getRentalDays(); void setId(int anId); void setRentalDays(int nofRentalDays); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testHashCode() { Rental x = new Rental(u1, m1, 5); m1.setRented(false); Rental y = new Rental(u1, m1, 5); assertEquals(x.hashCode(), y.hashCode()); x.setId(42); assertTrue(x.hashCode() != y.hashCode()); y.setId(42); assertEquals(x.hashCode(), y.hashCode()); x.setMovie(m2); assertTrue(x.hashCode() != y.hashCode()); y.setMovie(m2); assertEquals(x.hashCode(), y.hashCode()); x.setUser(u2); assertTrue(x.hashCode() != y.hashCode()); y.setUser(u2); assertEquals(x.hashCode(), y.hashCode()); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public double getCharge(int daysRented) { if (daysRented > 0) { return daysRented * 3; } return 0.0d; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testGetCharge() { assertEquals(0.0d, nrpc.getCharge(-5), tolerance); assertEquals(0.0d, nrpc.getCharge(0), tolerance); assertEquals(3.0d, nrpc.getCharge(1), tolerance); assertEquals(6.0d, nrpc.getCharge(2), tolerance); assertEquals(66.0d, nrpc.getCharge(22), tolerance); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public int getFrequentRenterPoints(int daysRented) { int result = 0; if (daysRented > 0) { if (daysRented == 1) { result = 1; } else { result = 2; } } return result; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testGetFrequentRenterPoints() { assertEquals(0, nrpc.getFrequentRenterPoints(-3)); assertEquals(0, nrpc.getFrequentRenterPoints(0)); assertEquals(1, nrpc.getFrequentRenterPoints(1)); assertEquals(2, nrpc.getFrequentRenterPoints(2)); assertEquals(2, nrpc.getFrequentRenterPoints(50)); }
### Question: NewReleasePriceCategory extends PriceCategory { @Override public String toString() { return "New Release"; } private NewReleasePriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override int getFrequentRenterPoints(int daysRented); @Override String toString(); static NewReleasePriceCategory getInstance(); }### Answer: @Test public void testToString() { assertEquals("New Release", nrpc.toString()); }
### Question: Stock { public int addToStock(Movie movie) { Integer i = stock.get(movie.getTitle()); int inStock = (i == null) ? 0 : i; stock.put(movie.getTitle(), ++inStock); return inStock; } int addToStock(Movie movie); int removeFromStock(Movie movie); int getInStock(String title); void removeFromStock(String title); void addLowStockListener(LowStockListener l); void removeLowStockListener(LowStockListener l); }### Answer: @Test public void testAddToStock() { testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); assertEquals(2, testStock.getInStock(mockMovie.getTitle())); }
### Question: Stock { public int removeFromStock(Movie movie) { String title = movie.getTitle(); Integer i = stock.get(title); int inStock = (i == null) ? 0 : i; if (inStock <= 0) { throw new MovieRentalException("no video in stock"); } stock.put(title, --inStock); notifyListeners(movie, inStock); return inStock; } int addToStock(Movie movie); int removeFromStock(Movie movie); int getInStock(String title); void removeFromStock(String title); void addLowStockListener(LowStockListener l); void removeLowStockListener(LowStockListener l); }### Answer: @Test(expected=MovieRentalException.class) public void testRemoveFromStock() throws Exception { testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.addToStock(mockMovie); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 3); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 2); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 1); testStock.removeFromStock(mockMovie); assertEquals(testStock.getInStock(mockMovie.getTitle()), 0); testStock.removeFromStock(mockMovie.getTitle()); }
### Question: User implements IUser { public User(String aName, String aFirstName) { if (aName != null) { if ((aName.length() == 0) || (aName.length() > 40)) { throw new MovieRentalException("invalid name value"); } } else { throw new NullPointerException("invalid name value"); } checkIfFirstNameValid(aFirstName); this.name = aName; this.firstName = aFirstName; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testUser() { User u = new User(NAME, FIRSTNAME); assertNotNull("u should not be null", u); String n = u.getName(); String f = u.getFirstName(); assertEquals(NAME, n); assertEquals(FIRSTNAME, f); List<Rental> rentals = u.getRentals(); assertNotNull("rentals list should be empty, not null", rentals); assertEquals(0, rentals.size()); }
### Question: User implements IUser { public double getCharge() { double result = 0.0d; for (Rental rental : rentals) { result += rental.getMovie().getPriceCategory().getCharge(rental.getRentalDays()); } return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testGetCharge() { double delta=1e-6; User u = new User(NAME, FIRSTNAME); double charge = u.getCharge(); assertEquals(0.0d, charge, delta); PriceCategory regular = RegularPriceCategory.getInstance(); Movie mov = new Movie("A", regular); Rental r = new Rental(u, mov, 1); charge = r.getRentalFee(); assertEquals(charge, u.getCharge(), delta); mov = new Movie("B", regular); r = new Rental(u, mov, 1); charge += r.getRentalFee(); mov = new Movie("C", regular); r = new Rental(u, mov, 1); charge += r.getRentalFee(); assertEquals(charge, u.getCharge(), delta); }
### Question: User implements IUser { @Override public boolean equals(Object o) { boolean result = this == o; if (!result) { if (o instanceof User) { User other = (User) o; result = initialized ? id == other.id : initialized == other.initialized; result &= name.equals(other.name); result &= firstName.equals(other.firstName); } } return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test @Ignore public void testEquals() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { }
### Question: User implements IUser { @Override public int hashCode() { int result = (initialized) ? id : 0; result = 19 * result + name.hashCode(); result = 19 * result + firstName.hashCode(); return result; } User(String aName, String aFirstName); int getId(); void setId(int anID); List<Rental> getRentals(); void setRentals(List<Rental> someRentals); String getName(); void setName(String aName); String getFirstName(); void setFirstName(String aFirstName); Calendar getBirthdate(); double getCharge(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasRentals(); int addRental(Rental rental); }### Answer: @Test public void testHashCode() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { IUser x = new User(NAME, FIRSTNAME); IUser y = new User(NAME, FIRSTNAME); assertEquals(x.hashCode(), y.hashCode()); x.setId(42); assertTrue(x.hashCode() != y.hashCode()); y.setId(42); assertEquals(x.hashCode(), y.hashCode()); }
### Question: RegularPriceCategory extends PriceCategory { @Override public double getCharge(int daysRented) { double result = 0; if (daysRented > 0) { result = 2; } if (daysRented > 2) { result = 2 + (daysRented - 2) * 1.5; } return result; } private RegularPriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override String toString(); static RegularPriceCategory getInstance(); }### Answer: @Test public void testGetCharge() { assertEquals(0.0d, rpc.getCharge(-3), tolerance); assertEquals(0.0d, rpc.getCharge(0), tolerance); assertEquals(2.0d, rpc.getCharge(1), tolerance); assertEquals(2.0d, rpc.getCharge(2), tolerance); assertEquals(3.5d, rpc.getCharge(3), tolerance); assertEquals(5.0d, rpc.getCharge(4), tolerance); assertEquals(32.0d, rpc.getCharge(22), tolerance); }
### Question: RegularPriceCategory extends PriceCategory { @Override public String toString() { return "Regular"; } private RegularPriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override String toString(); static RegularPriceCategory getInstance(); }### Answer: @Test public void testToString() { assertEquals("Regular", rpc.toString()); }
### Question: Movie { @Override public int hashCode() { final int prime = 31; int result = prime + id; result = prime * result + ((releaseDate == null) ? 0 : releaseDate.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } protected Movie(); Movie(String aTitle, PriceCategory aPriceCategory); Movie(String aTitle, Date aReleaseDate, PriceCategory aPriceCategory); PriceCategory getPriceCategory(); void setPriceCategory(PriceCategory aPriceCategory); String getTitle(); void setTitle(String aTitle); Date getReleaseDate(); void setReleaseDate(Date aReleaseDate); boolean isRented(); void setRented(boolean isRented); int getId(); void setId(int anId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testHashCode() throws InterruptedException { Date d = new Date(Calendar.getInstance().getTimeInMillis()); PriceCategory pc = RegularPriceCategory.getInstance(); Movie x = new Movie(); Movie y = new Movie("A", d, pc); Movie z = new Movie("A", d, pc); int h = x.hashCode(); assertEquals(h, x.hashCode()); h = y.hashCode(); assertEquals(h, y.hashCode()); h = y.hashCode(); assertEquals(h, z.hashCode()); z.setRented(true); assertEquals(h, z.hashCode()); z = new Movie("A", d, pc); z.setPriceCategory(ChildrenPriceCategory.getInstance()); assertEquals(h, z.hashCode()); z = new Movie("B", d, pc); assertFalse(h == z.hashCode()); Thread.sleep(10); z = new Movie("A", new Date(Calendar.getInstance().getTimeInMillis()), pc); assertFalse(h == z.hashCode()); z = new Movie("A", d, pc); z.setId(42); assertFalse(h == z.hashCode()); }
### Question: Movie { protected Movie() { } protected Movie(); Movie(String aTitle, PriceCategory aPriceCategory); Movie(String aTitle, Date aReleaseDate, PriceCategory aPriceCategory); PriceCategory getPriceCategory(); void setPriceCategory(PriceCategory aPriceCategory); String getTitle(); void setTitle(String aTitle); Date getReleaseDate(); void setReleaseDate(Date aReleaseDate); boolean isRented(); void setRented(boolean isRented); int getId(); void setId(int anId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testMovie() { Movie m = new Movie(); assertNull(m.getPriceCategory()); assertNull(m.getReleaseDate()); assertNull(m.getTitle()); assertFalse(m.isRented()); }
### Question: Movie { public void setTitle(String aTitle) { if (this.title != null) { throw new IllegalStateException(); } this.title = aTitle; } protected Movie(); Movie(String aTitle, PriceCategory aPriceCategory); Movie(String aTitle, Date aReleaseDate, PriceCategory aPriceCategory); PriceCategory getPriceCategory(); void setPriceCategory(PriceCategory aPriceCategory); String getTitle(); void setTitle(String aTitle); Date getReleaseDate(); void setReleaseDate(Date aReleaseDate); boolean isRented(); void setRented(boolean isRented); int getId(); void setId(int anId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test(expected = IllegalStateException.class) public void testSetTitle() { Movie m = new Movie(); m.setTitle("Hallo"); assertEquals("Hallo", m.getTitle()); m.setTitle(null); }
### Question: Movie { public void setReleaseDate(Date aReleaseDate) { if (this.releaseDate != null) { throw new IllegalStateException(); } this.releaseDate = aReleaseDate; } protected Movie(); Movie(String aTitle, PriceCategory aPriceCategory); Movie(String aTitle, Date aReleaseDate, PriceCategory aPriceCategory); PriceCategory getPriceCategory(); void setPriceCategory(PriceCategory aPriceCategory); String getTitle(); void setTitle(String aTitle); Date getReleaseDate(); void setReleaseDate(Date aReleaseDate); boolean isRented(); void setRented(boolean isRented); int getId(); void setId(int anId); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test(expected = IllegalStateException.class) public void testSetReleaseDate() { Movie m = new Movie(); Date d = new Date(Calendar.getInstance().getTimeInMillis()); m.setReleaseDate(d); assertEquals(d, m.getReleaseDate()); m.setReleaseDate(null); }
### Question: ChildrenPriceCategory extends PriceCategory { @Override public double getCharge(int daysRented) { double result = 0; if (daysRented > 0) { result = 1.5; if (daysRented > 3) { result += (daysRented - 3) * 1.5; } } return result; } private ChildrenPriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override String toString(); static ChildrenPriceCategory getInstance(); }### Answer: @Test public void testGetCharge() { assertEquals(0.0D, cpc.getCharge(-5), 1.0e-10); assertEquals(0.0, cpc.getCharge(0), 1.0e-10); assertEquals(1.5D, cpc.getCharge(1), 1.0e-10); assertEquals(1.5D, cpc.getCharge(2), 1.0e-10); assertEquals(1.5D, cpc.getCharge(3), 1.0e-10); assertEquals(3.0D, cpc.getCharge(4), 1.0e-10); assertEquals(151.5D, cpc.getCharge(103), 1.0e-10); }
### Question: ChildrenPriceCategory extends PriceCategory { @Override public String toString() { return "Children"; } private ChildrenPriceCategory(); int getId(); @Override double getCharge(int daysRented); @Override String toString(); static ChildrenPriceCategory getInstance(); }### Answer: @Test public void testToString() { assertEquals("Children", cpc.toString()); }
### Question: PriceCategory { public int getFrequentRenterPoints(int daysRented) { return daysRented > 0 ? 1 : 0; } int getId(); abstract double getCharge(int daysRented); int getFrequentRenterPoints(int daysRented); }### Answer: @Test public void testGetFrequentRenterPoints() { assertEquals(0, pc.getFrequentRenterPoints(-6)); assertEquals(0, pc.getFrequentRenterPoints(0)); assertEquals(1, pc.getFrequentRenterPoints(1)); assertEquals(1, pc.getFrequentRenterPoints(2)); assertEquals(1, pc.getFrequentRenterPoints(4000)); }
### Question: Part04HandlingErrors { public Flux<Integer> errorIsTerminal(Flux<String> numbers) { return numbers.map(s -> Integer.parseInt(s)).log(); } Flux<Integer> errorIsTerminal(Flux<String> numbers); Flux<Integer> handleErrorWithFallback(Flux<String> numbers); Flux<Integer> handleErrorAndContinue(Flux<String> numbers); Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers); Flux<String> timeOutWithRetry(Flux<String> colors); Mono<String> simulateRemoteCall(String input); }### Answer: @Test public void errorIsTerminal() { Flux<String> flux = Flux.just("31", "12", "2", "A", "5", "6"); Flux<Integer> numbers = workshop.errorIsTerminal(flux); StepVerifier.create(numbers).expectNext(31, 12, 2).expectError().verify(); }
### Question: Part04HandlingErrors { public Flux<Integer> handleErrorWithFallback(Flux<String> numbers) { return numbers.map(s -> Integer.parseInt(s)) .onErrorReturn(NumberFormatException.class, 0) .log(); } Flux<Integer> errorIsTerminal(Flux<String> numbers); Flux<Integer> handleErrorWithFallback(Flux<String> numbers); Flux<Integer> handleErrorAndContinue(Flux<String> numbers); Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers); Flux<String> timeOutWithRetry(Flux<String> colors); Mono<String> simulateRemoteCall(String input); }### Answer: @Test public void handleErrorWithFallback() { Flux<String> flux = Flux.just("31", "12", "2", "A", "5", "6"); Flux<Integer> numbers = workshop.handleErrorWithFallback(flux); StepVerifier.create(numbers).expectNext(31, 12, 2, 0).expectComplete().verify(); }
### Question: Part04HandlingErrors { public Flux<Integer> handleErrorAndContinue(Flux<String> numbers) { return numbers.flatMap(s -> Mono.just(s).map(Integer::parseInt) .onErrorReturn(NumberFormatException.class, 0).log()); } Flux<Integer> errorIsTerminal(Flux<String> numbers); Flux<Integer> handleErrorWithFallback(Flux<String> numbers); Flux<Integer> handleErrorAndContinue(Flux<String> numbers); Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers); Flux<String> timeOutWithRetry(Flux<String> colors); Mono<String> simulateRemoteCall(String input); }### Answer: @Test public void handleErrorAndContinue() { Flux<String> flux = Flux.just("31", "12", "2", "A", "5", "6"); Flux<Integer> numbers = workshop.handleErrorAndContinue(flux); StepVerifier.create(numbers).expectNext(31, 12, 2, 0, 5, 6).expectComplete().verify(); }
### Question: Part04HandlingErrors { public Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers) { return numbers.flatMap(s -> Mono.just(s).map(Integer::parseInt) .onErrorResume(throwable -> Mono.empty())).log(); } Flux<Integer> errorIsTerminal(Flux<String> numbers); Flux<Integer> handleErrorWithFallback(Flux<String> numbers); Flux<Integer> handleErrorAndContinue(Flux<String> numbers); Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers); Flux<String> timeOutWithRetry(Flux<String> colors); Mono<String> simulateRemoteCall(String input); }### Answer: @Test public void handleErrorWithEmptyMonoAndContinue() { Flux<String> flux = Flux.just("31", "12", "2", "A", "5", "6"); Flux<Integer> numbers = workshop.handleErrorWithEmptyMonoAndContinue(flux); StepVerifier.create(numbers).expectNext(31, 12, 2, 5, 6).expectComplete().verify(); }
### Question: Part04HandlingErrors { public Flux<String> timeOutWithRetry(Flux<String> colors) { return colors.concatMap(color -> simulateRemoteCall(color) .timeout(Duration.ofMillis(400)) .doOnError(s -> log.info(s.getMessage())) .retry(2).onErrorReturn("default")).log(); } Flux<Integer> errorIsTerminal(Flux<String> numbers); Flux<Integer> handleErrorWithFallback(Flux<String> numbers); Flux<Integer> handleErrorAndContinue(Flux<String> numbers); Flux<Integer> handleErrorWithEmptyMonoAndContinue(Flux<String> numbers); Flux<String> timeOutWithRetry(Flux<String> colors); Mono<String> simulateRemoteCall(String input); }### Answer: @Test public void timeOutWithRetry() { Flux<String> colors = Flux.just("red", "black", "tan"); Flux<String> results = workshop.timeOutWithRetry(colors); StepVerifier.create(results).expectNext("processed red", "default", "processed tan").verifyComplete(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeEmpty() { Flux<Integer> flux = Flux.just(1, 2, 3); flux.log().subscribe(); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeEmpty() { Flux<Integer> flux = workshop.subscribeEmpty(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyComplete(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeWithConsumer() { Flux<Integer> flux = Flux.just(1, 2, 3); flux.log().subscribe(integer -> log.info("{}", integer)); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeWithConsumer() { Flux<Integer> flux = workshop.subscribeWithConsumer(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyComplete(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeWithConsumerAndCompleteConsumer() { Flux<Integer> flux = Flux.just(1, 2, 3); flux.subscribe(integer -> log.info("{}", integer), null, () -> log.info("completed")); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeWithConsumerAndCompleteConsumer() { Flux<Integer> flux = workshop.subscribeWithConsumerAndCompleteConsumer(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyComplete(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeWithConsumerAndErrorConsumer() { Flux<Integer> flux = Flux.just(1, 2, 3, 4).map(i -> { if (i != 4) { return i; } else { throw new IllegalStateException("error"); } }); flux.log().subscribe(integer -> log.info("{}", integer), throwable -> log.info("{}", throwable.getMessage())); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeWithConsumerAndErrorConsumer() { Flux<Integer> flux = workshop.subscribeWithConsumerAndErrorConsumer(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyError(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeWithSubscriptionConsumer() { Flux<Integer> flux = Flux.just(1, 2, 3); flux.log().subscribe(null, null, null, new Consumer<Subscription>() { @Override public void accept(Subscription subscription) { subscription.request(2); } }); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeWithSubscriptionConsumer() { Flux<Integer> flux = workshop.subscribeWithSubscriptionConsumer(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyComplete(); }
### Question: Part05Subscribe { public Flux<Integer> subscribeWithSubscription() { Flux<Integer> flux = Flux.just(1, 2, 3); flux.log().subscribe(new Subscriber<Integer>() { Subscription s; @Override public void onSubscribe(Subscription s) { this.s = s; s.request(1); } @Override public void onNext(Integer integer) { s.request(integer); } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); return flux; } Flux<Integer> subscribeEmpty(); Flux<Integer> subscribeWithConsumer(); Flux<Integer> subscribeWithConsumerAndCompleteConsumer(); Flux<Integer> subscribeWithConsumerAndErrorConsumer(); Flux<Integer> subscribeWithSubscriptionConsumer(); Flux<Integer> subscribeWithSubscription(); }### Answer: @Test public void subscribeWithSubscription() { Flux<Integer> flux = workshop.subscribeWithSubscription(); StepVerifier.create(flux) .expectNext(1, 2, 3).verifyComplete(); }
### Question: Part02Transform { Flux<Integer> transformToLength(Flux<String> flux) { return flux.map(s -> s.length()); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void transform() { Flux<Integer> flux = workshop.transformToLength(Flux.just("foo", "bar")); StepVerifier.create(flux).expectNext(3, 3).verifyComplete(); }
### Question: Part02Transform { Flux<String> characters(Flux<String> flux) { return flux .map(s -> s.toUpperCase()) .flatMap(s -> Flux.fromArray(s.split("")).log()); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void characters() { Flux<String> flux = workshop.characters(Flux.just("foo", "bar")); StepVerifier.create(flux).expectNextCount(6).verifyComplete(); }
### Question: Part02Transform { Flux<String> combineInEmissionOrder(Flux<String> flux1, Flux<String> flux2) { return Flux.merge(flux1, flux2); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void combineInEmissionOrder() { Flux<String> flux1 = Flux.just("foo", "bar").delayElements(Duration.ofMillis(1)); Flux<String> flux2 = Flux.just("a", "b", "c").delayElements(Duration.ofMillis(1)); StepVerifier.create(workshop.combineInEmissionOrder(flux1, flux2)).expectNextCount(5).verifyComplete(); }
### Question: Part02Transform { public Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2) { return Flux.zip(flux1, flux2); } Flux<Tuple2<String, Integer>> pairValues(Flux<String> flux1, Flux<Integer> flux2); Mono<Order> combineValues(Mono<String> phoneNumber, Mono<String> deliveryAddress); }### Answer: @Test public void pairValues() { Flux<String> flux1 = Flux.just("a", "b", "c"); Flux<Integer> flux2 = Flux.just(1, 2, 3, 4); StepVerifier.create(workshop.pairValues(flux1, flux2)) .assertNext(tuple2 -> { assertThat(tuple2.getT1()).isEqualTo("a"); assertThat(tuple2.getT2()).isEqualTo(1); }) .assertNext(tuple2 -> { assertThat(tuple2.getT1()).isEqualTo("b"); assertThat(tuple2.getT2()).isEqualTo(2); }) .assertNext(tuple2 -> { assertThat(tuple2.getT1()).isEqualTo("c"); assertThat(tuple2.getT2()).isEqualTo(3); }) .verifyComplete(); }
### Question: PRNGSeedFactoryBean implements FactoryBean<Integer> { @Override public Integer getObject() { try { int time = new java.util.Date().hashCode(); int ipAddress = InetAddress.getLocalHost().hashCode(); int rand = metaPrng.nextInt(); int seed = (ipAddress & 0xffff) | ((time & 0x00ff) << 32) | (rand & 0x0f000000); logger.info("seed = " + seed); return seed; } catch (UnknownHostException e) { throw new RuntimeException(e); } } @Override Integer getObject(); @Override Class<?> getObjectType(); @Override boolean isSingleton(); }### Answer: @Test public void test() { for(int i=0; i<10; i++) { Integer result = bean.getObject(); System.out.println(result); } }
### Question: RationalNumber { public void optimize() { int gcd = calcGcd(numerator, denominator); this.numerator = this.numerator / gcd; this.denominator = this.denominator / gcd; } RationalNumber(int numerator, int denominator); static RationalNumber create(int numerator, int denominator); int getNumerator(); int getDenominator(); void optimize(); String toString(); boolean equals(Object obj); int hashCode(); }### Answer: @Test public void optimizeTest() throws Exception { RationalNumber actual = RationalNumber.create(15, 9); actual.optimize(); RationalNumber expected = RationalNumber.create(5, 3); Assert.assertEquals(expected, actual); }
### Question: RationalNumber { public static RationalNumber create(int numerator, int denominator) { return new RationalNumber(numerator, denominator); } RationalNumber(int numerator, int denominator); static RationalNumber create(int numerator, int denominator); int getNumerator(); int getDenominator(); void optimize(); String toString(); boolean equals(Object obj); int hashCode(); }### Answer: @Test public void createTest() throws Exception { RationalNumber actual = RationalNumber.create(15, 9); RationalNumber expected = new RationalNumber(15, 9); Assert.assertEquals(expected, actual); } @Test(expected = ArithmeticException.class) public void createTestOnBadData() throws Exception { RationalNumber.create(15, 0); }
### Question: HumansJdbcTemplateDaoImpl implements HumansDao { @Override public Human find(int id) { try { return template.queryForObject(SQL_SELECT_USER_BY_ID, humanRowMapper, id); } catch (EmptyResultDataAccessException e) { throw new IllegalArgumentException("User with id <" + id + "> not found"); } } HumansJdbcTemplateDaoImpl(DataSource dataSource); @Override List<Human> findAllByAge(int age); @Override void save(Human model); @Override Human find(int id); @Override void update(Human model); @Override void delete(int id); @Override List<Human> findAll(); }### Answer: @Test public void findTest() throws Exception { Human expected = Human.builder() .id(2) .age(19) .name("Андрей") .citizen("Россия") .build(); Human actual = testedHumansDao.find(2); Assert.assertEquals(expected, actual); } @Test(expected = IllegalArgumentException.class) public void findTestOnBadUserId() { testedHumansDao.find(44); }
### Question: Validator { @VisibleForTesting void validateExactlyOnceSelect(SqlNodeList query) { Preconditions.checkArgument(query.size() > 0); SqlNode last = query.get(query.size() - 1); long n = StreamSupport.stream(query.spliterator(), false) .filter(x -> x instanceof SqlSelect) .count(); Preconditions.checkArgument(n == 1 && last instanceof SqlSelect, "Only one top-level SELECT statement is allowed"); statement = (SqlSelect) last; } }### Answer: @Test(expected = IllegalArgumentException.class) public void testMultiSqlInsert() throws IOException, ParseException { String sql = Joiner.on(";\n").join( "INSERT INTO foo (SELECT * FROM bar)", "INSERT INTO foo (SELECT * FROM bar)" ); SqlNodeList nodes = Planner.parse(sql); Validator validator = new Validator(); validator.validateExactlyOnceSelect(nodes); } @Test public void testWrapSelectIntoInsert() throws IOException, ParseException { String sql = Joiner.on(";\n").join( "SET foo = 1", "SELECT * FROM bar" ); SqlNodeList nodes = Planner.parse(sql); Validator validator = new Validator(); validator.validateExactlyOnceSelect(nodes); }
### Question: JobDeployer { void start(JobGraph job, JobConf desc) throws Exception { AthenaXYarnClusterDescriptor descriptor = new AthenaXYarnClusterDescriptor(clusterConf, yarnClient, flinkConf, desc); start(descriptor, job); } JobDeployer(YarnClusterConfiguration clusterConf, YarnClient yarnClient, ScheduledExecutorService executor, Configuration flinkConf); }### Answer: @Test public void testDeployerWithIsolatedConfiguration() throws Exception { YarnClusterConfiguration clusterConf = mock(YarnClusterConfiguration.class); doReturn(new YarnConfiguration()).when(clusterConf).conf(); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); Configuration flinkConf = new Configuration(); YarnClient client = mock(YarnClient.class); JobDeployer deploy = new JobDeployer(clusterConf, client, executor, flinkConf); AthenaXYarnClusterDescriptor desc = mock(AthenaXYarnClusterDescriptor.class); YarnClusterClient clusterClient = mock(YarnClusterClient.class); doReturn(clusterClient).when(desc).deploy(); ActorGateway actorGateway = mock(ActorGateway.class); doReturn(actorGateway).when(clusterClient).getJobManagerGateway(); doReturn(Future$.MODULE$.successful(null)).when(actorGateway).ask(any(), any()); JobGraph jobGraph = mock(JobGraph.class); doReturn(JobID.generate()).when(jobGraph).getJobID(); deploy.start(desc, jobGraph); verify(clusterClient).runDetached(jobGraph, null); }
### Question: Validator { @VisibleForTesting void extract(SqlNodeList query) { for (SqlNode n : query) { if (n instanceof SqlSetOption) { extract((SqlSetOption) n); } else if (n instanceof SqlCreateFunction) { extract((SqlCreateFunction) n); } } } }### Answer: @Test(expected = IllegalArgumentException.class) public void testInvalidSetSystemProperties() throws IOException, ParseException { String sql = "ALTER SYSTEM SET bar = OFF"; SqlNodeList nodes = Planner.parse(sql); Validator validator = new Validator(); validator.extract(nodes); }
### Question: Planner { @VisibleForTesting static SqlNodeList parse(String sql) throws ParseException { try (StringReader in = new StringReader(sql)) { SqlParserImpl impl = new SqlParserImpl(in); impl.switchTo("BTID"); impl.setTabSize(1); impl.setQuotedCasing(Lex.JAVA.quotedCasing); impl.setUnquotedCasing(Lex.JAVA.unquotedCasing); impl.setIdentifierMaxLength(DEFAULT_IDENTIFIER_MAX_LENGTH); return impl.SqlStmtsEof(); } } Planner(Map<String, AthenaXTableCatalog> inputs, AthenaXTableCatalog outputs); JobCompilationResult sql(String sql, int parallelism); }### Answer: @Test public void testCreateFunction() throws Exception { String sql = "CREATE FUNCTION foo AS 'com.uber.foo';"; Planner.parse(sql); sql = "CREATE FUNCTION foo AS 'com.uber.foo' USING JAR 'mock: Planner.parse(sql); } @Test public void testSetOption() throws Exception { String sql = "SET flink.enable.checkpoint=1;"; Planner.parse(sql); } @Test public void testMultipleStatement() throws Exception { String sql = "SET flink.enable.checkpoint=1;"; SqlNodeList list = Planner.parse(sql); assertEquals(1, list.size()); sql = "SET flink.enable.checkpoint=1;\n" + "SELECT * FROM foo"; list = Planner.parse(sql); assertEquals(2, list.size()); sql = "SET flink.enable.checkpoint=1;\n" + "SELECT * FROM foo;"; list = Planner.parse(sql); assertEquals(2, list.size()); }
### Question: KafkaUtils { static Properties getSubProperties(Map<String, String> prop, String prefix) { Properties p = new Properties(); for (Map.Entry<String, String> e : prop.entrySet()) { String key = e.getKey(); if (key.startsWith(prefix)) { p.put(key.substring(prefix.length()), e.getValue()); } } return p; } private KafkaUtils(); }### Answer: @Test public void testGetSubProperties() { Map<String, String> parent = Collections.singletonMap("foo.bar", "1"); Properties children = KafkaUtils.getSubProperties(parent, "foo."); assertEquals(1, children.size()); assertEquals("1", children.getProperty("bar")); }
### Question: JobWatcherUtil { static StateView computeState(Map<UUID, JobDefinition> jobs, Map<UUID, InstanceInfo> instances) { HashMap<UUID, UUID> instanceToJob = new HashMap<>(); HashMap<UUID, List<InstanceInfo>> jobInstances = new HashMap<>(); for (Map.Entry<UUID, InstanceInfo> e : instances.entrySet()) { YarnApplicationState state = YarnApplicationState.valueOf(e.getValue().status().getState().toString()); if (!isInstanceAlive(state)) { continue; } UUID jobId = e.getValue().metadata().jobDefinition(); UUID instanceId = e.getKey(); instanceToJob.put(instanceId, jobId); if (!jobInstances.containsKey(jobId)) { jobInstances.put(jobId, new ArrayList<>()); } jobInstances.get(jobId).add(e.getValue()); } jobs.keySet().stream().filter(x -> !jobInstances.containsKey(x)) .forEach(x -> jobInstances.put(x, Collections.emptyList())); return new StateView(jobs, instances, instanceToJob, jobInstances); } private JobWatcherUtil(); }### Answer: @Test public void testComputeState() { HashMap<UUID, JobDefinition> jobMap = new HashMap<>(); HashMap<UUID, InstanceInfo> instanceMap = new HashMap<>(); mockState1(jobMap, instanceMap); JobWatcherUtil.StateView v = JobWatcherUtil.computeState(jobMap, instanceMap); HashMap<UUID, List<InstanceInfo>> jobInstances = new HashMap<>(); HashMap<UUID, UUID> instanceToJob = new HashMap<>(); for (Map.Entry<UUID, InstanceInfo> e : instanceMap.entrySet()) { UUID jobId = e.getValue().metadata().jobDefinition(); instanceToJob.put(e.getKey(), jobId); List<InstanceInfo> li = jobInstances.getOrDefault(jobId, new ArrayList<>()); li.add(e.getValue()); jobInstances.put(jobId, li); } assertEquals(jobMap, v.jobs()); assertEquals(instanceMap, v.instances()); assertEquals(instanceToJob, v.instanceToJob()); assertEquals(jobInstances, v.jobInstances()); }
### Question: Base { public static Long count(String table) { return new DB(DB.DEFAULT_NAME).count(table); } private Base(); static DB open(); static DB open(String driver, String url, String user, String password); static DB open(String driver, String url, Properties props); static DB open(String jndiName); static DB open(String jndiName, Properties jndiProperties); static DB open(DataSource dataSource); static Connection connection(); static boolean hasConnection(); static void close(boolean suppressWarning); static void close(); static Long count(String table); static Long count(String table, String query, Object... params); static Object firstCell(String query, Object... params); static List<Map> findAll(String query, Object... params); static List firstColumn(String query, Object... params); static List<Map> findAll(String query); static RowProcessor find(String query, Object ... params); static RowProcessor find(RowProcessor.ResultSetType type, RowProcessor.ResultSetConcur concur, int fetchSize, String query, Object ... params); static void find(String sql, RowListener listener); static int exec(String query); static int exec(String query, Object ... params); static void openTransaction(); static void commitTransaction(); static void rollbackTransaction(); static PreparedStatement startBatch(String parametrizedStatement); static void addBatch(PreparedStatement ps, Object... parameters); static int[] executeBatch(PreparedStatement ps); static void closePreparedStatement(PreparedStatement ps); static void attach(Connection connection); static Connection detach(); static T withDb(String jndiName, Properties jndiProperties, Supplier<T> supplier); static T withDb(DataSource dataSource, Supplier<T> supplier); static T withDb(String jndiName, Supplier<T> supplier); static T withDb(String driver, String url, Properties properties, Supplier<T> supplier); static T withDb(String driver, String url, String user, String password, Supplier<T> supplier); static T withDb(Supplier<T> supplier); }### Answer: @Test public void testCount(){ a(Base.count("people")).shouldBeEqual(4); }
### Question: DefaultDialect implements Dialect { @Override public String selectStar(String table) { return "SELECT * FROM " + table; } @Override String selectStar(String table); @Override String selectStar(String table, String where); @Override String selectStarParametrized(String table, String ... parameters); @Override String formSelect(String tableName, String[] columns, String subQuery, List<String> orderBys, long limit, long offset); @Override Object overrideDriverTypeConversion(MetaModel mm, String attributeName, Object value); @Override String selectCount(String from); @Override String selectCount(String table, String where); @Override String selectExists(MetaModel metaModel); @Override String selectManyToManyAssociation(Many2ManyAssociation association, String sourceFkColumnName, int questionsCount); @Override String insertManyToManyAssociation(Many2ManyAssociation association); @Override String insertParametrized(MetaModel metaModel, List<String> columns, boolean containsId); @Override String deleteManyToManyAssociation(Many2ManyAssociation association); @Override String insert(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); @Override String update(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); }### Answer: @Test public void testSelectStar() { a(dialect.selectStar("people")).shouldBeEqual("SELECT * FROM people"); } @Test public void testSelectStarWithQuery() { a(dialect.selectStar("people", "name = ?")).shouldBeEqual("SELECT * FROM people WHERE name = ?"); }
### Question: DefaultDialect implements Dialect { @Override public String selectStarParametrized(String table, String ... parameters) { StringBuilder sql = new StringBuilder().append("SELECT * FROM ").append(table).append(" WHERE "); join(sql, parameters, " = ? AND "); sql.append(" = ?"); return sql.toString(); } @Override String selectStar(String table); @Override String selectStar(String table, String where); @Override String selectStarParametrized(String table, String ... parameters); @Override String formSelect(String tableName, String[] columns, String subQuery, List<String> orderBys, long limit, long offset); @Override Object overrideDriverTypeConversion(MetaModel mm, String attributeName, Object value); @Override String selectCount(String from); @Override String selectCount(String table, String where); @Override String selectExists(MetaModel metaModel); @Override String selectManyToManyAssociation(Many2ManyAssociation association, String sourceFkColumnName, int questionsCount); @Override String insertManyToManyAssociation(Many2ManyAssociation association); @Override String insertParametrized(MetaModel metaModel, List<String> columns, boolean containsId); @Override String deleteManyToManyAssociation(Many2ManyAssociation association); @Override String insert(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); @Override String update(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); }### Answer: @Test public void testSelectStarParametrized() { a(dialect.selectStarParametrized("people", "name")).shouldBeEqual("SELECT * FROM people WHERE name = ?"); a(dialect.selectStarParametrized("people", "name", "last_name")).shouldBeEqual( "SELECT * FROM people WHERE name = ? AND last_name = ?"); }
### Question: DefaultDialect implements Dialect { @Override public String deleteManyToManyAssociation(Many2ManyAssociation association) { return "DELETE FROM " + association.getJoin() + " WHERE " + association.getSourceFkName() + " = ? AND " + association.getTargetFkName() + " = ?"; } @Override String selectStar(String table); @Override String selectStar(String table, String where); @Override String selectStarParametrized(String table, String ... parameters); @Override String formSelect(String tableName, String[] columns, String subQuery, List<String> orderBys, long limit, long offset); @Override Object overrideDriverTypeConversion(MetaModel mm, String attributeName, Object value); @Override String selectCount(String from); @Override String selectCount(String table, String where); @Override String selectExists(MetaModel metaModel); @Override String selectManyToManyAssociation(Many2ManyAssociation association, String sourceFkColumnName, int questionsCount); @Override String insertManyToManyAssociation(Many2ManyAssociation association); @Override String insertParametrized(MetaModel metaModel, List<String> columns, boolean containsId); @Override String deleteManyToManyAssociation(Many2ManyAssociation association); @Override String insert(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); @Override String update(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); }### Answer: @Test public void testDeleteManyToManyAssociation() { String expectedQuery = "DELETE FROM issue_assignments " + "WHERE assignment_id = ? AND programmer_id = ?"; Many2ManyAssociation association = new Many2ManyAssociation( Programmer.class, Assignment.class, "issue_assignments", "assignment_id", "programmer_id"); String query = dialect.deleteManyToManyAssociation(association); a(query).shouldBeEqual(expectedQuery); }
### Question: DefaultDialect implements Dialect { @Override public String selectExists(MetaModel metaModel) { return "SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() + " WHERE " + metaModel.getIdName() + " = ?"; } @Override String selectStar(String table); @Override String selectStar(String table, String where); @Override String selectStarParametrized(String table, String ... parameters); @Override String formSelect(String tableName, String[] columns, String subQuery, List<String> orderBys, long limit, long offset); @Override Object overrideDriverTypeConversion(MetaModel mm, String attributeName, Object value); @Override String selectCount(String from); @Override String selectCount(String table, String where); @Override String selectExists(MetaModel metaModel); @Override String selectManyToManyAssociation(Many2ManyAssociation association, String sourceFkColumnName, int questionsCount); @Override String insertManyToManyAssociation(Many2ManyAssociation association); @Override String insertParametrized(MetaModel metaModel, List<String> columns, boolean containsId); @Override String deleteManyToManyAssociation(Many2ManyAssociation association); @Override String insert(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); @Override String update(MetaModel metaModel, Map<String, Object> attributes, String ... replacements); }### Answer: @Test public void testSelectExist() { a(dialect.selectExists( Person.getMetaModel())) .shouldBeEqual("SELECT id FROM people WHERE id = ?"); }
### Question: LazyList extends AbstractLazyList<T> implements Externalizable { public String toSql() { return toSql(true); } protected LazyList(String subQuery, MetaModel metaModel, Object... params); protected LazyList(boolean forPaginator, MetaModel metaModel, String fullQuery, Object... params); protected LazyList(); LazyList<E> limit(long limit); LazyList<E> offset(long offset); LazyList<E> orderBy(String orderBy); LazyList<E> include(Class<? extends Model>... classes); List<Map<String, Object>> toMaps(); String toXml(boolean pretty, boolean declaration, String... attrs); String toJson(boolean pretty, String ... attrs); LazyList<E> load(); String toSql(); String toSql(boolean showParameters); List collect(String attributeName); Set collectDistinct(String attributeName); List collect(String attributeName, String filterAttribute, Object filterValue); Set collectDistinct(String attributeName, String filterAttribute, Object filterValue); void dump(); void dump(OutputStream out); @Override void writeExternal(ObjectOutput out); @Override @SuppressWarnings("unchecked") void readExternal(ObjectInput in); }### Answer: @Test public void shouldGenerateSqlWithParameters() { a(Person.where("name = ? AND last_name = ?", "John", "Doe").toSql(true) .endsWith(", with parameters: John, Doe")).shouldBeTrue(); }
### Question: Escape { public static void html(StringBuilder sb, String html) { for (int i = 0; i < html.length(); i++) { char c = html.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; default: sb.append(c); } } } private Escape(); static void html(StringBuilder sb, String html); static String html(String html); static void xml(StringBuilder sb, String xml); static String xml(String xml); }### Answer: @Test public void shouldEscapeBasicHTML(){ the(Escape.html("<script>alert(\"This & that, it's the problem.\");</script>")).shouldBeEqual( "&lt;script&gt;alert(&quot;This &amp; that, it&apos;s the problem.&quot;);&lt;/script&gt;"); } @Test public void shouldNotEscapeHighUnicode() { String unicode = "\u30D5\u30EC\u30FC\u30E0\u30EF\u30FC\u30AF\u306E\u30D9\u30F3\u30C1\u30DE\u30FC\u30AF"; the(Escape.html(unicode)).shouldBeEqual(unicode); }
### Question: Collections { public static <K, V> Map<K, V> map(Object... keysAndValues) { if (keysAndValues.length % 2 != 0) { throw new IllegalArgumentException("number of arguments must be even"); } Map<K, V> map = new HashMap<K, V>(Math.max(keysAndValues.length, 16)); for (int i = 0; i < keysAndValues.length;) { map.put((K) keysAndValues[i++], (V) keysAndValues[i++]); } return map; } private Collections(); static T[] arr(T... values); static T[] array(T... values); static Set<T> set(T... values); static Map<K, V> map(Object... keysAndValues); static List<T> li(T... values); static List<T> list(T... values); }### Answer: @Test(expected = IllegalArgumentException.class) public void shouldRejectOddNumberOfArguments(){ Collections.map("hi"); } @Test public void shouldCreateProperMap(){ Map<String, Object> person = Collections.map("name", "James", "last_name", "Belushi"); a(person.get("name")).shouldBeEqual("James"); a(person.get("last_name")).shouldBeEqual("Belushi"); }
### Question: Collections { public static <T> T[] array(T... values) { return values; } private Collections(); static T[] arr(T... values); static T[] array(T... values); static Set<T> set(T... values); static Map<K, V> map(Object... keysAndValues); static List<T> li(T... values); static List<T> list(T... values); }### Answer: @Test public void shouldCreateArray(){ String[] ar = Collections.array("John", "James", "Mary", "Keith"); a(ar.length).shouldBeEqual(4); a(ar[0]).shouldBeEqual("John"); a(ar[1]).shouldBeEqual("James"); a(ar[2]).shouldBeEqual("Mary"); a(ar[3]).shouldBeEqual("Keith"); }
### Question: Collections { public static <T> List<T> list(T... values) { return new ArrayList<T>(Arrays.asList(values)); } private Collections(); static T[] arr(T... values); static T[] array(T... values); static Set<T> set(T... values); static Map<K, V> map(Object... keysAndValues); static List<T> li(T... values); static List<T> list(T... values); }### Answer: @Test public void shouldCreateList(){ List<String> list = Collections.list("John", "James", "Mary", "Keith"); list.add("hello"); a(list.size()).shouldBeEqual(5); a(list.get(0)).shouldBeEqual("John"); a(list.get(1)).shouldBeEqual("James"); a(list.get(2)).shouldBeEqual("Mary"); a(list.get(3)).shouldBeEqual("Keith"); }
### Question: Util { public static String read(InputStream in) throws IOException { return read(in, "UTF-8"); } private Util(); static byte[] readResourceBytes(String resourceName); static String readResource(String resourceName); static String readResource(String resourceName, String charset); static String readFile(String fileName); static String readFile(String fileName, String charset); static void closeQuietly(AutoCloseable autoCloseable); static void closeQuietly(AutoCloseable ... autoCloseable); static void closeQuietly(List<T> autoCloseable); static String read(InputStream in); static String read(InputStream in, String charset); static byte[] bytes(InputStream in); static byte[] read(File file); static List<String> getResourceLines(String resourceName); static boolean blank(Object value); static boolean empty(Object[] array); static boolean empty(Collection<?> collection); static String join(String[] array, String delimiter); static String[] split(String input, String delimiters); static String[] split(String input, char delimiter); static String join(Collection<?> collection, String delimiter); static void join(StringBuilder sb, Collection<?> collection, String delimiter); static void join(StringBuilder sb, Object[] array, String delimiter); static void repeat(StringBuilder sb, String str, int count); static void joinAndRepeat(StringBuilder sb, String str, String delimiter, int count); static void saveTo(String path, InputStream in); static String getCauseMessage(Throwable throwable); static String getStackTraceString(Throwable throwable); static void saveTo(String path, byte[] content); static String toBase64(byte[] input); static byte[] fromBase64(String input); String[] arr(String ... params); static Properties readProperties(String fileOrResource); static boolean createTree(Path path); static void recursiveDelete(Path directory); }### Answer: @Test public void shouldReadUTF8() throws IOException { it(Util.read(getClass().getResourceAsStream("/test.txt"), "UTF-8")).shouldBeEqual("чебурашка"); it(Util.read(getClass().getResourceAsStream("/test.txt"))).shouldBeEqual("чебурашка"); }
### Question: Util { public static String readResource(String resourceName) { return readResource(resourceName, "UTF-8"); } private Util(); static byte[] readResourceBytes(String resourceName); static String readResource(String resourceName); static String readResource(String resourceName, String charset); static String readFile(String fileName); static String readFile(String fileName, String charset); static void closeQuietly(AutoCloseable autoCloseable); static void closeQuietly(AutoCloseable ... autoCloseable); static void closeQuietly(List<T> autoCloseable); static String read(InputStream in); static String read(InputStream in, String charset); static byte[] bytes(InputStream in); static byte[] read(File file); static List<String> getResourceLines(String resourceName); static boolean blank(Object value); static boolean empty(Object[] array); static boolean empty(Collection<?> collection); static String join(String[] array, String delimiter); static String[] split(String input, String delimiters); static String[] split(String input, char delimiter); static String join(Collection<?> collection, String delimiter); static void join(StringBuilder sb, Collection<?> collection, String delimiter); static void join(StringBuilder sb, Object[] array, String delimiter); static void repeat(StringBuilder sb, String str, int count); static void joinAndRepeat(StringBuilder sb, String str, String delimiter, int count); static void saveTo(String path, InputStream in); static String getCauseMessage(Throwable throwable); static String getStackTraceString(Throwable throwable); static void saveTo(String path, byte[] content); static String toBase64(byte[] input); static byte[] fromBase64(String input); String[] arr(String ... params); static Properties readProperties(String fileOrResource); static boolean createTree(Path path); static void recursiveDelete(Path directory); }### Answer: @Test public void shouldReadLargeUTF8() throws IOException { Util.readResource("/large.txt"); }
### Question: Convert { public static BigDecimal toBigDecimal(Object value) { if (value == null) { return null; } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else { try { return new BigDecimal(value.toString().trim()); } catch (NumberFormatException e) { throw new ConversionException("failed to convert: '" + value + "' to BigDecimal", e); } } } private Convert(); static String toString(Object value); static Boolean toBoolean(Object value); static java.sql.Date toSqlDate(Object value); static java.sql.Date truncateToSqlDate(Object value); static java.sql.Date truncateToSqlDate(long time); static String toIsoString(java.util.Date date); static Double toDouble(Object value); static java.sql.Time toTime(Object value); static java.sql.Timestamp toTimestamp(Object value); static Float toFloat(Object value); static Long toLong(Object value); static Integer toInteger(Object value); static BigDecimal toBigDecimal(Object value); static byte[] toBytes(Object value); static byte[] toBytes(Blob blob); static Short toShort(Object value); }### Answer: @Test public void shouldCovertToBigDecimal() { Object object = Convert.toBigDecimal(1); the(object).shouldBeA(BigDecimal.class); a(object).shouldBeEqual(1); object = Convert.toBigDecimal("1"); the(object).shouldBeA(BigDecimal.class); a(object).shouldBeEqual(1); object = Convert.toBigDecimal(1d); the(object).shouldBeA(BigDecimal.class); a(object).shouldBeEqual(1); object = Convert.toBigDecimal(1L); the(object).shouldBeA(BigDecimal.class); a(object).shouldBeEqual(1); }
### Question: Convert { public static Double toDouble(Object value) { if (value == null) { return null; } else if (value instanceof Double) { return (Double) value; } else if (value instanceof Number) { return ((Number) value).doubleValue(); } else { try { return Double.valueOf(value.toString().trim()); } catch (NumberFormatException e) { throw new ConversionException("failed to convert: '" + value + "' to Double", e); } } } private Convert(); static String toString(Object value); static Boolean toBoolean(Object value); static java.sql.Date toSqlDate(Object value); static java.sql.Date truncateToSqlDate(Object value); static java.sql.Date truncateToSqlDate(long time); static String toIsoString(java.util.Date date); static Double toDouble(Object value); static java.sql.Time toTime(Object value); static java.sql.Timestamp toTimestamp(Object value); static Float toFloat(Object value); static Long toLong(Object value); static Integer toInteger(Object value); static BigDecimal toBigDecimal(Object value); static byte[] toBytes(Object value); static byte[] toBytes(Blob blob); static Short toShort(Object value); }### Answer: @Test public void shouldCovertToDouble() { Object object = Convert.toDouble(1); the(object).shouldBeA(Double.class); a(object).shouldBeEqual(1); object = Convert.toDouble("1"); the(object).shouldBeA(Double.class); a(object).shouldBeEqual(1); object = Convert.toDouble(1L); the(object).shouldBeA(Double.class); a(object).shouldBeEqual(1); object = Convert.toDouble(new BigDecimal(1)); the(object).shouldBeA(Double.class); a(object).shouldBeEqual(1); }
### Question: Convert { public static Float toFloat(Object value) { if (value == null) { return null; } else if (value instanceof Float) { return (Float) value; } else if (value instanceof Number) { return ((Number) value).floatValue(); } else { return Float.valueOf(value.toString().trim()); } } private Convert(); static String toString(Object value); static Boolean toBoolean(Object value); static java.sql.Date toSqlDate(Object value); static java.sql.Date truncateToSqlDate(Object value); static java.sql.Date truncateToSqlDate(long time); static String toIsoString(java.util.Date date); static Double toDouble(Object value); static java.sql.Time toTime(Object value); static java.sql.Timestamp toTimestamp(Object value); static Float toFloat(Object value); static Long toLong(Object value); static Integer toInteger(Object value); static BigDecimal toBigDecimal(Object value); static byte[] toBytes(Object value); static byte[] toBytes(Blob blob); static Short toShort(Object value); }### Answer: @Test public void shouldCovertToFloat() { Object object = Convert.toFloat(1F); the(object).shouldBeA(Float.class); a(object).shouldBeEqual(1); object = Convert.toFloat("1"); the(object).shouldBeA(Float.class); a(object).shouldBeEqual(1); object = Convert.toFloat(1L); the(object).shouldBeA(Float.class); a(object).shouldBeEqual(1); object = Convert.toFloat(new BigDecimal(1)); the(object).shouldBeA(Float.class); a(object).shouldBeEqual(1); }
### Question: Convert { public static Short toShort(Object value) { if (value == null) { return null; } else if (value instanceof Short) { return (Short) value; } else if (value instanceof Number) { return ((Number) value).shortValue(); } else { try { return Short.valueOf(value.toString().trim()); } catch (NumberFormatException e) { throw new ConversionException("failed to convert: '" + value + "' to Short", e); } } } private Convert(); static String toString(Object value); static Boolean toBoolean(Object value); static java.sql.Date toSqlDate(Object value); static java.sql.Date truncateToSqlDate(Object value); static java.sql.Date truncateToSqlDate(long time); static String toIsoString(java.util.Date date); static Double toDouble(Object value); static java.sql.Time toTime(Object value); static java.sql.Timestamp toTimestamp(Object value); static Float toFloat(Object value); static Long toLong(Object value); static Integer toInteger(Object value); static BigDecimal toBigDecimal(Object value); static byte[] toBytes(Object value); static byte[] toBytes(Blob blob); static Short toShort(Object value); }### Answer: @Test public void shouldCovertToShort() { Object object = Convert.toShort(1F); the(object).shouldBeA(Short.class); a(object).shouldBeEqual(1); object = Convert.toShort("1"); the(object).shouldBeA(Short.class); a(object).shouldBeEqual(1); object = Convert.toShort(1L); the(object).shouldBeA(Short.class); a(object).shouldBeEqual(1); object = Convert.toShort(new BigDecimal(1)); the(object).shouldBeA(Short.class); a(object).shouldBeEqual(1); }
### Question: Convert { public static byte[] toBytes(Object value) { if (value == null) { return null; } else if (value instanceof byte[]) { return (byte[]) value; } else if (value instanceof Blob) { return toBytes((Blob) value); } else { return toString(value).getBytes(); } } private Convert(); static String toString(Object value); static Boolean toBoolean(Object value); static java.sql.Date toSqlDate(Object value); static java.sql.Date truncateToSqlDate(Object value); static java.sql.Date truncateToSqlDate(long time); static String toIsoString(java.util.Date date); static Double toDouble(Object value); static java.sql.Time toTime(Object value); static java.sql.Timestamp toTimestamp(Object value); static Float toFloat(Object value); static Long toLong(Object value); static Integer toInteger(Object value); static BigDecimal toBigDecimal(Object value); static byte[] toBytes(Object value); static byte[] toBytes(Blob blob); static Short toShort(Object value); }### Answer: @Test public void shouldToBytesCovertNull() { the(Convert.toBytes((Object) null)).shouldBeNull(); }
### Question: CarmlMapper implements Mapper, MappingCache { @Override public <T> T map(Model model, Resource resource, Set<Type> types) { if (types.size() > 1) { if (!types.stream().allMatch(t -> ((Class<?>)t).isInterface())) { throw new IllegalStateException(String.format( "Error mapping %s. In case of multiple types, mapper requires all types to be interfaces", formatResourceForLog(model, resource, namespaces, true))); } } if (types.stream().allMatch(t -> ((Class<?>)t).isInterface())) { return doMultipleInterfaceMapping(model, resource, types); } else { return doSingleTypeConcreteClassMapping(model, resource, Iterables.getOnlyElement(types)); } } CarmlMapper(); CarmlMapper(Set<Namespace> namespaces); @Override T map(Model model, Resource resource, Set<Type> types); @Override Object getCachedMapping(Resource resource, Set<Type> targetType); @Override void addCachedMapping(Resource resource, Set<Type> targetType, Object value); @Override Type getDecidableType(IRI rdfType); @Override void addDecidableType(IRI rdfType, Type type); @Override void bindInterfaceImplementation(Type interfaze, Type implementation); @Override Type getInterfaceImplementation(Type interfaze); }### Answer: @Test public void mapper_havingMethodWithMultiplePropertyAnnotations_MapsCorrectly() { prepareTest(); CarmlMapper mapper = new CarmlMapper(); Person manu = mapper.map(model, (Resource) VF.createIRI("http: ImmutableSet.of(Person.class)); Set<Person> acquaintances = manu.getKnows(); assertThat(acquaintances, hasSize(6)); }
### Question: IriSafeMaker implements Function<String, String> { @Override public String apply(String s) { StringBuilder result = new StringBuilder(); s = Normalizer.normalize(s, normalizationForm); s.codePoints().flatMap(c -> { if ( Character.isAlphabetic(c) || Character.isDigit(c) || c == '-' || c == '.' || c == '_' || c == '~' || ranges.stream().anyMatch(r -> r.includes(c)) ) return IntStream.of(c); String hex = Integer.toHexString(c); hex = upperCaseHex ? hex.toUpperCase() : hex; return ("%" + hex).codePoints(); }) .forEach(c -> result.append((char) c)); return result.toString(); } IriSafeMaker(List<Range> ranges, Form normalizationForm, boolean upperCaseHex); static String makeSafe(String input, Form normalizationForm, boolean upperCaseHex); static IriSafeMaker create(Form normalizationForm, boolean upperCaseHex); static IriSafeMaker create(); @Override String apply(String s); }### Answer: @Test public void nfkcSafeMaker_givenNormalizableToken_encodesAsExpected() { String input = "StandaardGeluidsruimteDagInDb_a_M²"; String expected = "StandaardGeluidsruimteDagInDb_a_M2"; String actual = nfkcSafeMaker.apply(input); assertEquals(expected, actual); }
### Question: ParentTriplesMapper { Set<Resource> map(Set<Pair<String, Object>> joinValues) { if (joinValues.isEmpty()) { return ImmutableSet.of(); } Set<Resource> results = new LinkedHashSet<>(); getIterator.get().forEach(e -> map(e, joinValues) .forEach(results::add)); return results; } ParentTriplesMapper( TermGenerator<Resource> subjectGenerator, TriplesMapperComponents<T> trMapperComponents ); ParentTriplesMapper( TermGenerator<Resource> subjectGenerator, Supplier<Iterable<T>> getIterator, LogicalSourceResolver.ExpressionEvaluatorFactory<T> expressionEvaluatorFactory ); }### Answer: @Test public void parentTriplesMapper_givenJoinConditions() { when(getIterator.get()).thenReturn(ImmutableList.of(entry)); when(expressionEvaluatorFactory.apply(entry)).thenReturn(evaluate); when(subjectGenerator.apply(evaluate)).thenReturn(ImmutableList.of(SKOS.CONCEPT)); ParentTriplesMapper<Object> mapper = new ParentTriplesMapper<>(subjectGenerator, getIterator, expressionEvaluatorFactory); Set<Resource> resources = mapper.map(joinValues); assertThat(resources.size(), is(1)); assertThat(SKOS.CONCEPT, is(in(resources))); } @Test public void parentTriplesMapper_givenMultiJoinWithNullValues_ShouldStillResolveJoin() { when(getIterator.get()).thenReturn(ImmutableList.of(entry)); when(expressionEvaluatorFactory.apply(entry)).thenReturn(evaluate); when(subjectGenerator.apply(evaluate)).thenReturn(ImmutableList.of(SKOS.CONCEPT)); ParentTriplesMapper<Object> mapper = new ParentTriplesMapper<>(subjectGenerator, getIterator, expressionEvaluatorFactory); Set<Resource> resources = mapper.map(multiJoinValues); assertThat(resources.size(), is(1)); assertThat(SKOS.CONCEPT, is(in(resources))); }
### Question: CsvResolver implements LogicalSourceResolver<Record> { @Override public ExpressionEvaluatorFactory<Record> getExpressionEvaluatorFactory() { return entry -> expression -> { logEvaluateExpression(expression, LOG); return Optional.ofNullable(entry.getString(expression)); }; } @Override SourceIterator<Record> getSourceIterator(); @Override ExpressionEvaluatorFactory<Record> getExpressionEvaluatorFactory(); }### Answer: @Test public void expressionEvaluator_givenExpression_shoulReturnCorrectValue() { String expression = "Year"; Iterable<Record> recordIterator = csvResolver.bindSource(LSOURCE, sourceResolver).get(); ExpressionEvaluatorFactory<Record> evaluatorFactory = csvResolver.getExpressionEvaluatorFactory(); List<Record> records = Lists.newArrayList(recordIterator); EvaluateExpression evaluateExpression = evaluatorFactory.apply(records.get(0)); assertThat(evaluateExpression.apply(expression).get(), is("1997")); }
### Question: HelloDocker { @GET public static String hello() { return "Hello world!"; } @GET static String hello(); static void main(String[] args); }### Answer: @Test public void testHello() { assertEquals("Hello world!", target("/").request().get(String.class)); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public SharedCacheMode getSharedCacheMode() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetSharedCacheMode() { pui.getSharedCacheMode(); }