method2testcases
stringlengths
118
6.63k
### Question: FsMountPoint implements Serializable, Comparable<FsMountPoint> { public static FsMountPoint create(URI uri) { return create(uri, NULL); } @ConstructorProperties("uri") FsMountPoint(URI uri); FsMountPoint(URI uri, FsUriModifier modifier); FsMountPoint(final FsScheme scheme, final...
### Question: FsMountPoint implements Serializable, Comparable<FsMountPoint> { public FsNodePath resolve(FsNodeName name) { return new FsNodePath(this, name); } @ConstructorProperties("uri") FsMountPoint(URI uri); FsMountPoint(URI uri, FsUriModifier modifier); FsMountPoint(final FsScheme scheme, ...
### Question: User implements Serializable { public User(final String login, final String password) { this.login = login; this.password = password; } User(final String login, final String password); final void setLocale(final String locale); final Date getLastUpdate(); final void setLastUpdate(final Date lastUpdate); f...
### Question: Portfolio { public final Optional<Account> getAccount(final String name) { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> account.getName().equals(name)).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotal...
### Question: Portfolio { public final Optional<Account> getFirstAccount() { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> !account.getDel()).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute();...
### Question: Portfolio { protected Map<String, List<Equity>> getSectorByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { companies = map.getOrDefault(Constants.FUND, new ArrayList<>()); companie...
### Question: Portfolio { public final String getHTMLSectorByCompanies() { final Map<String, List<Equity>> map = getSectorByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYiel...
### Question: Portfolio { protected Map<String, List<Equity>> getGapByCompanies() { final Map<String, List<Equity>> map = new TreeMap<>(); List<Equity> companies; for (final Equity equity : getEquities()) { if (equity.getMarketCapitalizationType().getValue() == null || equity.getCompany().getFund()) { equity.setMarketC...
### Question: Portfolio { public final String getHTMLCapByCompanies() { final Map<String, List<Equity>> map = getGapByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(...
### Question: Portfolio { public final Double getTotalValue() { return totalValue + getLiquidity(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc()...
### Question: Portfolio { public final void compute() { Double totalUnitCostPrice = 0d; Double totalAverageQuotePrice = 0d; Double totalOriginalValue = 0d; totalVariation = 0d; double totalValueStart = 0; totalGainToday = 0d; Date lastUpdate = null; if (equities != null) { for (final Equity equity : equities) { totalQu...
### Question: Portfolio { protected final Map<String, Double> getChartSectorData() { if (chartSectorData == null) { final Map<String, Double> data = new HashMap<>(); for (final Equity equity : getEquities()) { if (equity.getCompany().getFund()) { addEquityValueToMap(data, Constants.FUND, equity); } else { final String ...
### Question: Portfolio { protected final Map<Date, Double> getChartShareValueData() { Map<Date, Double> data = new HashMap<>(); List<ShareValue> shareValuess = getShareValues(); int max = shareValuess.size(); double base = shareValuess.get(max - 1).getShareValue(); for (int i = max - 1; i != -1; i--) { ShareValue temp...
### Question: Portfolio { protected final Map<String, Double> getChartCapData() { if (chartCapData == null) { Map<String, Double> data = new HashMap<>(); for (Equity equity : getEquities()) { if (!equity.getCompany().getFund()) { MarketCapitalization marketCap = equity.getMarketCapitalizationType(); if (marketCap == nu...
### Question: Portfolio { public final List<String> getCompaniesYahooIdRealTime() { return getEquities().stream() .filter(equity -> equity.getCompany().getRealTime()) .map(equity -> equity.getCompany().getYahooId()) .collect(Collectors.toList()); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMin...
### Question: Portfolio { public final void addIndexes(final List<Index> indexes) { if (indexes.size() > 0) { String index = indexes.get(0).getYahooId(); this.indexes.put(index, indexes); } } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute();...
### Question: Portfolio { public final String getPortfolioReview() { final StringBuilder sb = new StringBuilder(); sb.append("<table class=\"shareValueTableDetails\">"); for (final Equity equity : getEquities()) { sb.append("<tr><td width=200px><b>") .append(equity.getCurrentName()) .append("</b></td><td width=180px>")...
### Question: TokenUtils { public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.genKeyPair(); return keyPair; } private TokenUtils(); static ...
### Question: TokenUtils { public static PrivateKey readPrivateKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length)); return p...
### Question: TokenUtils { public static PublicKey readPublicKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PublicKey publicKey = decodePublicKey(new String(tmp, 0, length)); return public...
### Question: MicrometerMetricsRegistry implements MetricsRegistry { @Override public <T> Gauge gauge(String name, Collection<Tag> tags, T obj, ToDoubleFunction<T> f) { return new MicrometerGauge<T>(io.micrometer.core.instrument.Gauge.builder(name, obj, f).tags(toTags(tags)).register(registry)); } MicrometerMetricsRegi...
### Question: Span implements io.opentracing.Span { @Override public void finish() { finishTrace(clock.microTime()); } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); ...
### Question: GRPCAgentClient extends BaseGrpcClient<Span> { @Override public boolean send(Span span) throws ClientException { try (Sample timer = sendTimer.start()) { stub.dispatch(format.format(span), observer); } catch (Exception e) { sendExceptionCounter.increment(); throw new ClientException(e.getMessage(), e); } ...
### Question: HttpCollectorClient extends BaseHttpClient implements Client<Span> { @Override public boolean send(Span span) throws ClientException { final byte[] spanBytes = format.format(span).toByteArray(); return super.send(spanBytes); } HttpCollectorClient(String endpoint, Map<String, String> headers); HttpCollect...
### Question: RemoteDispatcher implements Dispatcher { @Override public void dispatch(Span span) { try (Sample timer = dispatchTimer.start()) { if (running.get()) { final boolean accepted = acceptQueue.offer(span); if (!accepted) { dispatchRejectedCounter.increment(); LOGGER.warn("Send queue is rejecting new spans"); }...
### Question: Span implements io.opentracing.Span { public String getServiceName() { synchronized (this) { return getTracer().getServiceName(); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString...
### Question: Span implements io.opentracing.Span { public Map<String, Object> getTags() { synchronized (this) { return Collections.unmodifiableMap(tags); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override Stri...
### Question: TeamUserController { @ApiOperation(value = "This API returns all TeamUser Objects present in Elastic Search", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned all TeamUser Objects"), @ApiResponse(code = 401, message = "User is not authorized to view req...
### Question: TeamUserController { @ApiOperation(value = "This API returns TeamUser Object present in Elastic Search for current user", response = ResponseEntity.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returned TeamUser Object for current user"), @ApiResponse(code = 401, message = "User is no...
### Question: Customer extends Person { public void setEmail(String email) { this.email = email; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); Integer getAge(...
### Question: Item { public Long getId() { return id; } Item(); Item(String title, Float price, String description); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); }### Answer: @Test public v...
### Question: CreditCard { public String getNumber() { return number; } CreditCard(); CreditCard(String number, String expiryDate, Integer controlNumber, CreditCardType creditCardType); String getNumber(); void setNumber(String number); String getExpiryDate(); void setExpiryDate(String expiryDate); Integer getControlN...
### Question: Address { public Long getId() { return id; } Address(); Address(Long id, String street1, String street2, String city, String state, String zipcode, String country); Long getId(); void setId(Long id); String getStreet1(); void setStreet1(String street1); String getStreet2(); void setStreet2(String street2...
### Question: Book { public Long getId() { return id; } Book(); Book(Long id, String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String ge...
### Question: Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescript...
### Question: News { public String getContent() { return content; } News(); News(NewsId id, String content); NewsId getId(); void setId(NewsId id); String getContent(); void setContent(String content); }### Answer: @Test public void shouldCreateANews() throws Exception { News news = new News(new NewsId("Richard Wrigh...
### Question: AddressEndpoint { @PostMapping("/addresses") public Address createAddress(@RequestBody Address address) { return addressRepository.save(address); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/ad...
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, Date dateOfBirth, Date creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); ...
### Question: BookService { public void createBook() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("cdbookstorePU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Book book = new Book().title("H2G2").price(12.5F).isbn("1-84023-742-2").nbOfPages(354); tx....
### Question: Customer { public void setAddress(Address address) { this.address = address; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void ...
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); Address g...
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(...
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(...
### Question: Customer { @Id @GeneratedValue public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); void setId(Long id); void setFirstName(String firstName); void setLastName(String lastName); void setEmail(String email); void setPhoneNumber(String...
### Question: AddressEndpoint { @GetMapping(value = "/addresses/country/{country}") public List<Address> getAddressesByCountry(@PathVariable String country) { return addressRepository.findAllByCountry(country); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@Req...
### Question: Author { public Author firstName(String firstName) { this.firstName = firstName; return this; } Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); Author firstName(String firstName); String getLastName(); void setLastName(String lastName); Author lastName(Strin...
### Question: AddressEndpoint { @GetMapping(value = "/addresses/like/{zip}") public List<Address> getAddressesLikeZip(@PathVariable String zip) { return addressRepository.findAllLikeZip(zip); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address ad...
### Question: Artist { public Artist firstName(String firstName) { this.firstName = firstName; return this; } Artist(); Artist(String firstName, String lastName, String email, String bio, LocalDate dateOfBirth); Long getId(); String getFirstName(); void setFirstName(String firstName); Artist firstName(String firstName...
### Question: Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, LocalDate dateOfBirth, LocalDateTime creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(Stri...
### Question: Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescri...
### Question: Track { public Long getId() { return id; } Track(); Track(String title, Float duration, String description); Long getId(); String getTitle(); void setTitle(String title); Float getDuration(); void setDuration(Float duration); byte[] getWav(); void setWav(byte[] wav); String getDescription(); void setDesc...
### Question: News { public String getTitle() { return title; } News(); News(String title, String language, String content); String getTitle(); void setTitle(String title); String getLanguage(); void setLanguage(String language); String getContent(); void setContent(String content); }### Answer: @Test public void sho...
### 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 n...
### 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...
### 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...
### 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(...
### 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) .verifyComplet...
### 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(); StepV...
### 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, ...
### Question: MaxSubProblem { public int maxSub(int[] data) { int maxend = data[0]; int maxfar = data[0]; for (int i = 1; i < data.length; i++) { maxend = Math.max(data[i], maxend + data[i]); maxfar = Math.max(maxfar, maxend); } return maxfar > 0 ? maxfar : 0; } int maxSub1(int[] data); int maxSub2(int[] data); int ma...
### Question: SimpleArrayList extends AbstractList<E> implements List<E> { @Override public void add(int index, E element) { if (index < 0 || index > size()) { throw new IndexOutOfBoundsException("Invalid index"); } if (arr.length == size) { Object[] temparr = new Object[size * 2]; for (int i = 0; i < size; i++) { coun...
### 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") ...
### Question: BinSearchFirstElement { public static int binSearch(int[] data, int value) { int l = -1, h = data.length; while (l + 1 != h) { int m = l + (h - l) / 2; if (data[m] < value) { l = m; } else { h = m; } } return h; } static int binSearch(int[] data, int value); }### Answer: @Test public void findFirstEleme...
### Question: BinaryObjectSearch { public static <T extends Comparable<? super T>> int binSearch(T[] data, T value) { int l = -1, h = data.length; while (l + 1 != h) { int m = l + (h - l) / 2; int compare = data[m].compareTo(value); if (compare < 0) { l = m; } else if (compare > 0) { h = m; } else { return m; } } retur...
### 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 m...
### 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 co...
### 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); } ret...
### 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(...
### 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 us...
### 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[][] getMo...
### 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.getFirstN...
### 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...
### 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[][] getUserListA...
### 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[][] get...
### 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) { movie...
### 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 updateR...
### 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> getUse...
### 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[][] ...
### 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(); rental...
### 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 dele...
### 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; ...
### 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 (SQ...
### 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));...
### Question: SQLUserDAO implements UserDAO { @Override public void saveOrUpdate(IUser user) { try { PreparedStatement ps = connection.prepareStatement(GET_BY_ID_SQL); ps.setInt(1, user.getId()); ResultSet r = ps.executeQuery(); if (r.next()) { PreparedStatement update = connection.prepareStatement(UPDATE_SQL); update....
### 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() { t...
### 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,...
### 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, ...
### 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); ...
### 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 rentaldat...
### 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 daysRente...
### 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 ...
### 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 NewReleasePri...
### 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...
### 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; } in...
### 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...
### 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()...
### 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.first...
### 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 set...