method2testcases
stringlengths
118
6.63k
### Question: HIA2ReportFormTextWatcher implements TextWatcher { public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } HIA2ReportFormTextWatcher(JsonFormFragment formFragment, String hi2IndicatorCode); void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2); void onTextChanged(CharSequence charSequence, int start, int before, int count); void afterTextChanged(Editable editable); }### Answer: @Test public void beforeTextChangedWasCalledWithTheCorrectParameters() { hia2ReportFormTextWatcher.beforeTextChanged(STRING_TEST_CONSTANTS.EMPTY_STRING, INT_TEST_CONSTANTS.INT_1, INT_TEST_CONSTANTS.INT_2, INT_TEST_CONSTANTS.INT_3); Mockito.verify(hia2ReportFormTextWatcher).beforeTextChanged(stringCaptor.capture(), param1IntCaptor.capture(), param2IntCaptor.capture(), param3IntCaptor.capture()); org.junit.Assert.assertEquals(stringCaptor.getValue(), STRING_TEST_CONSTANTS.EMPTY_STRING); org.hamcrest.MatcherAssert.assertThat(param1IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_1)); org.hamcrest.MatcherAssert.assertThat(param2IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_2)); org.hamcrest.MatcherAssert.assertThat(param3IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_3)); }
### Question: HIA2ReportFormTextWatcher implements TextWatcher { public void onTextChanged(CharSequence charSequence, int start, int before, int count) { } HIA2ReportFormTextWatcher(JsonFormFragment formFragment, String hi2IndicatorCode); void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2); void onTextChanged(CharSequence charSequence, int start, int before, int count); void afterTextChanged(Editable editable); }### Answer: @Test public void onTextChangedWasCalledWithTheCorrectParameters() { hia2ReportFormTextWatcher.onTextChanged(STRING_TEST_CONSTANTS.EMPTY_STRING, INT_TEST_CONSTANTS.INT_1, INT_TEST_CONSTANTS.INT_2, INT_TEST_CONSTANTS.INT_3); Mockito.verify(hia2ReportFormTextWatcher).onTextChanged(stringCaptor.capture(), param1IntCaptor.capture(), param2IntCaptor.capture(), param3IntCaptor.capture()); org.junit.Assert.assertEquals(stringCaptor.getValue(), STRING_TEST_CONSTANTS.EMPTY_STRING); org.hamcrest.MatcherAssert.assertThat(param1IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_1)); org.hamcrest.MatcherAssert.assertThat(param2IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_2)); org.hamcrest.MatcherAssert.assertThat(param3IntCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(INT_TEST_CONSTANTS.INT_3)); }
### Question: HIA2ReportFormTextWatcher implements TextWatcher { public void afterTextChanged(Editable editable) { if (indicatorKeyMap.containsKey(hia2Indicator)) { Integer aggregateValue = 0; String[] operandIndicators = aggregateFieldsMap.get(indicatorKeyMap.get(hia2Indicator)); for (int i = 0; i < operandIndicators.length; i++) { MaterialEditText editTextIndicatorView = (MaterialEditText) formFragment.getMainView().findViewWithTag(operandIndicators[i]); aggregateValue += editTextIndicatorView.getText() == null || editTextIndicatorView.getText().toString().isEmpty() ? 0 : Integer.valueOf(editTextIndicatorView.getText().toString()); } MaterialEditText aggregateEditText = (MaterialEditText) formFragment.getMainView().findViewWithTag(indicatorKeyMap.get(hia2Indicator)); aggregateEditText.setText(Integer.toString(aggregateValue)); } } HIA2ReportFormTextWatcher(JsonFormFragment formFragment, String hi2IndicatorCode); void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2); void onTextChanged(CharSequence charSequence, int start, int before, int count); void afterTextChanged(Editable editable); }### Answer: @Test public void afterTextChangedWasCalledWithTheCorrectParameters() { hia2ReportFormTextWatcher.afterTextChanged(editable); Mockito.verify(hia2ReportFormTextWatcher).afterTextChanged(editableArgumentCaptor.capture()); org.hamcrest.MatcherAssert.assertThat(editableArgumentCaptor.getValue(), org.hamcrest.CoreMatchers.equalTo(editableArgumentCaptor.getValue())); }
### Question: ImageUtils { public static Photo profilePhotoByClient(CommonPersonObjectClient client) { Photo photo = new Photo(); ProfileImage profileImage = VaccinatorApplication.getInstance().context().imageRepository().findByEntityId(client.entityId()); if (profileImage != null) { photo.setFilePath(profileImage.getFilepath()); } else { String gender = getValue(client, "gender", true); photo.setResourceId(profileImageResourceByGender(gender)); } return photo; } static int profileImageResourceByGender(String gender); static int profileImageResourceByGender(Gender gender); static Photo profilePhotoByClient(CommonPersonObjectClient client); }### Answer: @Test public void profilePhotoByClientReturnsDefaultInfantBoyPhoto() { PowerMockito.mockStatic(VaccinatorApplication.class); PowerMockito.when(VaccinatorApplication.getInstance()).thenReturn(vaccinatorApplication); PowerMockito.when(VaccinatorApplication.getInstance().context()).thenReturn(context); PowerMockito.when(VaccinatorApplication.getInstance().context().imageRepository()).thenReturn(imageRepository); PowerMockito.when(VaccinatorApplication.getInstance().context().imageRepository().findByEntityId(anyString())).thenReturn(null); Photo photo = ImageUtils.profilePhotoByClient(commonPersonObjectClient); assertNotNull(photo); assertEquals(photo.getResourceId(), R.drawable.child_boy_infant); } @Test public void profilePhotoByClientReturnsCorrectPhotoFilePathForCorrespondingClient() { PowerMockito.mockStatic(VaccinatorApplication.class); PowerMockito.when(VaccinatorApplication.getInstance()).thenReturn(vaccinatorApplication); PowerMockito.when(VaccinatorApplication.getInstance().context()).thenReturn(context); PowerMockito.when(VaccinatorApplication.getInstance().context().imageRepository()).thenReturn(imageRepository); ProfileImage profileImage = new ProfileImage(); String imagePath = "/dummy/test/path/image.png"; String dummyCaseId = "4400"; profileImage.setFilepath(imagePath); PowerMockito.when(VaccinatorApplication.getInstance().context().imageRepository().findByEntityId(dummyCaseId)).thenReturn(profileImage); commonPersonObjectClient = new CommonPersonObjectClient(dummyCaseId, Collections.<String, String>emptyMap(), "Test Name"); commonPersonObjectClient.setCaseId(dummyCaseId); Photo photo = ImageUtils.profilePhotoByClient(commonPersonObjectClient); assertNotNull(photo); assertEquals(imagePath, photo.getFilePath()); }
### Question: NowPlayingViewModel extends ViewModel { @NonNull public ObservableBoolean getFirstLoad() { return firstLoad; } @Inject NowPlayingViewModel(@NonNull Application application, @NonNull ServiceGateway serviceGateway); @Override void onCleared(); @NonNull List<MovieViewInfo> getMovieViewInfoList(); void loadMoreNowPlayingInfo(); @NonNull Observable<Boolean> getShowErrorObserver(); @NonNull ObservableField<String> getToolbarTitle(); @NonNull ObservableBoolean getFirstLoad(); @NonNull BehaviorSubject<Boolean> getLoadMoreEnabledBehaviorSubject(); @NonNull PublishSubject<AdapterUiCommand> getAdapterDataPublishSubject(); }### Answer: @Test public void isFirstLoadInProgress_true() throws Exception { NowPlayingViewModel nowPlayingViewModel = new NowPlayingViewModel(mockApplication, mockServiceGateway); assertThat(nowPlayingViewModel.getFirstLoad().get()).isTrue(); } @Test public void isFirstLoadInProgress_false() throws Exception { NowPlayingViewModel nowPlayingViewModel = new NowPlayingViewModel(mockApplication, mockServiceGateway); testScheduler.triggerActions(); testScheduler.advanceTimeBy(10, TimeUnit.SECONDS); assertThat(nowPlayingViewModel.getFirstLoad().get()).isFalse(); }
### Question: NowPlayingViewModel extends ViewModel { @NonNull public List<MovieViewInfo> getMovieViewInfoList() { return movieViewInfoList; } @Inject NowPlayingViewModel(@NonNull Application application, @NonNull ServiceGateway serviceGateway); @Override void onCleared(); @NonNull List<MovieViewInfo> getMovieViewInfoList(); void loadMoreNowPlayingInfo(); @NonNull Observable<Boolean> getShowErrorObserver(); @NonNull ObservableField<String> getToolbarTitle(); @NonNull ObservableBoolean getFirstLoad(); @NonNull BehaviorSubject<Boolean> getLoadMoreEnabledBehaviorSubject(); @NonNull PublishSubject<AdapterUiCommand> getAdapterDataPublishSubject(); }### Answer: @Test public void getMovieViewInfoList() throws Exception { NowPlayingViewModel nowPlayingViewModel = new NowPlayingViewModel(mockApplication, mockServiceGateway); List<MovieViewInfo> movieViewInfos = nowPlayingViewModel.getMovieViewInfoList(); assertThat(movieViewInfos.size()).isEqualTo(0); }
### Question: ScrollEventCalculator { public boolean isAtScrollEnd() { RecyclerView.LayoutManager layoutManager = recyclerViewScrollEvent.view().getLayoutManager(); if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; int totalItemCount = linearLayoutManager.getItemCount(); int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition(); return totalItemCount <= (lastVisibleItem + 2); } else { return false; } } ScrollEventCalculator(RecyclerViewScrollEvent recyclerViewScrollEvent); boolean isAtScrollEnd(); }### Answer: @Test public void isAtScrollEnd() throws Exception { LinearLayoutManager mockLinearLayoutManager = Mockito.mock(LinearLayoutManager.class); RecyclerView mockRecyclerView = Mockito.mock(RecyclerView.class); RecyclerViewScrollEvent mockRecyclerViewScrollEvent = Mockito.mock(RecyclerViewScrollEvent.class); when(mockLinearLayoutManager.getItemCount()).thenReturn(50); when(mockLinearLayoutManager.findLastVisibleItemPosition()).thenReturn(50); when(mockRecyclerView.getLayoutManager()).thenReturn(mockLinearLayoutManager); when(mockRecyclerViewScrollEvent.dx()).thenReturn(0); when(mockRecyclerViewScrollEvent.dy()).thenReturn(100); when(mockRecyclerViewScrollEvent.view()).thenReturn(mockRecyclerView); ScrollEventCalculator scrollEventCalculator = new ScrollEventCalculator(mockRecyclerViewScrollEvent); boolean value = scrollEventCalculator.isAtScrollEnd(); assertThat(value).isTrue(); } @Test public void isAtScrollEnd_false() throws Exception { LinearLayoutManager mockLinearLayoutManager = Mockito.mock(LinearLayoutManager.class); RecyclerView mockRecyclerView = Mockito.mock(RecyclerView.class); RecyclerViewScrollEvent mockRecyclerViewScrollEvent = Mockito.mock(RecyclerViewScrollEvent.class); when(mockLinearLayoutManager.getItemCount()).thenReturn(50); when(mockLinearLayoutManager.findLastVisibleItemPosition()).thenReturn(5); when(mockRecyclerView.getLayoutManager()).thenReturn(mockLinearLayoutManager); when(mockRecyclerViewScrollEvent.dx()).thenReturn(0); when(mockRecyclerViewScrollEvent.dy()).thenReturn(100); when(mockRecyclerViewScrollEvent.view()).thenReturn(mockRecyclerView); ScrollEventCalculator scrollEventCalculator = new ScrollEventCalculator(mockRecyclerViewScrollEvent); boolean value = scrollEventCalculator.isAtScrollEnd(); assertThat(value).isFalse(); }
### Question: RxBus { public static RxBus getDefault() { return sInstance; } private RxBus(); static RxBus getDefault(); @SuppressWarnings("ConstantConditions") void post(@android.support.annotation.NonNull Event event); Observable<Event> register(@android.support.annotation.NonNull final String tag); Observable<Event> register(@android.support.annotation.NonNull final Class aClass); Observable<Event> register(@android.support.annotation.NonNull final String[] tags); Observable<Event> register(@android.support.annotation.NonNull final Class[] aClass); }### Answer: @Test public void isSingleton() throws Exception { assertEquals(mRxBus, RxBus.getDefault()); }
### Question: BarcodeInfo { Phone getPhone() { return mPhone; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getPhone() throws Exception { BarcodeInfo.Phone phone = new BarcodeInfo.Phone("7894561230"); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setPhone(phone); assertEquals(barcodeInfo.getPhone(), phone); }
### Question: BarcodeInfo { String getRawValue() { return mRawValue; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getRawValue() throws Exception { BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setRawValue("Raw value"); assertEquals(barcodeInfo.getRawValue(), "Raw value"); }
### Question: RxBus { @SuppressWarnings("ConstantConditions") public void post(@android.support.annotation.NonNull Event event) { if (event == null) throw new IllegalArgumentException("Event cannot be null."); sBus.onNext(event); } private RxBus(); static RxBus getDefault(); @SuppressWarnings("ConstantConditions") void post(@android.support.annotation.NonNull Event event); Observable<Event> register(@android.support.annotation.NonNull final String tag); Observable<Event> register(@android.support.annotation.NonNull final Class aClass); Observable<Event> register(@android.support.annotation.NonNull final String[] tags); Observable<Event> register(@android.support.annotation.NonNull final Class[] aClass); }### Answer: @SuppressWarnings("ConstantConditions") @Test public void postNull() throws Exception { try { mRxBus.post(null); fail(); } catch (IllegalArgumentException e) { } }
### Question: Event { @android.support.annotation.NonNull public String getTag() { return mTag; } @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull String tag); @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull Object o); @android.support.annotation.NonNull String getTag(); Object getObject(); }### Answer: @Test public void getTag() throws Exception { String mockTag = "Test"; Event event = new Event(mockTag); assertEquals(event.getTag(), mockTag); Integer mockObj = 34; event = new Event(mockObj); assertEquals(event.getTag(), mockObj.getClass().getSimpleName()); }
### Question: Event { public Object getObject() { return mObject; } @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull String tag); @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull Object o); @android.support.annotation.NonNull String getTag(); Object getObject(); }### Answer: @Test public void getObject() throws Exception { Integer mockObj = 34; Event event = new Event(mockObj); assertEquals(event.getObject(), mockObj); }
### Question: InfoModel { public String getLabel() { return label; } InfoModel(@NonNull String label); String getInfo(); void setInfo(@NonNull String info); String getImageUrl(); void setImageUrl(String imageUrl); String getLabel(); }### Answer: @SuppressWarnings("ConstantConditions") @Test public void checkLLabel() throws Exception { try { new InfoModel(null); fail(); } catch (IllegalArgumentException e) { } InfoModel infoModel = new InfoModel(MOCK_LABEL); assertEquals(infoModel.getLabel(), MOCK_LABEL); }
### Question: BarcodeInfo { Contact getContact() { return mContact; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getContact() throws Exception { BarcodeInfo.Contact contact = new BarcodeInfo.Contact(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setContact(contact); assertEquals(barcodeInfo.getContact(), contact); }
### Question: BarcodeInfo { UrlBookmark getUrlBookmark() { return mUrlBookmark; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getUrlBookmark() throws Exception { BarcodeInfo.UrlBookmark urlBookmark = new BarcodeInfo.UrlBookmark("Google", "www.google.com"); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setUrlBookmark(urlBookmark); assertEquals(barcodeInfo.getUrlBookmark(), urlBookmark); }
### Question: BarcodeInfo { Sms getSms() { return mSms; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getSms() throws Exception { BarcodeInfo.Sms sms = new BarcodeInfo.Sms("This is test message.", "1234567890"); BarcodeInfo info = new BarcodeInfo(); info.setSms(sms); assertEquals(info.getSms(), sms); }
### Question: BarcodeInfo { GeoPoint getGeoPoint() { return mGeoPoint; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getGeoPoint() throws Exception { BarcodeInfo.GeoPoint geoPoint = new BarcodeInfo.GeoPoint(23.0225, 72.5714); BarcodeInfo info = new BarcodeInfo(); info.setGeoPoint(geoPoint); assertEquals(info.getGeoPoint(), geoPoint); }
### Question: BarcodeInfo { CalendarEvent getCalendarEvent() { return mCalendarEvent; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(String rawValue); }### Answer: @Test public void getCalendarEvent() throws Exception { BarcodeInfo.CalendarEvent calendarEvent = new BarcodeInfo.CalendarEvent(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setCalendarEvent(calendarEvent); assertEquals(barcodeInfo.getCalendarEvent(), calendarEvent); }
### Question: ClasspathUtils { @SuppressWarnings("unchecked") public static <T> Class<? extends T> findImplementationClass(Class<T> clazz) { if (!Modifier.isAbstract(clazz.getModifiers())) return clazz; String implementationClass = String.format("%s.impl.%sImpl", clazz.getPackage().getName(), clazz.getSimpleName()); try { return (Class<? extends T>) Class.forName(implementationClass); } catch (ClassNotFoundException e) { throw new NoImplementationClassFoundException(clazz, e); } } private ClasspathUtils(); @SuppressWarnings("unchecked") static Class<? extends T> findImplementationClass(Class<T> clazz); }### Answer: @Test public void shouldFindImplementation() { Class<? extends DummyComponent> clazz = ClasspathUtils .findImplementationClass(DummyComponent.class); assertEquals(clazz, DummyComponentImpl.class); } @Test(expectedExceptions = RuntimeException.class) public void shouldThrowExceptionWhenNoImplementationIsFound() { ClasspathUtils.findImplementationClass(List.class); }
### Question: WisePageFactory { public static <T> T initElements(WebDriver driver, Class<T> clazz) { T instance = instantiatePage(driver, clazz); return initElements(driver, instance); } private WisePageFactory(); static T initElements(WebDriver driver, Class<T> clazz); static T initElements(SearchContext searchContext, T instance); }### Answer: @Test public void shouldCreatePageWithWebDriverConstructorAndInitElements() { DummyPageWithWebDriverConstructor page = WisePageFactory.initElements( this.driver, DummyPageWithWebDriverConstructor.class); assertNotNull(page.getDummyComponent()); } @Test public void shouldCreatePageWithNoArgConstructorAndInitElements() { DummyPageWithNoArgConstructor page = WisePageFactory.initElements(this.driver, DummyPageWithNoArgConstructor.class); assertNotNull(page.getDummyComponent()); } @Test public void shouldInitElementsOfInstance() { DummyPageWithWebDriverConstructor page = new DummyPageWithWebDriverConstructor(this.driver); WisePageFactory.initElements(this.driver, page); assertNotNull(page.getDummyComponent()); } @Test(expectedExceptions = PageInstantiationException.class) public void shouldThrowExceptionWhileInstantiatingPageWithoutProperConstructor() { WisePageFactory.initElements(this.driver, DummyPageWithoutProperConstructor.class); }
### Question: Wiselenium { public static <E> E findElement(Class<E> clazz, By by, SearchContext searchContext) { WebElement webElement = searchContext.findElement(by); return decorateElement(clazz, webElement); } private Wiselenium(); static E findElement(Class<E> clazz, By by, SearchContext searchContext); static List<E> findElements(Class<E> clazz, By by, SearchContext searchContext); static E decorateElement(Class<E> clazz, WebElement webElement); static List<E> decorateElements(Class<E> clazz, List<WebElement> webElements); }### Answer: @Test public void shouldFindElement() { DummyComponent select = Wiselenium.findElement(DummyComponent.class, BY_SELECT1, this.driver); assertNotNull(select); } @Test(expectedExceptions = NoSuchElementException.class) public void shouldThrowExceptionWhenElementIsntFound() { Wiselenium.findElement(DummyComponent.class, By.id("inexistent"), this.driver); }
### Question: Wiselenium { public static <E> List<E> findElements(Class<E> clazz, By by, SearchContext searchContext) { List<WebElement> webElements = searchContext.findElements(by); if (webElements.isEmpty()) return Lists.newArrayList(); WiseDecorator decorator = new WiseDecorator(new DefaultElementLocatorFactory(searchContext)); return decorator.decorate(clazz, webElements); } private Wiselenium(); static E findElement(Class<E> clazz, By by, SearchContext searchContext); static List<E> findElements(Class<E> clazz, By by, SearchContext searchContext); static E decorateElement(Class<E> clazz, WebElement webElement); static List<E> decorateElements(Class<E> clazz, List<WebElement> webElements); }### Answer: @SuppressWarnings("null") @Test public void shouldFindElements() { List<DummyComponent> elements = Wiselenium.findElements( DummyComponent.class, BY_RADIOBUTTON, this.driver); assertTrue(elements != null && !elements.isEmpty()); for (DummyComponent element : elements) { assertNotNull(element); } } @Test public void shouldReturnEmptyListWhenElementsAreNotFound() { List<DummyComponent> selects = Wiselenium.findElements( DummyComponent.class, By.id("inexistent"), this.driver); assertTrue(selects != null && selects.isEmpty()); }
### Question: LexerStream extends LineNumberReader { public int peek() throws IOException { super.mark(1); int c = super.read(); super.reset(); return c; } LexerStream(Reader in_stream); int getLine(); int getCol(); int getPosition(); @Override int read(); @Override String readLine(); int peek(); int peek(int ahead); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override void mark(int readAheadLimit); @Override void reset(); }### Answer: @Test public void peek() throws Exception { Reader in = new StringReader("I see you"); LexerStream ls = new LexerStream(in); assertEquals(1, ls.getLine()); assertEquals(1, ls.getCol()); int c = ls.peek(); assertEquals('I', (char)c); assertTrue(1 == ls.getLine() && 1 == ls.getCol()); c = ls.peek(2); assertEquals(' ', (char)c); assertTrue(1 == ls.getLine() && 1 == ls.getCol()); c = ls.peek(4); assertEquals('e', (char)c); assertTrue(1 == ls.getLine() && 1 == ls.getCol()); c = ls.peek(8); assertEquals('o', (char)c); assertTrue(1 == ls.getLine() && 1 == ls.getCol()); c = ls.read(); assertEquals('I', (char)c); assertTrue(1 == ls.getLine() && 2 == ls.getCol()); }
### Question: LexCharLiteral { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int code_point; int next = in_stream.peek(); if (next != '\'') { throw new LexerException(start_line, start_col, "Not a character literal"); } in_stream.read(); next = in_stream.peek(); if (next == '\'') { in_stream.read(); return factory.create(TokenType.LiteralChar, start_index, start_line, start_col, 2, "''"); } if (next == '\\') { code_point = LexEscape.read(in_stream); } else { code_point = in_stream.read(); } if (in_stream.read() != '\'') { throw new LexerException(start_line, start_col, "Unterminated character literal"); } String ch_str = String.valueOf(Character.toChars(code_point)); return factory.create(TokenType.LiteralChar, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), ch_str); } LexCharLiteral(TokenFactory factory, LexerStream in_stream); Token read(); }### Answer: @Test public void chars() throws Exception { String str = "'a' '\\n' '' '\\t'"; LexerStream ls = new LexerStream(new StringReader(str)); LexCharLiteral lex = new LexCharLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralChar, tok.getType()); assertEquals("a", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LiteralChar, tok.getType()); assertEquals("\n", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LiteralChar, tok.getType()); assertEquals("''", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(10, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(12, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LiteralChar, tok.getType()); assertEquals("\t", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(13, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(17, tok.getEndCol()); }
### Question: LexerStream extends LineNumberReader { @Override public String readLine() throws IOException { String ln = super.readLine(); if (ln != null) { index += ln.length(); } line = super.getLineNumber(); col = 1; return ln; } LexerStream(Reader in_stream); int getLine(); int getCol(); int getPosition(); @Override int read(); @Override String readLine(); int peek(); int peek(int ahead); @Override int read(char[] cbuf, int off, int len); @Override long skip(long n); @Override void mark(int readAheadLimit); @Override void reset(); }### Answer: @Test public void readLine() throws Exception { Reader in = new StringReader("line1\nline2\n3line\n\nline5"); LexerStream ls = new LexerStream(in); assertEquals(1, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals('l', (char)ls.read()); assertEquals(1, ls.getLine()); assertEquals(2, ls.getCol()); assertEquals("ine1", ls.readLine()); assertEquals(2, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals("line2", ls.readLine()); assertEquals(3, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals('3', (char)ls.read()); assertEquals(3, ls.getLine()); assertEquals(2, ls.getCol()); assertEquals("line", ls.readLine()); assertEquals(4, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals("", ls.readLine()); assertEquals(5, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals("line5", ls.readLine()); assertEquals(6, ls.getLine()); assertEquals(1, ls.getCol()); assertNull(ls.readLine()); assertEquals(-1, ls.read()); }
### Question: LexTokenString { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of stream when parsing token string literal"); } if (next != 'q') { throw new LexerException(start_line, start_col, "Not a literal hex string"); } in_stream.read(); next = in_stream.peek(); if (next != '{') { throw new LexerException(start_line, start_col, "Not a token string"); } in_stream.read(); StringBuilder result = new StringBuilder(); Token token = parent.next(); while (token != null && token.getType() != TokenType.EOF) { if (token.getType() == TokenType.CloseCurlyBrace) { break; } result.append(token.getValue()); token = parent.next(); if (token == null || token.getType().equals(TokenType.EOF) || token.getType().equals(TokenType.Unknown)) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Invalid token inside token string"); } } if (token == null || token.getType() != TokenType.CloseCurlyBrace) { throw new LexerException(start_line, start_col, "Unexpected end of stream when parsing token string literal"); } return factory.create(TokenType.LiteralUtf8, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), result.toString()); } LexTokenString(TokenFactory factory, LexerStream in_stream, Lexer parent); Token read(); }### Answer: @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexTokenString lex = new LexTokenString(new BaseTokenFactory(), ls, null); lex.read(); } @Test(expected = LexerException.class) public void not() throws Exception { String str = "q[]"; LexerStream ls = new LexerStream(new StringReader(str)); LexTokenString lex = new LexTokenString(new BaseTokenFactory(), ls, null); lex.read(); } @Test(expected = LexerException.class) public void also_not() throws Exception { String str = "\"q{}\""; LexerStream ls = new LexerStream(new StringReader(str)); LexTokenString lex = new LexTokenString(new BaseTokenFactory(), ls, null); lex.read(); }
### Question: MCacheDb extends AbstractActor { public String getValue(String key) { return this.map.get(key); } @Override Receive createReceive(); String getValue(String key); }### Answer: @Test public void testPut() { TestActorRef<MCacheDb> actorRef = TestActorRef.create(actorSystem, Props.create(MCacheDb.class)); actorRef.tell(new SetRequest("key", "value"), ActorRef.noSender()); MCacheDb mCacheDb = actorRef.underlyingActor(); Assert.assertEquals(mCacheDb.getValue("key"), "value"); }
### Question: HelloWorldImpl implements HelloWorldPortType { @Override public Greeting sayHello(Person person) { String firstName = person.getFirstName(); LOGGER.info("firstName={}", firstName); String lasttName = person.getLastName(); LOGGER.info("lastName={}", lasttName); ObjectFactory factory = new ObjectFactory(); Greeting response = factory.createGreeting(); String greeting = "Hello " + firstName + " " + lasttName + "!"; LOGGER.info("greeting={}", greeting); response.setText(greeting); return response; } @Override Greeting sayHello(Person person); }### Answer: @Test public void testSayHelloProxy() { Person person = new Person(); person.setFirstName("Jane"); person.setLastName("Doe"); Greeting greeting = helloWorldRequesterProxy.sayHello(person); assertEquals("Hello Jane Doe!", greeting.getText()); }
### Question: EnrichmentBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { String fileContent = new String(stormTaskTuple.getFileData()); LOGGER.info("starting enrichment on {} .....", stormTaskTuple.getFileUrl()); String output = enrichmentWorker.process(fileContent); LOGGER.info("Finishing enrichment on {} .....", stormTaskTuple.getFileUrl()); emitEnrichedContent(anchorTuple, stormTaskTuple, output); } catch (Exception e) { LOGGER.error("Exception while Enriching/dereference", e); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Remote Enrichment/dereference service caused the problem!. The full error: " + ExceptionUtils.getStackTrace(e), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } EnrichmentBolt(String dereferenceURL, String enrichmentURL); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); }### Answer: @Test public void enrichEdmInternalSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, new HashMap<String, String>(), null); String fileContent = new String(tuple.getFileData()); when(enrichmentWorker.process(eq(fileContent))).thenReturn("enriched file content"); enrichmentBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(Mockito.any(List.class)); Mockito.verify(outputCollector, Mockito.times(0)).emit(Mockito.eq(AbstractDpsBolt.NOTIFICATION_STREAM_NAME), Mockito.any(List.class)); } @Test public void sendErrorNotificationWhenTheEnrichmentFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters(), null); String fileContent = new String(tuple.getFileData()); String errorMessage = "Dereference or Enrichment Exception"; given(enrichmentWorker.process(eq(fileContent))).willThrow(new DereferenceOrEnrichException(errorMessage, new Throwable())); enrichmentBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(0)).emit(Mockito.any(List.class)); Mockito.verify(outputCollector, Mockito.times(1)).emit(Mockito.eq(AbstractDpsBolt.NOTIFICATION_STREAM_NAME), any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); Map val = (Map) capturedValues.get(2); Assert.assertTrue(val.get("additionalInfo").toString().contains("emote Enrichment/dereference service caused the problem!. The full error:")); Assert.assertTrue(val.get("additionalInfo").toString().contains(errorMessage)); }
### Question: RemoverInvoker { public void executeInvokerForSingleTask(long taskId, boolean shouldRemoveErrors) { remover.removeNotifications(taskId); LOGGER.info("Logs for task Id:" + taskId + " were removed successfully"); LOGGER.info("Removing statistics for:" + taskId + " was started. This step could take times depending on the size of the task"); remover.removeStatistics(taskId); LOGGER.info("Statistics for task Id:" + taskId + " were removed successfully"); if (shouldRemoveErrors) { remover.removeErrorReports(taskId); LOGGER.info("Error reports for task Id:" + taskId + " were removed successfully"); } } RemoverInvoker(Remover remover); void executeInvokerForSingleTask(long taskId, boolean shouldRemoveErrors); void executeInvokerForListOfTasks(String filePath, boolean shouldRemoveErrors); }### Answer: @Test public void shouldInvokeAllTheRemovalStepsExcludingErrorReports() { removerInvoker.executeInvokerForSingleTask(TASK_ID, false); verify(remover, times(1)).removeNotifications((eq(TASK_ID))); verify(remover, times(1)).removeStatistics((eq(TASK_ID))); verify(remover, times(0)).removeErrorReports((eq(TASK_ID))); } @Test public void shouldInvokeAllTheRemovalStepsIncludingErrorReports() { removerInvoker.executeInvokerForSingleTask(TASK_ID, true); verify(remover, times(1)).removeNotifications((eq(TASK_ID))); verify(remover, times(1)).removeStatistics((eq(TASK_ID))); verify(remover, times(1)).removeErrorReports((eq(TASK_ID))); }
### Question: ReadFileBolt extends AbstractDpsBolt { private InputStream getFile(FileServiceClient fileClient, String file, String authorization) throws MCSException, IOException { int retries = DEFAULT_RETRIES; while (true) { try { return fileClient.getFile(file, AUTHORIZATION, authorization); } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while getting a file. Retries left:{} ", retries); waitForSpecificTime(); } else { LOGGER.error("Error while getting a file."); throw e; } } } } ReadFileBolt(String ecloudMcsAddress); @Override void prepare(); @Override void execute(Tuple anchorTuple, StormTaskTuple t); }### Answer: @Test public void shouldEmmitNotificationWhenDataSetListHasOneElement() throws MCSException, IOException { when(fileServiceClient.getFile(eq(FILE_URL),eq(AUTHORIZATION), eq(AUTHORIZATION_HEADER))).thenReturn(null); verifyMethodExecutionNumber(1, 0, FILE_URL); } @Test public void shouldRetry3TimesBeforeFailingWhenThrowingMCSException() throws MCSException, IOException { doThrow(MCSException.class).when(fileServiceClient).getFile(eq(FILE_URL),eq(AUTHORIZATION), eq(AUTHORIZATION_HEADER)); verifyMethodExecutionNumber(4, 1, FILE_URL); } @Test public void shouldRetry3TimesBeforeFailingWhenThrowingDriverException() throws MCSException, IOException { doThrow(DriverException.class).when(fileServiceClient).getFile(eq(FILE_URL),eq(AUTHORIZATION), eq(AUTHORIZATION_HEADER)); verifyMethodExecutionNumber(4, 1, FILE_URL); }
### Question: HarvestingWriteRecordBolt extends WriteRecordBolt { private String getCloudId(String authorizationHeader, String providerId, String localId, String additionalLocalIdentifier) throws CloudException { String result; CloudId cloudId; cloudId = getCloudId(providerId, localId, authorizationHeader); if (cloudId != null) { result = cloudId.getId(); } else { result = createCloudId(providerId, localId, authorizationHeader); } if (additionalLocalIdentifier != null) attachAdditionalLocalIdentifier(additionalLocalIdentifier, result, providerId, authorizationHeader); return result; } HarvestingWriteRecordBolt(String ecloudMcsAddress, String ecloudUisAddress); @Override void prepare(); static final String ERROR_MSG_WHILE_CREATING_CLOUD_ID; static final String ERROR_MSG_WHILE_MAPPING_LOCAL_CLOUD_ID; static final String ERROR_MSG_WHILE_GETTING_CLOUD_ID; static final String ERROR_MSG_RETRIES; }### Answer: @Test public void successfulExecuteStormTupleWithExistedCloudId() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); CloudId cloudId = mock(CloudId.class); when(cloudId.getId()).thenReturn(SOURCE + CLOUD_ID); when(uisClient.getCloudId(SOURCE + DATA_PROVIDER, SOURCE + LOCAL_ID,AUTHORIZATION,AUTHORIZATION_HEADER)).thenReturn(cloudId); URI uri = new URI(SOURCE_VERSION_URL); when(recordServiceClient.createRepresentation(anyString(), anyString(), anyString(), any(InputStream.class), anyString(), anyString(),anyString(),anyString())).thenReturn(uri); oaiWriteRecordBoltT.execute(anchorTuple, getStormTaskTuple()); assertExecutionResults(); } @Test public void shouldRetry3TimesBeforeFailingWhenThrowingMCSException() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); CloudId cloudId = mock(CloudId.class); when(cloudId.getId()).thenReturn(SOURCE + CLOUD_ID); when(uisClient.getCloudId(SOURCE + DATA_PROVIDER, SOURCE + LOCAL_ID,AUTHORIZATION,AUTHORIZATION_HEADER)).thenReturn(cloudId); doThrow(MCSException.class).when(recordServiceClient).createRepresentation(anyString(), anyString(), anyString(), any(InputStream.class), anyString(), anyString(),anyString(),anyString()); oaiWriteRecordBoltT.execute(anchorTuple, getStormTaskTuple()); assertFailingExpectationWhenCreatingRepresentation(); } @Test public void shouldRetry3TimesBeforeFailingWhenThrowingDriverException() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); CloudId cloudId = mock(CloudId.class); when(cloudId.getId()).thenReturn(SOURCE + CLOUD_ID); when(uisClient.getCloudId(SOURCE + DATA_PROVIDER, SOURCE + LOCAL_ID,AUTHORIZATION,AUTHORIZATION_HEADER)).thenReturn(cloudId); doThrow(DriverException.class).when(recordServiceClient).createRepresentation(anyString(), anyString(), anyString(), any(InputStream.class), anyString(), anyString(),anyString(),anyString()); oaiWriteRecordBoltT.execute(anchorTuple, getStormTaskTuple()); assertFailingExpectationWhenCreatingRepresentation(); }
### Question: RemoverInvoker { public void executeInvokerForListOfTasks(String filePath, boolean shouldRemoveErrors) throws IOException { TaskIdsReader reader = new CommaSeparatorReaderImpl(); List<String> taskIds = reader.getTaskIds(filePath); for (String taskId : taskIds) { executeInvokerForSingleTask(Long.valueOf(taskId), shouldRemoveErrors); } } RemoverInvoker(Remover remover); void executeInvokerForSingleTask(long taskId, boolean shouldRemoveErrors); void executeInvokerForListOfTasks(String filePath, boolean shouldRemoveErrors); }### Answer: @Test public void shouldExecuteTheRemovalOnListOfTASKS() throws IOException { removerInvoker.executeInvokerForListOfTasks("src/test/resources/taskIds.csv", true); verify(remover, times(6)).removeNotifications(anyLong()); verify(remover, times(6)).removeStatistics((anyLong())); verify(remover, times(6)).removeErrorReports((anyLong())); }
### Question: AddResultToDataSetBolt extends AbstractDpsBolt { private void assignRepresentationToDataSet(DataSet dataSet, Representation resultRepresentation, String authorizationHeader) throws MCSException { int retries = DEFAULT_RETRIES; while (true) { try { dataSetServiceClient.assignRepresentationToDataSet( dataSet.getProviderId(), dataSet.getId(), resultRepresentation.getCloudId(), resultRepresentation.getRepresentationName(), resultRepresentation.getVersion(), AUTHORIZATION, authorizationHeader); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while assigning record to dataset. Retries left: {}", retries); waitForSpecificTime(); } else { LOGGER.error("Error while assigning record to dataset."); throw e; } } } } AddResultToDataSetBolt(String ecloudMcsAddress); @Override void prepare(); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); }### Answer: @Test public void shouldRetry3TimesBeforeFailingWhenThrowingMCSException() throws MCSException { stormTaskTuple = prepareTupleWithSingleDataSet(); doThrow(MCSException.class).when(dataSetServiceClient).assignRepresentationToDataSet(anyString(), anyString(), anyString(), anyString(), anyString(),eq(AUTHORIZATION),eq(AUTHORIZATION)); verifyMethodExecutionNumber(4, 1); } @Test public void shouldRetry3TimesBeforeFailingWhenThrowingDriverException() throws MCSException { stormTaskTuple = prepareTupleWithSingleDataSet(); doThrow(DriverException.class).when(dataSetServiceClient).assignRepresentationToDataSet(anyString(), anyString(), anyString(), anyString(), anyString(),eq(AUTHORIZATION),eq(AUTHORIZATION)); verifyMethodExecutionNumber(4, 1); }
### Question: QueueFiller { public int addTupleToQueue(StormTaskTuple stormTaskTuple, FileServiceClient fileServiceClient, Representation representation) { int count = 0; final long taskId = stormTaskTuple.getTaskId(); if (representation != null) { for (eu.europeana.cloud.common.model.File file : representation.getFiles()) { String fileUrl = ""; if (!taskStatusChecker.hasKillFlag(taskId)) { try { fileUrl = fileServiceClient.getFileUri(representation.getCloudId(), representation.getRepresentationName(), representation.getVersion(), file.getFileName()).toString(); final StormTaskTuple fileTuple = buildNextStormTuple(stormTaskTuple, fileUrl); tuplesWithFileUrls.put(fileTuple); count++; } catch (Exception e) { LOGGER.warn("Error while getting File URI from MCS {}", e.getMessage()); count++; emitErrorNotification(taskId, fileUrl, "Error while getting File URI from MCS " + e.getMessage(), ""); } } else break; } } else { LOGGER.warn("Problem while reading representation"); } return count; } QueueFiller(TaskStatusChecker taskStatusChecker, SpoutOutputCollector collector, ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls); int addTupleToQueue(StormTaskTuple stormTaskTuple, FileServiceClient fileServiceClient, Representation representation); }### Answer: @Test public void testAddingToQueueSuccessfully() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date()); assertEquals(0, queueFiller.tuplesWithFileUrls.size()); for (int i = 0; i < 10; i++) queueFiller.addTupleToQueue(new StormTaskTuple(), new FileServiceClient(BASE_URL), representation); assertEquals(10, queueFiller.tuplesWithFileUrls.size()); } @Test public void testKillingTheTaskEffectOnQueue() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false, false, false, true); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date()); assertEquals(0, queueFiller.tuplesWithFileUrls.size()); for (int i = 0; i < 10; i++) queueFiller.addTupleToQueue(new StormTaskTuple(), new FileServiceClient(BASE_URL), representation); assertEquals(3, queueFiller.tuplesWithFileUrls.size()); } @Test public void shouldEmitErrorsInCaseOfExceptionWhileGettingTheFiles() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date()); FileServiceClient fileServiceClient = Mockito.mock(FileServiceClient.class); doThrow(MCSException.class).when(fileServiceClient).getFile(anyString(),anyString(),anyString(),anyString()); assertEquals(0, queueFiller.tuplesWithFileUrls.size()); for (int i = 0; i < 10; i++) queueFiller.addTupleToQueue(new StormTaskTuple(), fileServiceClient, representation); assertEquals(0, queueFiller.tuplesWithFileUrls.size()); verify(collector, times(10)).emit(Matchers.eq(AbstractDpsBolt.NOTIFICATION_STREAM_NAME), anyListOf(Object.class)); }
### Question: FileUtil { public static String createFilePath(String folderPath, String fileName, String extension) { String filePtah = folderPath + fileName; if ("".equals(FilenameUtils.getExtension(fileName))) filePtah = filePtah + extension; return filePtah; } static void persistStreamToFile(InputStream inputStream, String folderPath, String fileName, String extension); static String createFilePath(String folderPath, String fileName, String extension); static String createFolder(); static String createZipFolderPath(Date date); }### Answer: @Test public void shouldCreateTheCorrectFilePath() throws Exception { String filePath = FileUtil.createFilePath(FOLDER_PATH, FILE_NAME_WITHOUT_EXTENSION, EXTENSION); assertEquals(filePath, FILE_PATH); filePath = FileUtil.createFilePath(FOLDER_PATH, FILE_NAME_WITH_EXTENSION, EXTENSION); assertEquals(filePath, FILE_PATH); }
### Question: PropertyFileLoader { public void loadDefaultPropertyFile(String defaultPropertyFile, Properties topologyProperties) throws IOException { InputStream propertiesInputStream = Thread.currentThread() .getContextClassLoader().getResourceAsStream(defaultPropertyFile); if (propertiesInputStream == null) throw new FileNotFoundException(); topologyProperties.load(propertiesInputStream); } static void loadPropertyFile(String defaultPropertyFile, String providedPropertyFile, Properties topologyProperties); void loadDefaultPropertyFile(String defaultPropertyFile, Properties topologyProperties); void loadProvidedPropertyFile(String fileName, Properties topologyProperties); }### Answer: @Test public void testLoadingDefaultPropertiesFile() throws FileNotFoundException, IOException { reader.loadDefaultPropertyFile(DEFAULT_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet()) { assertNotNull(e.getKey()); } } @Test(expected = FileNotFoundException.class) public void testLoadingNonExistedDefaultFile() throws FileNotFoundException, IOException { reader.loadDefaultPropertyFile("NON_EXISTED_FILE", topologyProperties); }
### Question: PropertyFileLoader { public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); FileInputStream fileInput = new FileInputStream(file); topologyProperties.load(fileInput); fileInput.close(); } static void loadPropertyFile(String defaultPropertyFile, String providedPropertyFile, Properties topologyProperties); void loadDefaultPropertyFile(String defaultPropertyFile, Properties topologyProperties); void loadProvidedPropertyFile(String fileName, Properties topologyProperties); }### Answer: @Test public void testLoadingProvidedPropertiesFile() throws FileNotFoundException, IOException { reader.loadProvidedPropertyFile(PROVIDED_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet()) { assertNotNull(e.getKey()); } } @Test(expected = FileNotFoundException.class) public void testLoadingNonExistedProvidedFile() throws FileNotFoundException, IOException { reader.loadProvidedPropertyFile("NON_EXISTED_FILE", topologyProperties); }
### Question: FileUtil { public static String createZipFolderPath(Date date) { String folderName = generateFolderName(date); return System.getProperty("user.dir") + "/" + folderName + ZIP_FORMAT_EXTENSION; } static void persistStreamToFile(InputStream inputStream, String folderPath, String fileName, String extension); static String createFilePath(String folderPath, String fileName, String extension); static String createFolder(); static String createZipFolderPath(Date date); }### Answer: @Test public void testCreateZipFolderPath() { Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ssss"); String expectedFolderName = ECLOUD_SUFFIX + "-" + dateFormat.format(date); String folderPath = FileUtil.createZipFolderPath(date); String extension = FilenameUtils.getExtension(folderPath); String folderName = FilenameUtils.getBaseName(folderPath); assertEquals(extension, ZIP_EXTENSION); assertEquals(folderName, expectedFolderName); }
### Question: PropertyFileLoader { public static void loadPropertyFile(String defaultPropertyFile, String providedPropertyFile, Properties topologyProperties) { try { PropertyFileLoader reader = new PropertyFileLoader(); reader.loadDefaultPropertyFile(defaultPropertyFile, topologyProperties); if (!"".equals(providedPropertyFile)) { reader.loadProvidedPropertyFile(providedPropertyFile, topologyProperties); } } catch (IOException e) { LOGGER.error(Throwables.getStackTraceAsString(e)); } } static void loadPropertyFile(String defaultPropertyFile, String providedPropertyFile, Properties topologyProperties); void loadDefaultPropertyFile(String defaultPropertyFile, Properties topologyProperties); void loadProvidedPropertyFile(String fileName, Properties topologyProperties); }### Answer: @Test public void testLoadingFileWhenProvidedPropertyFileNotExisted() throws FileNotFoundException, IOException { PropertyFileLoader.loadPropertyFile(DEFAULT_PROPERTIES_FILE, "NON_EXISTED_PROVIDED_FILE", topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet()) { assertNotNull(e.getKey()); } } @Test public void testLoadingFileWhenDefaultFileNotExists() throws FileNotFoundException, IOException { PropertyFileLoader.loadPropertyFile("NON_EXISTED_DEFAULT_FILE", PROVIDED_PROPERTIES_FILE, topologyProperties); assertTrue(topologyProperties.isEmpty()); }
### Question: CassandraValidationStatisticsService implements ValidationStatisticsReportService { @Override public StatisticsReport getTaskStatisticsReport(long taskId) { StatisticsReport report = cassandraNodeStatisticsDAO.getStatisticsReport(taskId); if (report == null) { List<NodeStatistics> nodeStatistics = cassandraNodeStatisticsDAO.getNodeStatistics(taskId); if (nodeStatistics == null || nodeStatistics.isEmpty()) { return null; } report = new StatisticsReport(taskId, nodeStatistics); cassandraNodeStatisticsDAO.storeStatisticsReport(taskId, report); } return report; } @Override StatisticsReport getTaskStatisticsReport(long taskId); @Override List<NodeReport> getElementReport(long taskId, String elementPath); }### Answer: @Test public void getTaskStatisticsReport() { List<NodeStatistics> stats = prepareStats(); Mockito.when(cassandraNodeStatisticsDAO.getNodeStatistics(TASK_ID)).thenReturn(stats); Mockito.when(cassandraNodeStatisticsDAO.getStatisticsReport(TASK_ID)).thenReturn(null); StatisticsReport actual = cassandraStatisticsService.getTaskStatisticsReport(TASK_ID); Mockito.verify(cassandraNodeStatisticsDAO, Mockito.times(1)).storeStatisticsReport(eq(TASK_ID), Mockito.any(StatisticsReport.class)); Mockito.verify(cassandraNodeStatisticsDAO, Mockito.times(1)).getNodeStatistics(eq(TASK_ID)); assertEquals(TASK_ID, actual.getTaskId()); assertThat(actual.getNodeStatistics().size(), is(2)); assertEquals(stats, actual.getNodeStatistics()); } @Test public void getStoredTaskStatisticsReport() { StatisticsReport report = new StatisticsReport(TASK_ID, prepareStats()); Mockito.when(cassandraNodeStatisticsDAO.getStatisticsReport(TASK_ID)).thenReturn(report); StatisticsReport actual = cassandraStatisticsService.getTaskStatisticsReport(TASK_ID); Mockito.verify(cassandraNodeStatisticsDAO, Mockito.times(0)).storeStatisticsReport(eq(TASK_ID), Mockito.any(StatisticsReport.class)); Mockito.verify(cassandraNodeStatisticsDAO, Mockito.times(0)).getNodeStatistics(eq(TASK_ID)); assertEquals(TASK_ID, actual.getTaskId()); assertThat(actual.getNodeStatistics().size(), is(2)); assertEquals(report, actual); }
### Question: TaskStatusChecker { public boolean hasKillFlag(long taskId) { try { return cache.get(taskId); } catch (ExecutionException e) { LOGGER.info(e.getMessage()); return false; } } private TaskStatusChecker(CassandraConnectionProvider cassandraConnectionProvider); TaskStatusChecker(CassandraTaskInfoDAO taskDAO); static synchronized TaskStatusChecker getTaskStatusChecker(); static synchronized void init(CassandraConnectionProvider cassandraConnectionProvider); boolean hasKillFlag(long taskId); static final int CHECKING_INTERVAL_IN_SECONDS; static final int CONCURRENCY_LEVEL; static final int SIZE; }### Answer: @Test public void testExecutionWithMultipleTasks() throws Exception { when(taskInfoDAO.hasKillFlag(TASK_ID)).thenReturn(false, false, false, true, true); when(taskInfoDAO.hasKillFlag(TASK_ID2)).thenReturn(false, false, true); boolean task1killedFlag = false; boolean task2killedFlag = false; for (int i = 0; i < 8; i++) { if (i < 4) assertFalse(task1killedFlag); if (i < 3) assertFalse(task2killedFlag); task1killedFlag = taskStatusChecker.hasKillFlag(TASK_ID); if (i < 5) task2killedFlag = taskStatusChecker.hasKillFlag(TASK_ID2); Thread.sleep(6000); } verify(taskInfoDAO, times(8)).hasKillFlag(eq(TASK_ID)); verify(taskInfoDAO, times(5)).hasKillFlag(eq(TASK_ID2)); assertTrue(task1killedFlag); assertTrue(task2killedFlag); Thread.sleep(20000); verifyNoMoreInteractions(taskInfoDAO); }
### Question: TaskTupleUtility { protected static boolean isProvidedAsParameter(StormTaskTuple stormTaskTuple, String parameter) { if (stormTaskTuple.getParameter(parameter) != null) { return true; } else { return false; } } static String getParameterFromTuple(StormTaskTuple stormTaskTuple, String parameter); }### Answer: @Test public void parameterIsProvidedTest() { stormTaskTuple.addParameter(PluginParameterKeys.MIME_TYPE, MIME_TYPE); assertTrue(TaskTupleUtility.isProvidedAsParameter(stormTaskTuple, PluginParameterKeys.MIME_TYPE)); } @Test public void parameterIsNotProvidedTest() { assertFalse(TaskTupleUtility.isProvidedAsParameter(stormTaskTuple, PluginParameterKeys.MIME_TYPE)); }
### Question: TaskTupleUtility { public static String getParameterFromTuple(StormTaskTuple stormTaskTuple, String parameter) { String outputValue = PluginParameterKeys.PLUGIN_PARAMETERS.get(parameter); if (isProvidedAsParameter(stormTaskTuple, parameter)) { outputValue = stormTaskTuple.getParameter(parameter); } return outputValue; } static String getParameterFromTuple(StormTaskTuple stormTaskTuple, String parameter); }### Answer: @Test public void getDefaultValueTest() { assertEquals(TaskTupleUtility.getParameterFromTuple(stormTaskTuple, PluginParameterKeys.MIME_TYPE), PluginParameterKeys.PLUGIN_PARAMETERS.get(PluginParameterKeys.MIME_TYPE)); } @Test public void getProvidedValueTest() { stormTaskTuple.addParameter(PluginParameterKeys.MIME_TYPE, MIME_TYPE); assertEquals(TaskTupleUtility.getParameterFromTuple(stormTaskTuple, PluginParameterKeys.MIME_TYPE), MIME_TYPE); }
### Question: FolderCompressor { public static void compress(String folderPath, String zipFolderPath) throws ZipException { File folder = new File(folderPath); ZipUtil.pack(folder, new File(zipFolderPath)); } static void compress(String folderPath, String zipFolderPath); }### Answer: @Test(expected = ZipException.class) public void shouldThrowZipExceptionWhileCompressEmptyFolder() throws Exception { folderPath = FileUtil.createFolder(); File folder = new File(folderPath); assertTrue(folder.isDirectory()); zipFolderPath = FileUtil.createZipFolderPath(new Date()); FolderCompressor.compress(folderPath, zipFolderPath); System.out.println(folderPath); } @Test public void shouldSuccessfullyCompressFolder() throws Exception { folderPath = FileUtil.createFolder(); File folder = new File(folderPath); assertTrue(folder.isDirectory()); InputStream inputStream = IOUtils.toInputStream("some test data for my input stream"); createFile(inputStream, folderPath + "fileName"); zipFolderPath = FileUtil.createZipFolderPath(new Date()); FolderCompressor.compress(folderPath, zipFolderPath); assertNotNull(zipFolderPath); }
### Question: Retriever { public static void retryOnError3Times(String errorMessage, Runnable runnable) { retryOnError3Times(errorMessage,()->{ runnable.run(); return null; }); } static void retryOnError3Times(String errorMessage, Runnable runnable); static V retryOnError3Times(String errorMessage, Callable<V> callable); static void waitForSpecificTime(int milliSecond); }### Answer: @Test public void repeatOnError3Times_callNoThrowsExceptions_validResult() throws Exception { when(call.call()).thenReturn(RESULT); String result = Retriever.retryOnError3Times(ERROR_MESSAGE, call); assertEquals(RESULT, result); } @Test public void repeatOnError3Times_callNoThrowsExceptions_callInvokedOnce() throws Exception { when(call.call()).thenReturn(RESULT); String result = Retriever.retryOnError3Times(ERROR_MESSAGE, call); verify(call).call(); } @Test(expected = IOException.class) public void repeatOnError3Times_callAlwaysThrowsExceptions_catchedException() throws Exception { when(call.call()).thenThrow(IOException.class); Retriever.retryOnError3Times(ERROR_MESSAGE, call); } @Test public void repeatOnError3Timescall_AlwaysThrowsExceptions_callInvoked3Times() throws Exception { when(call.call()).thenThrow(IOException.class); try { Retriever.<String,IOException>retryOnError3Times(ERROR_MESSAGE, call); } catch (IOException e) { e.printStackTrace(); } verify(call,times(4)).call(); }
### Question: TaskStatusSynchronizer { public void synchronizeTasksByTaskStateFromBasicInfo(String topologyName, Collection<String> availableTopics) { List<TaskInfo> tasksFromTaskByTaskStateTableList = tasksByStateDAO.listAllActiveTasksInTopology(topologyName); Map<Long, TaskInfo> tasksFromTaskByTaskStateTableMap = tasksFromTaskByTaskStateTableList.stream().filter(info -> availableTopics.contains(info.getTopicName())) .collect(Collectors.toMap(TaskInfo::getId, Function.identity())); List<TaskInfo> tasksFromBasicInfoTable = taskInfoDAO.findByIds(tasksFromTaskByTaskStateTableMap.keySet()); List<TaskInfo> tasksToCorrect = tasksFromBasicInfoTable.stream().filter(this::isFinished).collect(Collectors.toList()); for (TaskInfo task : tasksToCorrect) { tasksByStateDAO.updateTask(topologyName, task.getId(), tasksFromTaskByTaskStateTableMap.get(task.getId()).getState().toString(), task.getState().toString()); } } TaskStatusSynchronizer(CassandraTaskInfoDAO taskInfoDAO, TasksByStateDAO tasksByStateDAO); void synchronizeTasksByTaskStateFromBasicInfo(String topologyName, Collection<String> availableTopics); }### Answer: @Test public void synchronizeShouldNotFailIfThereIsNoTask() { synchronizer.synchronizeTasksByTaskStateFromBasicInfo(TOPOLOGY_NAME, TOPICS); } @Test public void synchronizedShouldRepairInconsistentData() { when(tasksByStateDAO.listAllActiveTasksInTopology(eq(TOPOLOGY_NAME))).thenReturn(Collections.singletonList(TASK_TOPIC_INFO_1)); when(taskInfoDAO.findByIds(eq(Collections.singleton(1L)))).thenReturn(Collections.singletonList(INFO_1_OF_UNSYNCED)); synchronizer.synchronizeTasksByTaskStateFromBasicInfo(TOPOLOGY_NAME, TOPICS); verify(tasksByStateDAO).updateTask(eq(TOPOLOGY_NAME), eq(1L), eq(TaskState.QUEUED.toString()), eq(TaskState.PROCESSED.toString())); } @Test public void synchronizedShouldNotTouchTasksWithConsistentData() { when(tasksByStateDAO.listAllActiveTasksInTopology(eq(TOPOLOGY_NAME))).thenReturn(Collections.singletonList(TASK_TOPIC_INFO_1)); when(taskInfoDAO.findByIds(eq(Collections.singleton(1L)))).thenReturn(Collections.singletonList(INFO_1)); synchronizer.synchronizeTasksByTaskStateFromBasicInfo(TOPOLOGY_NAME, TOPICS); verify(tasksByStateDAO, never()).updateTask(any(), anyLong(), any(), any()); } @Test public void synchronizedShouldOnlyConcernTasksWithTopicReservedForTopology() { when(tasksByStateDAO.listAllActiveTasksInTopology(eq(TOPOLOGY_NAME))).thenReturn(Collections.singletonList(TASK_TOPIC_INFO_1_UNKNOWN_TOPIC)); synchronizer.synchronizeTasksByTaskStateFromBasicInfo(TOPOLOGY_NAME, TOPICS); verify(taskInfoDAO, never()).findByIds(eq(Collections.singleton(1L))); verify(tasksByStateDAO, never()).updateTask(any(), anyLong(), any(), any()); }
### Question: RecordDownloader { public final String downloadFilesFromDataSet(String providerId, String datasetName, String representationName, int threadsCount) throws InterruptedException, ExecutionException, IOException, DriverException,MimeTypeException, RepresentationNotFoundException { ExecutorService executorService = Executors.newFixedThreadPool(threadsCount); final String folderPath = FileUtil.createFolder(); boolean isSuccess = false; try { RepresentationIterator iterator = dataSetServiceClient.getRepresentationIterator(providerId, datasetName); boolean representationIsFound = false; while (iterator.hasNext()) { final Representation representation = iterator.next(); if (representation.getRepresentationName().equals(representationName)) { representationIsFound = true; downloadFilesInsideRepresentation(executorService, representation, folderPath); } } if (!representationIsFound) throw new RepresentationNotFoundException("The representation " + representationName + " was not found inside the dataset: " + datasetName); isSuccess = true; return folderPath; } finally { executorService.shutdown(); if (!isSuccess) FileUtils.deleteDirectory(new java.io.File(folderPath)); } } RecordDownloader(DataSetServiceClient dataSetServiceClient, FileServiceClient fileServiceClient); final String downloadFilesFromDataSet(String providerId, String datasetName, String representationName, int threadsCount); }### Answer: @Test public void shouldSuccessfullyDownloadTwoRecords() throws Exception { Representation representation = prepareRepresentation(); inputStream = IOUtils.toInputStream("some test data for my input stream"); inputStream2 = IOUtils.toInputStream("some test data for my input stream"); when(dataSetServiceClient.getRepresentationIterator(anyString(), anyString())).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); when(fileServiceClient.getFileUri(CLOUD_ID, REPRESENTATION_NAME, VERSION, FILE)).thenReturn(new URI(FILE_URL)); when(fileServiceClient.getFileUri(CLOUD_ID, REPRESENTATION_NAME, VERSION, FILE + "2")).thenReturn(new URI(FILE_URL2)); when(fileServiceClient.getFile(FILE_URL)).thenReturn(inputStream); when(fileServiceClient.getFile(FILE_URL2)).thenReturn(inputStream2); String folderPtah = recordDownloader.downloadFilesFromDataSet(DATA_PROVIDER, DATASET_NAME, REPRESENTATION_NAME,1); assertNotNull(folderPtah); java.io.File folder = new java.io.File(folderPtah); assert (folder.isDirectory()); assertEquals(folder.list().length, 2); FileUtils.forceDelete(new java.io.File(folderPtah)); } @Test(expected = RepresentationNotFoundException.class) public void shouldThrowRepresentationNotFoundException() throws Exception { when(dataSetServiceClient.getRepresentationIterator(anyString(), anyString())).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(false, false); recordDownloader.downloadFilesFromDataSet(DATA_PROVIDER, DATASET_NAME, EMPTY_REPRESENTATION,1); }
### Question: ReportResource { @GetMapping(path = "{taskId}/statistics", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") public StatisticsReport getTaskStatisticsReport( @PathVariable String topologyName, @PathVariable String taskId) throws AccessDeniedOrTopologyDoesNotExistException, AccessDeniedOrObjectDoesNotExistException { assertContainTopology(topologyName); reportService.checkIfTaskExists(taskId, topologyName); return validationStatisticsService.getTaskStatisticsReport(Long.parseLong(taskId)); } @GetMapping(path = "{taskId}/reports/details", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") List<SubTaskInfo> getTaskDetailedReport( @PathVariable String taskId, @PathVariable final String topologyName, @RequestParam(defaultValue = "1") @Min(1) int from, @RequestParam(defaultValue = "100") @Min(1) int to); @GetMapping(path = "{taskId}/reports/errors", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") TaskErrorsInfo getTaskErrorReport( @PathVariable String taskId, @PathVariable final String topologyName, @RequestParam(required = false) String error, @RequestParam(defaultValue = "0") int idsCount); @RequestMapping(method = { RequestMethod.HEAD }, path = "{taskId}/reports/errors") @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") Boolean checkIfErrorReportExists( @PathVariable String taskId, @PathVariable final String topologyName); @GetMapping(path = "{taskId}/statistics", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") StatisticsReport getTaskStatisticsReport( @PathVariable String topologyName, @PathVariable String taskId); @GetMapping(path = "{taskId}/reports/element", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") List<NodeReport> getElementsValues( @PathVariable String topologyName, @PathVariable String taskId, @NotNull @RequestParam("path") String elementPath); static final String TASK_PREFIX; }### Answer: @Test public void shouldGetStatisticReport() throws Exception { when(validationStatisticsService.getTaskStatisticsReport(TASK_ID)).thenReturn(new StatisticsReport(TASK_ID, null)); when(topologyManager.containsTopology(anyString())).thenReturn(true); ResultActions response = mockMvc.perform(get(VALIDATION_STATISTICS_REPORT_WEB_TARGET, TOPOLOGY_NAME, TASK_ID)); System.err.println(content().string("taskId")); response .andExpect(status().isOk()) .andExpect(jsonPath("taskId", org.hamcrest.Matchers.is((int)TASK_ID))); } @Test public void shouldReturn405WhenStatisticsRequestedButTopologyNotFound() throws Exception { when(validationStatisticsService.getTaskStatisticsReport(TASK_ID)).thenReturn(new StatisticsReport(TASK_ID, null)); when(topologyManager.containsTopology(anyString())).thenReturn(false); ResultActions response = mockMvc.perform( get(VALIDATION_STATISTICS_REPORT_WEB_TARGET, TOPOLOGY_NAME, TASK_ID) ); response.andExpect(status().isMethodNotAllowed()); }
### Question: UnfinishedTasksExecutor { @PostConstruct public void reRunUnfinishedTasks() { LOGGER.info("Will restart all pending tasks"); List<TaskInfo> results = findProcessingByRestTasks(); List<TaskInfo> tasksForCurrentMachine = findTasksForCurrentMachine(results); resumeExecutionFor(tasksForCurrentMachine); } UnfinishedTasksExecutor(TasksByStateDAO tasksDAO, CassandraTaskInfoDAO taskInfoDAO, TaskSubmitterFactory taskSubmitterFactory, String applicationIdentifier, TaskStatusUpdater taskStatusUpdater); @PostConstruct void reRunUnfinishedTasks(); static final List<TaskState> RESUMABLE_TASK_STATES; }### Answer: @Test public void shouldNotStartExecutionForEmptyTasksList() { List<TaskInfo> unfinishedTasks = new ArrayList<>(); Mockito.reset(cassandraTasksDAO); when(cassandraTasksDAO.findTasksInGivenState(Mockito.any(List.class))).thenReturn(unfinishedTasks); unfinishedTasksExecutor.reRunUnfinishedTasks(); Mockito.verify(cassandraTasksDAO, Mockito.times(1)).findTasksInGivenState(UnfinishedTasksExecutor.RESUMABLE_TASK_STATES); } @Test public void shouldStartExecutionForOneTasks() throws TaskInfoDoesNotExistException { List<TaskInfo> unfinishedTasks = new ArrayList<>(); TaskInfo taskInfo = prepareTestTask(); unfinishedTasks.add(taskInfo); Mockito.reset(cassandraTasksDAO); Mockito.reset(taskSubmitterFactory); when(cassandraTasksDAO.findTasksInGivenState(UnfinishedTasksExecutor.RESUMABLE_TASK_STATES)).thenReturn(unfinishedTasks); when(cassandraTaskInfoDAO.findById(1L)).thenReturn(Optional.of(taskInfo)); when(taskSubmitterFactory.provideTaskSubmitter(Mockito.any(SubmitTaskParameters.class))).thenReturn(Mockito.mock(TaskSubmitter.class)); unfinishedTasksExecutor.reRunUnfinishedTasks(); Mockito.verify(cassandraTasksDAO, Mockito.times(1)).findTasksInGivenState(UnfinishedTasksExecutor.RESUMABLE_TASK_STATES); Mockito.verify(taskSubmitterFactory, Mockito.times(1)).provideTaskSubmitter(Mockito.any(SubmitTaskParameters.class)); } @Test public void shouldStartExecutionForTasksThatBelongsToGivenMachine() throws TaskInfoDoesNotExistException { List<TaskInfo> unfinishedTasks = new ArrayList<>(); TaskInfo taskInfo = prepareTestTask(); unfinishedTasks.add(taskInfo); unfinishedTasks.add(prepareTestTaskForAnotherMachine()); Mockito.reset(cassandraTasksDAO); Mockito.reset(taskSubmitterFactory); when(cassandraTasksDAO.findTasksInGivenState(UnfinishedTasksExecutor.RESUMABLE_TASK_STATES)).thenReturn(unfinishedTasks); when(cassandraTaskInfoDAO.findById(1L)).thenReturn(Optional.of(taskInfo)); when(taskSubmitterFactory.provideTaskSubmitter(Mockito.any(SubmitTaskParameters.class))).thenReturn(Mockito.mock(TaskSubmitter.class)); unfinishedTasksExecutor.reRunUnfinishedTasks(); Mockito.verify(cassandraTasksDAO, Mockito.times(1)).findTasksInGivenState(UnfinishedTasksExecutor.RESUMABLE_TASK_STATES); Mockito.verify(taskSubmitterFactory, Mockito.times(1)).provideTaskSubmitter(Mockito.any(SubmitTaskParameters.class)); }
### Question: RowsValidatorJob implements Callable<Void> { @Override public Void call() throws Exception { validateRows(); return null; } RowsValidatorJob(Session session, List<String> primaryKeys, BoundStatement matchingBoundStatement, List<Row> rows); @Override Void call(); }### Answer: @Test public void shouldExecuteTheSessionWithoutRetry() throws Exception { ResultSet resultSet = mock(ResultSet.class); when(resultSet.one()).thenReturn(rows.get(0)); when(resultSet.one().getLong("count")).thenReturn(1l); when(session.execute(matchingBoundStatement)).thenReturn(resultSet); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(matchingBoundStatement.preparedStatement()).thenReturn(preparedStatement); when(preparedStatement.getQueryString()).thenReturn("Query String"); final RowsValidatorJob job = new RowsValidatorJob(session, primaryKeys, matchingBoundStatement, rows); job.call(); verify(session, times(1)).execute(any(BoundStatement.class)); } @Test public void shouldExecuteTheSessionWithMaximumRetry() throws Exception { ResultSet resultSet = mock(ResultSet.class); when(resultSet.one()).thenReturn(rows.get(0)); when(resultSet.one().getLong("count")).thenReturn(0l); final Session session = mock(Session.class); when(session.execute(matchingBoundStatement)).thenReturn(resultSet); final RowsValidatorJob job = new RowsValidatorJob(session, primaryKeys, matchingBoundStatement, rows); try { job.call(); assertTrue(false); } catch (Exception e) { } verify(session, times(5)).execute(any(BoundStatement.class)); } @Test public void shouldThrowAnExceptionWithCorrectMessage() throws Exception { ResultSet resultSet = mock(ResultSet.class); when(resultSet.one()).thenReturn(rows.get(0)); when(resultSet.one().getLong("count")).thenReturn(0l); final Session session = mock(Session.class); when(session.execute(matchingBoundStatement)).thenReturn(resultSet); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(matchingBoundStatement.preparedStatement()).thenReturn(preparedStatement); when(preparedStatement.getQueryString()).thenReturn("Select count(*) From TableName"); final RowsValidatorJob job = new RowsValidatorJob(session, primaryKeys, matchingBoundStatement, rows); try { job.call(); } catch (Exception e) { assertEquals("The data doesn't fully match!. The exception was thrown for this query: Select count(*) From TableName Using these values(Item1)", e.getMessage()); } verify(session, times(5)).execute(any(BoundStatement.class)); }
### Question: TopologiesTopicsParser { public Map<String, List<String>> parse(String topicsList) { if (isInputValid(topicsList)) { List<String> topologies = extractTopologies(topicsList); return extractTopics(topologies); } else { throw new RuntimeException("Topics list is not valid"); } } Map<String, List<String>> parse(String topicsList); }### Answer: @Test public void shouldSuccessfullyParseTopicsList() { TopologiesTopicsParser t = new TopologiesTopicsParser(); Map<String, List<String>> topologiesTopicsList = t.parse(VALID_INPUT); Assert.assertEquals(2, topologiesTopicsList.size()); Assert.assertNotNull(topologiesTopicsList.get("oai_topology")); Assert.assertNotNull(topologiesTopicsList.get("another_topology")); Assert.assertEquals(3, topologiesTopicsList.get("oai_topology").size()); Assert.assertEquals(2, topologiesTopicsList.get("another_topology").size()); } @Test public void shouldSuccessfullyParseTopicsList_1() { TopologiesTopicsParser t = new TopologiesTopicsParser(); Map<String, List<String>> topologiesTopicsList = t.parse(VALID_INPUT_1); Assert.assertEquals(2, topologiesTopicsList.size()); Assert.assertNotNull(topologiesTopicsList.get("oai_topology")); Assert.assertNotNull(topologiesTopicsList.get("another_topology")); Assert.assertEquals(3, topologiesTopicsList.get("oai_topology").size()); Assert.assertEquals(0, topologiesTopicsList.get("another_topology").size()); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionForInvalidTopicsList_1() { TopologiesTopicsParser t = new TopologiesTopicsParser(); t.parse(INVALID_INPUT_1); }
### Question: GhostTaskService { public List<TaskInfo> findGhostTasks() { return findTasksInGivenStates(TaskState.PROCESSING_BY_REST_APPLICATION, TaskState.QUEUED). filter(this::isGhost).collect(Collectors.toList()); } GhostTaskService(Environment environment); @Scheduled(cron = "0 0 * * * *") void serviceTask(); List<TaskInfo> findGhostTasks(); }### Answer: @Test public void findGhostTasksReturnsEmptyListIfNotTaskActive() { assertThat(service.findGhostTasks(), empty()); } @Test public void findGhostTasksReturnsTaskIfItIsOldSentAndNoStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(OLD_SENT_NO_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), contains(OLD_SENT_NO_STARTED_TASK_INFO_1)); } @Test public void findGhostTasksReturnsTaskIfItIsOldSentAndOldStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(OLD_SENT_OLD_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), contains(OLD_SENT_OLD_STARTED_TASK_INFO_1)); } @Test public void findGhostTasksShouldIgnoreTasksThatNewlySentAndNewStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(OLD_SENT_NEWLY_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), empty()); } @Test public void findGhostTasksShouldIgnoreTasksThatOldSentButNewStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(NEWLY_SENT_NEWLY_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), empty()); } @Test public void findGhostTasksShouldIgnoreTasksThatNewlySentAndNotStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(NEWLY_SENT_NO_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), empty()); } @Test public void findGhostTasksShouldIgnoreTasksThatNotReserveTopicBelongingToTopology() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1_UNKNONW_TOPIC)); when(taskInfoDAO.findById(anyLong())).thenReturn(Optional.of(OLD_SENT_NO_STARTED_TASK_INFO_1)); assertThat(service.findGhostTasks(), empty()); }
### Question: DatasetFilesCounter extends FilesCounter { public int getFilesCount(DpsTask task) throws TaskSubmissionException { String providedTaskId = task.getParameter(PluginParameterKeys.PREVIOUS_TASK_ID); if (providedTaskId==null) return UNKNOWN_EXPECTED_SIZE; try { long taskId = Long.parseLong(providedTaskId); TaskInfo taskInfo = taskInfoDAO.findById(taskId).orElseThrow(TaskInfoDoesNotExistException::new); return taskInfo.getProcessedElementCount(); } catch (NumberFormatException e) { LOGGER.error("The provided previous task id {} is not long ", providedTaskId); return UNKNOWN_EXPECTED_SIZE; } catch (TaskInfoDoesNotExistException e) { LOGGER.error("Task with taskId {} doesn't exist ", providedTaskId); return UNKNOWN_EXPECTED_SIZE; } catch (Exception e) { LOGGER.error("he task was dropped because of {} ", e.getMessage()); throw new TaskSubmissionException("The task was dropped while counting the files number because of " + e.getMessage()); } } DatasetFilesCounter(CassandraTaskInfoDAO taskInfoDAO); int getFilesCount(DpsTask task); static final int UNKNOWN_EXPECTED_SIZE; }### Answer: @Test public void shouldReturnProcessedFiles() throws Exception { TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, "", EXPECTED_SIZE, EXPECTED_SIZE, 0, 0, new Date(), new Date(), new Date()); when(taskInfoDAO.findById(TASK_ID)).thenReturn(Optional.of(taskInfo)); dpsTask.addParameter(PluginParameterKeys.PREVIOUS_TASK_ID, String.valueOf(TASK_ID)); int expectedFilesCount = datasetFilesCounter.getFilesCount(dpsTask); assertEquals(EXPECTED_SIZE, expectedFilesCount); } @Test public void shouldReturnedDefaultFilesCountWhenNoPreviousTaskIdIsProvided() throws Exception { int expectedFilesCount = datasetFilesCounter.getFilesCount(dpsTask); assertEquals(DEFAULT_FILES_COUNT, expectedFilesCount); } @Test public void shouldReturnedDefaultFilesCountWhenPreviousTaskIdIsNotLongValue() throws Exception { int expectedFilesCount = datasetFilesCounter.getFilesCount(dpsTask); dpsTask.addParameter(PluginParameterKeys.PREVIOUS_TASK_ID, "Not long value"); assertEquals(DEFAULT_FILES_COUNT, expectedFilesCount); } @Test public void shouldReturnedDefaultFilesCountWhenPreviousTaskIdDoesNotExist() throws Exception { dpsTask.addParameter(PluginParameterKeys.PREVIOUS_TASK_ID, String.valueOf(TASK_ID)); doReturn(Optional.empty()).when(taskInfoDAO).findById(TASK_ID); int expectedFilesCount = datasetFilesCounter.getFilesCount(dpsTask); assertEquals(DEFAULT_FILES_COUNT, expectedFilesCount); } @Test(expected = TaskSubmissionException.class) public void shouldThrowExceptionWhenQueryingDatabaseUsingPreviousTaskIdThrowAnExceptionOtherThanTaskInfoDoesNotExistException() throws Exception { dpsTask.addParameter(PluginParameterKeys.PREVIOUS_TASK_ID, String.valueOf(TASK_ID)); doThrow(Exception.class).when(taskInfoDAO).findById(TASK_ID); datasetFilesCounter.getFilesCount(dpsTask); }
### Question: ValidatorFactory { public static Validator getValidator(ValidatorType type) { if (type == ValidatorType.KEYSPACE) return new KeyspaceValidator(); if (type == ValidatorType.TABLE) return new TableValidator(); return null; } static Validator getValidator(ValidatorType type); }### Answer: @Test public void TestValidator() { Validator validator = ValidatorFactory.getValidator(ValidatorType.KEYSPACE); assertTrue(validator instanceof KeyspaceValidator); validator = ValidatorFactory.getValidator(ValidatorType.TABLE); assertTrue(validator instanceof TableValidator); }
### Question: DepublicationFilesCounter extends FilesCounter { @Override public int getFilesCount(DpsTask task) throws TaskSubmissionException { if (task.getParameter(PluginParameterKeys.RECORD_IDS_TO_DEPUBLISH) != null) { return calculateRecordsNumber(task); } if (task.getParameter(PluginParameterKeys.METIS_DATASET_ID) != null) { return calculateDatasetSize(task); } throw new TaskSubmissionException("Can't evaluate task expected size! Needed parameters not found in the task"); } DepublicationFilesCounter(DatasetDepublisher depublisher); @Override int getFilesCount(DpsTask task); }### Answer: @Test public void shouldCountRecords() throws Exception { int randomNum = ThreadLocalRandom.current().nextInt(1, DATASET_EXPECTED_SIZE); StringBuilder records = new StringBuilder("r1"); for(int index = 2; index <= randomNum; index++) { records.append(", r"); records.append(index); } DpsTask dpsTask = new DpsTask(); dpsTask.addParameter(METIS_DATASET_ID, ""); dpsTask.addParameter(RECORD_IDS_TO_DEPUBLISH, records.toString()); DepublicationFilesCounter depublicationFilesCounter = new DepublicationFilesCounter(datasetDepublisher); int count = depublicationFilesCounter.getFilesCount(dpsTask); assertEquals(randomNum, count); } @Test public void shouldCountEntireDataset() throws Exception { DpsTask dpsTask = new DpsTask(); dpsTask.addParameter(METIS_DATASET_ID, ""); DepublicationFilesCounter depublicationFilesCounter = new DepublicationFilesCounter(datasetDepublisher); int count = depublicationFilesCounter.getFilesCount(dpsTask); assertEquals(DATASET_EXPECTED_SIZE, count); }
### Question: DepublicationService { public void depublishDataset(SubmitTaskParameters parameters) { try { long taskId = parameters.getTask().getTaskId(); checkTaskKilled(taskId); Future<Integer> future = depublisher.executeDatasetDepublicationAsync(parameters); waitForFinish(future, parameters); } catch (SubmitingTaskWasKilled e) { LOGGER.warn(e.getMessage(), e); } catch (Exception e) { saveErrorResult(parameters, e); } } DepublicationService(TaskStatusChecker taskStatusChecker, DatasetDepublisher depublisher, TaskStatusUpdater taskStatusUpdater, RecordStatusUpdater recordStatusUpdater); void depublishDataset(SubmitTaskParameters parameters); void depublishIndividualRecords(SubmitTaskParameters parameters); }### Answer: @Test public void verifyUseValidEnvironmentIfNoAlternativeEnvironmentParameterSet() throws IndexingException, URISyntaxException { service.depublishDataset(parameters); verify(metisIndexerFactory, atLeast(1)).openIndexer(eq(false)); verify(metisIndexerFactory, never()).openIndexer(eq(true)); } @Test public void verifyUseAlternativeEnvironmentIfAlternativeEnvironmentParameterSet() throws IndexingException, URISyntaxException { task.addParameter(PluginParameterKeys.METIS_USE_ALT_INDEXING_ENV, "true"); service.depublishDataset(parameters); verify(metisIndexerFactory, atLeast(1)).openIndexer(eq(true)); verify(metisIndexerFactory, never()).openIndexer(eq(false)); } @Test public void verifyTaskRemoveInvokedOnIndexer() throws IndexingException { service.depublishDataset(parameters); verify(indexer).removeAll(eq(DATASET_METIS_ID), isNull(Date.class)); assertTaskSucceed(); } @Test public void verifyWaitForAllRowsRemoved() throws IndexingException { AtomicBoolean allRowsRemoved = new AtomicBoolean(false); StopWatch watch = StopWatch.createStarted(); when(indexer.countRecords(anyString())).then(r -> { allRowsRemoved.set(watch.getTime() > WAITING_FOR_COMPLETE_TIME); if (allRowsRemoved.get()) { return 0; } else { return EXPECTED_SIZE; } }); service.depublishDataset(parameters); assertTaskSucceed(); assertTrue(allRowsRemoved.get()); } @Test public void verifyTaskRemoveNotInvokedIfTaskWereKilledBefore() throws IndexingException { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(true); service.depublishDataset(parameters); verify(indexer, never()).removeAll(eq(DATASET_METIS_ID), isNull(Date.class)); verify(updater, never()).setTaskCompletelyProcessed(eq(TASK_ID), anyString()); } @Test public void verifyTaskFailedWhenRemoveMethodThrowsException() throws IndexingException { when(indexer.removeAll(anyString(), any(Date.class))).thenThrow(new IndexerRelatedIndexingException("Indexer exception!")); service.depublishDataset(parameters); assertTaskFailed(); } @Test public void verifyTaskFailedWhenRemovedRowCountNotMatchExpected() throws IndexingException { when(indexer.removeAll(anyString(), any(Date.class))).thenReturn(EXPECTED_SIZE + 2); service.depublishDataset(parameters); assertTaskFailed(); }
### Question: KeyspaceValidator implements Validator { @Override public void validate(CassandraConnectionProvider sourceCassandraConnectionProvider, CassandraConnectionProvider targetCassandraConnectionProvider, String sourceTableName, String targetTableName, int threadsCount) throws InterruptedException, ExecutionException { ExecutorService executorService = null; try { Iterator<TableMetadata> tmIterator = sourceCassandraConnectionProvider.getMetadata().getKeyspace(sourceCassandraConnectionProvider.getKeyspaceName()).getTables().iterator(); final Set<Callable<Void>> tableValidatorJobs = new HashSet<>(); executorService = Executors.newFixedThreadPool(threadsCount); while (tmIterator.hasNext()) { CassandraConnectionProvider newSourceCassandraConnectionProvider = new CassandraConnectionProvider(sourceCassandraConnectionProvider); CassandraConnectionProvider newTargetCassandraConnectionProvider = new CassandraConnectionProvider(targetCassandraConnectionProvider); DataValidator dataValidator = new DataValidator(newSourceCassandraConnectionProvider, newTargetCassandraConnectionProvider); TableMetadata t = tmIterator.next(); LOGGER.info("Checking data integrity between source table " + t.getName() + " and target table " + t.getName()); tableValidatorJobs.add(new TableValidatorJob(dataValidator, t.getName(), t.getName(), threadsCount)); } executorService.invokeAll(tableValidatorJobs); } finally { if (executorService != null) executorService.shutdown(); if (sourceCassandraConnectionProvider != null) sourceCassandraConnectionProvider.closeConnections(); if (targetCassandraConnectionProvider != null) targetCassandraConnectionProvider.closeConnections(); } } @Override void validate(CassandraConnectionProvider sourceCassandraConnectionProvider, CassandraConnectionProvider targetCassandraConnectionProvider, String sourceTableName, String targetTableName, int threadsCount); }### Answer: @Test public void verifyJobExecution() throws Exception { CassandraConnectionProvider cassandraConnectionProvider = mock(CassandraConnectionProvider.class); int threadCount = 1; String tableName = "tableName"; KeyspaceValidator keyspaceValidator = new KeyspaceValidator(); Metadata metadata = mock(Metadata.class); KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class); when(cassandraConnectionProvider.getMetadata()).thenReturn(metadata); when(cassandraConnectionProvider.getKeyspaceName()).thenReturn("keyspace"); when(metadata.getKeyspace(anyString())).thenReturn(keyspaceMetadata); TableMetadata tableMetadata = mock(TableMetadata.class); when(tableMetadata.getName()).thenReturn(tableName); Collection<TableMetadata> tableMetadataList = Arrays.asList(tableMetadata); when(keyspaceMetadata.getTables()).thenReturn(tableMetadataList); PowerMockito.whenNew(CassandraConnectionProvider.class).withAnyArguments().thenReturn(cassandraConnectionProvider); ExecutorService executorService = mock(ExecutorService.class); PowerMockito.mockStatic(Executors.class); when(Executors.newFixedThreadPool(threadCount)).thenReturn(executorService); keyspaceValidator.validate(cassandraConnectionProvider, cassandraConnectionProvider, tableName, tableName, threadCount); verify(executorService, times(1)).invokeAll(any(Collection.class)); }
### Question: DpsClient { public long submitTask(DpsTask task, String topologyName) throws DpsException { Response resp = null; try { resp = client.target(dpsUrl) .path(TASKS_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .request() .post(Entity.json(task)); if (resp.getStatus() == Response.Status.CREATED.getStatusCode()) { return getTaskId(resp.getLocation()); } else { LOGGER.error("Submit Task Was not successful"); throw handleException(resp); } } finally { closeResponse(resp); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Betamax(tape = "DPSClient/submitTaskAndFail") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public final void shouldThrowAnExceptionWhenCannotSubmitATask() throws Exception { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); DpsTask task = prepareDpsTask(); dpsClient.submitTask(task, TOPOLOGY_NAME); } @Betamax(tape = "DPSClient/permitAndSubmitTaskReturnBadURI") @Test(expected = RuntimeException.class) public final void shouldThrowAnExceptionWhenReturnedTaskIdIsNotParsable() throws Exception { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); DpsTask task = prepareDpsTask(); dpsClient.submitTask(task, TOPOLOGY_NAME); }
### Question: DpsClient { public Response.StatusType topologyPermit(String topologyName, String username) throws DpsException { Form form = new Form(); form.param("username", username); Response resp = null; try { resp = client.target(dpsUrl) .path(PERMIT_TOPOLOGY_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .request() .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (resp.getStatus() == Response.Status.OK.getStatusCode()) { return resp.getStatusInfo(); } else { LOGGER.error("Granting permission was not successful"); throw handleException(resp); } } finally { closeResponse(resp); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient/permitForNotDefinedTopologyTest") public final void shouldNotBeAbleToPermitUserForNotDefinedTopology() throws Exception { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); try { dpsClient.topologyPermit(NOT_DEFINED_TOPOLOGY_NAME, "user"); fail(); } catch (AccessDeniedOrTopologyDoesNotExistException e) { assertThat(e.getLocalizedMessage(), equalTo("The topology doesn't exist")); } }
### Question: DpsClient { public TaskInfo getTaskProgress(String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(TASK_PROGRESS_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(TaskInfo.class); } else { LOGGER.error("Task progress cannot be read"); throw handleException(response); } } finally { closeResponse(response); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient/getTaskProgressTest") public final void shouldReturnedProgressReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, "", 1, 0, 0, 0, null, null, null); assertThat(dpsClient.getTaskProgress(TOPOLOGY_NAME, TASK_ID), is(taskInfo)); }
### Question: DpsClient { public List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(DETAILED_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().get(); return handleResponse(response); } finally { closeResponse(response); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient_getTaskDetailsReportTest") public final void shouldReturnedDetailsReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); SubTaskInfo subTaskInfo = new SubTaskInfo(1, "resource", RecordState.SUCCESS, "", "", "result"); List<SubTaskInfo> taskInfoList = new ArrayList<>(1); taskInfoList.add(subTaskInfo); assertThat(dpsClient.getDetailedTaskReport(TOPOLOGY_NAME, TASK_ID), is(taskInfoList)); }
### Question: DpsClient { public TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(ERRORS_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .queryParam(ERROR, error) .queryParam(IDS_COUNT, idsCount) .request().get(); return handleErrorResponse(response); } finally { closeResponse(response); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient_shouldReturnedGeneralErrorReport") public final void shouldReturnedGeneralErrorReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); TaskErrorsInfo report = createErrorInfo(TASK_ID, false); assertThat(dpsClient.getTaskErrorsReport(TOPOLOGY_NAME, TASK_ID, null, 0), is(report)); } @Test @Betamax(tape = "DPSClient_shouldReturnedSpecificErrorReport") public final void shouldReturnedSpecificErrorReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); TaskErrorsInfo report = createErrorInfo(TASK_ID, true); assertThat(dpsClient.getTaskErrorsReport(TOPOLOGY_NAME, TASK_ID, ERROR_TYPE, 100), is(report)); }
### Question: CassandraHelper { public static BoundStatement prepareBoundStatementForMatchingTargetTable(CassandraConnectionProvider cassandraConnectionProvider, String targetTableName, List<String> primaryKeys) { String matchCountStatementCQL = CQLBuilder.getMatchCountStatementFromTargetTable(targetTableName, primaryKeys); PreparedStatement matchCountStatementCQLStatement = cassandraConnectionProvider.getSession().prepare(matchCountStatementCQL); matchCountStatementCQLStatement.setConsistencyLevel(cassandraConnectionProvider.getConsistencyLevel()); return matchCountStatementCQLStatement.bind(); } static BoundStatement prepareBoundStatementForMatchingTargetTable(CassandraConnectionProvider cassandraConnectionProvider, String targetTableName, List<String> primaryKeys); static ResultSet getPrimaryKeysFromSourceTable(CassandraConnectionProvider cassandraConnectionProvider, String sourceTableName, List<String> primaryKeys); static List<String> getPrimaryKeysNames(CassandraConnectionProvider cassandraConnectionProvider, String tableName, String selectColumnNames); }### Answer: @Test public void prepareBoundStatementForMatchingTargetTableTest() { assertThat(CassandraHelper.prepareBoundStatementForMatchingTargetTable(cassandraConnectionProvider, "table", primaryKeys), is(boundStatement)); }
### Question: DpsClient { public boolean checkIfErrorReportExists(final String topologyName, final long taskId) { Response response = null; try { response = client .target(dpsUrl) .path(ERRORS_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().head(); return response.getStatus() == Response.Status.OK.getStatusCode(); } finally { closeResponse(response); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient_shouldReturnTrueWhenErrorsReportExists") public final void shouldReturnTrueWhenErrorsReportExists() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); assertTrue(dpsClient.checkIfErrorReportExists(TOPOLOGY_NAME, TASK_ID)); } @Test @Betamax(tape = "DPSClient_shouldReturnFalseWhenErrorsReportDoesNotExists") public final void shouldReturnFalseWhenErrorsReportDoesNotExists() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); assertFalse(dpsClient.checkIfErrorReportExists(TOPOLOGY_NAME, TASK_ID)); }
### Question: DpsClient { public List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath) throws DpsException { Response getResponse = null; try { getResponse = client .target(dpsUrl) .path(ELEMENT_REPORT) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId).queryParam("path", elementPath) .request().get(); return handleElementReportResponse(getResponse); } finally { closeResponse(getResponse); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient_shouldReturnElementReport") public void shouldGetTheElementReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); List<NodeReport> nodeReports = dpsClient.getElementReport(TOPOLOGY_NAME, TASK_ID, " assertNotNull(nodeReports); assertEquals(1, nodeReports.size()); assertEquals("Lattakia", nodeReports.get(0).getNodeValue()); assertEquals(10, nodeReports.get(0).getOccurrence()); List<AttributeStatistics> attributes = nodeReports.get(0).getAttributeStatistics(); assertNotNull(attributes); assertEquals(1, attributes.size()); assertEquals(" assertEquals(10, attributes.get(0).getOccurrence()); assertEquals("en", attributes.get(0).getValue()); }
### Question: DpsClient { public StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client.target(dpsUrl).path(STATISTICS_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName).resolveTemplate(TASK_ID, taskId).request() .get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(StatisticsReport.class); } else { LOGGER.error("Task statistics report cannot be read"); throw handleException(response); } } finally { closeResponse(response); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test(expected = AccessDeniedOrTopologyDoesNotExistException.class) @Betamax(tape = "DPSClient_shouldThrowExceptionForStatisticsWhenTopologyDoesNotExist") public void shouldThrowExceptionForStatistics() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); dpsClient.getTaskStatisticsReport(NOT_DEFINED_TOPOLOGY_NAME, TASK_ID); } @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "DPSClient_shouldThrowExceptionForStatisticsWhenTaskIdDoesNotExistOrUnAccessible") public void shouldThrowExceptionForStatisticsWhenTaskIdIsUnAccessible() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); dpsClient.getTaskStatisticsReport(TOPOLOGY_NAME, TASK_ID); }
### Question: DpsClient { public void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters) throws DpsException { Response resp = null; try { resp = client.target(dpsUrl) .path(TASK_CLEAN_DATASET_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request() .post(Entity.json(dataSetCleanerParameters)); if (resp.getStatus() != Response.Status.OK.getStatusCode()) { LOGGER.error("Cleaning a dataset was not successful"); throw handleException(resp); } } finally { closeResponse(resp); } } DpsClient(final String dpsUrl, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl, final String username, final String password); DpsClient(final String dpsUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); DpsClient(final String dpsUrl); long submitTask(DpsTask task, String topologyName); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters); void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters, String key, String value); Response.StatusType topologyPermit(String topologyName, String username); TaskInfo getTaskProgress(String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId); List<SubTaskInfo> getDetailedTaskReportBetweenChunks(final String topologyName, final long taskId, int from, int to); List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath); TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount); boolean checkIfErrorReportExists(final String topologyName, final long taskId); StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId); String killTask(final String topologyName, final long taskId, String info); void close(); }### Answer: @Test @Betamax(tape = "DPSClient_shouldCleanIndexingDataSet") public void shouldCleanIndexingDataSet() throws DpsException { DpsClient dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); dpsClient.cleanMetisIndexingDataset(TOPOLOGY_NAME, TASK_ID, new DataSetCleanerParameters()); } @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "DPSClient_shouldThrowAccessDeniedWhenTaskIdDoesNotExistOrUnAccessible") public void shouldThrowAccessDeniedWhenTaskIdDoesNotExistOrUnAccessible() throws DpsException { DpsClient dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); long missingTaskId = 111; dpsClient.cleanMetisIndexingDataset(TOPOLOGY_NAME, missingTaskId, new DataSetCleanerParameters()); } @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "DPSClient_shouldThrowAccessDeniedWhenTopologyDoesNotExist") public void shouldThrowAccessDeniedWhenTopologyDoesNotExist() throws DpsException { DpsClient dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); String wrongTopologyName = "wrongTopology"; dpsClient.cleanMetisIndexingDataset(wrongTopologyName, TASK_ID, new DataSetCleanerParameters()); }
### Question: XmlXPath { InputStream xpathToStream(XPathExpression expr) throws HarvesterException { try { final InputSource inputSource = getInputSource(); final ArrayList<NodeInfo> result = (ArrayList<NodeInfo>) expr.evaluate(inputSource, XPathConstants.NODESET); return convertToStream(result); } catch (XPathExpressionException | TransformerException e) { throw new HarvesterException("Cannot xpath XML!", e); } } XmlXPath(String input); }### Answer: @Test public void shouldFilterOaiDcResponse() throws IOException, HarvesterException { final String fileContent = WiremockHelper.getFileContent("/sampleOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); final InputStream result = new XmlXPath(content).xpathToStream(expr); final String actual = TestHelper.convertToString(result); assertThat(actual, TestHelper.isSimilarXml(WiremockHelper.getFileContent("/expectedOaiRecord.xml"))); } @Test public void shouldThrowExceptionNonSingleOutputCandidate() throws IOException, XPathExpressionException { final String fileContent = WiremockHelper.getFileContent("/sampleOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); try { XPath xpath = new net.sf.saxon.xpath.XPathFactoryImpl().newXPath(); expr = xpath.compile("/some/bad/xpath"); new XmlXPath(content).xpathToStream(expr); fail(); } catch (HarvesterException e) { assertThat(e.getMessage(), is("Empty XML!")); } } @Test public void shouldThrowExceptionOnEmpty() throws IOException { final String fileContent = ""; final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); try { new XmlXPath(content).xpathToStream(expr); fail(); } catch (HarvesterException e) { assertThat(e.getMessage(), is("Cannot xpath XML!")); } }
### Question: CassandraHelper { public static ResultSet getPrimaryKeysFromSourceTable(CassandraConnectionProvider cassandraConnectionProvider, String sourceTableName, List<String> primaryKeys) { String selectPrimaryKeysFromSourceTable = CQLBuilder.constructSelectPrimaryKeysFromSourceTable(sourceTableName, primaryKeys); PreparedStatement sourceSelectStatement = cassandraConnectionProvider.getSession().prepare(selectPrimaryKeysFromSourceTable); sourceSelectStatement.setConsistencyLevel(cassandraConnectionProvider.getConsistencyLevel()); BoundStatement boundStatement = sourceSelectStatement.bind(); return cassandraConnectionProvider.getSession().execute(boundStatement); } static BoundStatement prepareBoundStatementForMatchingTargetTable(CassandraConnectionProvider cassandraConnectionProvider, String targetTableName, List<String> primaryKeys); static ResultSet getPrimaryKeysFromSourceTable(CassandraConnectionProvider cassandraConnectionProvider, String sourceTableName, List<String> primaryKeys); static List<String> getPrimaryKeysNames(CassandraConnectionProvider cassandraConnectionProvider, String tableName, String selectColumnNames); }### Answer: @Test public void getPrimaryKeysFromSourceTableTest() { ResultSet resultSet = mock(ResultSet.class); when(session.execute(boundStatement)).thenReturn(resultSet); assertThat(CassandraHelper.getPrimaryKeysFromSourceTable(cassandraConnectionProvider, "table", primaryKeys), is(resultSet)); }
### Question: XmlXPath { String xpathToString(XPathExpression expr) throws HarvesterException { try { return evaluateExpression(expr); } catch (XPathExpressionException e) { throw new HarvesterException("Cannot xpath XML!", e); } } XmlXPath(String input); }### Answer: @Test public void shouldReturnRecordIsDeleted() throws IOException, HarvesterException { final String fileContent = WiremockHelper.getFileContent("/deletedOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); assertEquals("deleted", new XmlXPath(content).xpathToString(isDeletedExpression)); } @Test public void shouldReturnRecordIsNotDeleted() throws IOException, HarvesterException { final String fileContent = WiremockHelper.getFileContent("/sampleOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); assertFalse("deleted".equalsIgnoreCase(new XmlXPath(content).xpathToString(isDeletedExpression))); }
### Question: HarvesterImpl implements Harvester { @Override public InputStream harvestRecord(String oaiPmhEndpoint, String recordId, String metadataPrefix, XPathExpression expression, XPathExpression statusCheckerExpression) throws HarvesterException { return harvestRecord(DEFAULT_CONNECTION_FACTORY, oaiPmhEndpoint, recordId, metadataPrefix, expression, statusCheckerExpression); } HarvesterImpl(int numberOfRetries, int timeBetweenRetries); @Override InputStream harvestRecord(String oaiPmhEndpoint, String recordId, String metadataPrefix, XPathExpression expression, XPathExpression statusCheckerExpression); @Override Iterator<OAIHeader> harvestIdentifiers(Harvest harvest); }### Answer: @Test public void shouldHarvestRecord() throws IOException, HarvesterException { stubFor(get(urlEqualTo("/oai-phm/?verb=GetRecord&identifier=mediateka" + "&metadataPrefix=oai_dc")) .willReturn(response200XmlContent(getFileContent("/sampleOaiRecord.xml")) )); final HarvesterImpl harvester = new HarvesterImpl(DEFAULT_RETRIES, SLEEP_TIME); final InputStream result = harvester.harvestRecord(OAI_PMH_ENDPOINT, "mediateka", "oai_dc", expr, isDeletedExpression); final String actual = TestHelper.convertToString(result); assertThat(actual, TestHelper.isSimilarXml(getFileContent("/expectedOaiRecord.xml"))); } @Test(expected = HarvesterException.class) public void shouldHandleDeletedRecords() throws IOException, HarvesterException { stubFor(get(urlEqualTo("/oai-phm/?verb=GetRecord&identifier=mediateka" + "&metadataPrefix=oai_dc")) .willReturn(response200XmlContent(getFileContent("/deletedOaiRecord.xml")) )); final HarvesterImpl harvester = new HarvesterImpl(DEFAULT_RETRIES, SLEEP_TIME); harvester.harvestRecord(OAI_PMH_ENDPOINT, "mediateka", "oai_dc", expr, isDeletedExpression); } @Test public void shouldThrowExceptionHarvestedRecordNotFound() { stubFor(get(urlEqualTo("/oai-phm/?verb=GetRecord&identifier=oai%3Amediateka.centrumzamenhofa" + ".pl%3A19&metadataPrefix=oai_dc")) .willReturn(response404())); final HarvesterImpl harvester = new HarvesterImpl(DEFAULT_RETRIES, SLEEP_TIME); try { harvester.harvestRecord(OAI_PMH_ENDPOINT, "oai:mediateka.centrumzamenhofa.pl:19", "oai_dc", expr, isDeletedExpression); fail(); } catch (HarvesterException e) { assertThat(e.getMessage(), is("Problem with harvesting record oai:mediateka.centrumzamenhofa.pl:19 for endpoint http: } } @Test(expected = HarvesterException.class) public void shouldHandleTimeout() throws IOException, HarvesterException { stubFor(get(urlEqualTo("/oai-phm/?verb=GetRecord&identifier=mediateka" + "&metadataPrefix=oai_dc")) .willReturn(responsTimeoutGreaterThanSocketTimeout(getFileContent("/sampleOaiRecord.xml"), TEST_SOCKET_TIMEOUT) )); final HarvesterImpl.ConnectionFactory connectionFactory = new HarvesterImpl.ConnectionFactory() { @Override public OaiPmhConnection createConnection(String oaiPmhEndpoint, Parameters parameters) { return new OaiPmhConnection(oaiPmhEndpoint, parameters, TEST_SOCKET_TIMEOUT, TEST_SOCKET_TIMEOUT, TEST_SOCKET_TIMEOUT); } }; final HarvesterImpl harvester = new HarvesterImpl(1, SLEEP_TIME); harvester.harvestRecord(connectionFactory, OAI_PMH_ENDPOINT, "mediateka", "oai_dc", expr, isDeletedExpression); }
### Question: TopologyManager { public List<String> getNames() { return topologies; } TopologyManager(final String nameList); List<String> getNames(); boolean containsTopology(String topologyName); static final String separatorChar; static final Logger logger; }### Answer: @Test public void should_successfully_getTopologyNames() { List<String> resultNameList = instance.getNames(); List<String> expectedNameList = convertStringToList(nameList); assertThat(resultNameList, is(equalTo(expectedNameList))); }
### Question: TopologyManager { public boolean containsTopology(String topologyName) { return topologies.contains(topologyName); } TopologyManager(final String nameList); List<String> getNames(); boolean containsTopology(String topologyName); static final String separatorChar; static final Logger logger; }### Answer: @Test public void should_successfully_containsTopology1() { final String topologyName = "topologyA"; boolean result = instance.containsTopology(topologyName); assertThat(result, is(equalTo(true))); } @Test public void should_successfully_containsTopology2() { final String topologyName = "topologyB"; boolean result = instance.containsTopology(topologyName); assertThat(result, is(equalTo(true))); } @Test public void should_unsuccessfully_containsTopology() { final String topologyName = "topologyC"; boolean result = instance.containsTopology(topologyName); assertThat(result, is(equalTo(false))); }
### Question: CassandraHelper { public static List<String> getPrimaryKeysNames(CassandraConnectionProvider cassandraConnectionProvider, String tableName, String selectColumnNames) { List<String> names = new LinkedList<>(); PreparedStatement selectStatement = cassandraConnectionProvider.getSession().prepare(selectColumnNames); selectStatement.setConsistencyLevel(cassandraConnectionProvider.getConsistencyLevel()); BoundStatement boundStatement = selectStatement.bind(cassandraConnectionProvider.getKeyspaceName(), tableName); ResultSet rs = cassandraConnectionProvider.getSession().execute(boundStatement); Iterator<Row> iterator = rs.iterator(); while (iterator.hasNext()) { Row row = iterator.next(); if (row.getString(COLUMN_INDEX_TYPE).equals(CLUSTERING_KEY_TYPE) || row.getString(COLUMN_INDEX_TYPE).equals(PARTITION_KEY_TYPE)) names.add(row.getString(COLUMN_NAME_SELECTOR)); } return names; } static BoundStatement prepareBoundStatementForMatchingTargetTable(CassandraConnectionProvider cassandraConnectionProvider, String targetTableName, List<String> primaryKeys); static ResultSet getPrimaryKeysFromSourceTable(CassandraConnectionProvider cassandraConnectionProvider, String sourceTableName, List<String> primaryKeys); static List<String> getPrimaryKeysNames(CassandraConnectionProvider cassandraConnectionProvider, String tableName, String selectColumnNames); }### Answer: @Test public void getPrimaryKeysNamesTest() { ResultSet resultSet = mock(ResultSet.class); when(preparedStatement.bind(anyString(), anyString())).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(resultSet); Iterator iterator = mock(Iterator.class); when(resultSet.iterator()).thenReturn(iterator); when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false); Row row1 = mock(Row.class); Row row2 = mock(Row.class); when(iterator.next()).thenReturn(row1).thenReturn(row2); when(row1.getString(COLUMN_INDEX_TYPE)).thenReturn(CLUSTERING_KEY_TYPE); when(row2.getString(COLUMN_INDEX_TYPE)).thenReturn(CLUSTERING_KEY_TYPE); when(row1.getString(COLUMN_INDEX_TYPE)).thenReturn(PARTITION_KEY_TYPE); when(row2.getString(COLUMN_INDEX_TYPE)).thenReturn(PARTITION_KEY_TYPE); when(row1.getString(COLUMN_NAME_SELECTOR)).thenReturn(primaryKeys.get(0)); when(row2.getString(COLUMN_NAME_SELECTOR)).thenReturn(primaryKeys.get(1)); assertThat(CassandraHelper.getPrimaryKeysNames(cassandraConnectionProvider, "table", "Query String"), is(primaryKeys)); }
### Question: SimplifiedRepresentationResource { @GetMapping @PostAuthorize("hasPermission" + "( " + " (returnObject.cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") public @ResponseBody Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String providerId, @PathVariable String localId, @PathVariable String representationName) throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { LOGGER.info("Reading representation '{}' using 'friendly' approach for providerId: {} and localId: {}", representationName, providerId, localId); final String cloudId = findCloudIdFor(providerId, localId); Representation representation = recordService.getRepresentation(cloudId, representationName); EnrichUriUtil.enrich(httpServletRequest, representation); return representation; } SimplifiedRepresentationResource(UISClientHandler uisClientHandler, RecordService recordService); @GetMapping @PostAuthorize("hasPermission" + "( " + " (returnObject.cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String providerId, @PathVariable String localId, @PathVariable String representationName); }### Answer: @Test(expected = ProviderNotExistsException.class) public void exceptionShouldBeThrowForNotExistingProviderId() throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { representationResource.getRepresentation(null, NOT_EXISTING_PROVIDER_ID, "localID", "repName"); } @Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrowForNotExistingCloudId() throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { representationResource.getRepresentation(null, PROVIDER_ID, LOCAL_ID_FOR_NOT_EXISTING_RECORD, "repName"); } @Test(expected = RepresentationNotExistsException.class) public void exceptionShouldBeThrowForRecordWithoutNamedRepresentation() throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { representationResource.getRepresentation(null, PROVIDER_ID, LOCAL_ID, RANDOM_REPRESENTATION_NAME); } @Test public void properRepresentationShouldBeReturned() throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { HttpServletRequest info = mockHttpServletRequest(); Representation rep = representationResource.getRepresentation(info, PROVIDER_ID, LOCAL_ID, EXISTING_REPRESENTATION_NAME); Assert.assertNotNull(rep); assertThat(rep.getCloudId(), is(CLOUD_ID)); assertThat(rep.getRepresentationName(), is(EXISTING_REPRESENTATION_NAME)); }
### Question: CQLBuilder { public static String constructSelectPrimaryKeysFromSourceTable(String sourceTableName, List<String> primaryKeyNames) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT "); for (int i = 0; i < primaryKeyNames.size() - 1; i++) stringBuilder.append(primaryKeyNames.get(i)).append(" , "); stringBuilder.append(primaryKeyNames.get(primaryKeyNames.size() - 1)); stringBuilder.append(" from ").append(sourceTableName).append(";"); return stringBuilder.toString(); } static String getMatchCountStatementFromTargetTable(String targetTableName, List<String> names); static String constructSelectPrimaryKeysFromSourceTable(String sourceTableName, List<String> primaryKeyNames); }### Answer: @Test public void shouldReturnTheExpectedPrimaryKeysSelectionCQL() { assertEquals(EXPECTED_PRIMARY_KEYS_SELECTION_STATEMENT, CQLBuilder.constructSelectPrimaryKeysFromSourceTable(SOURCE_TABLE, primaryKeys)); }
### Question: SimplifiedFileAccessResource { @RequestMapping(method = RequestMethod.HEAD) public ResponseEntity<?> getFileHeaders( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName) throws RepresentationNotExistsException, FileNotExistsException, RecordNotExistsException, ProviderNotExistsException { LOGGER.info("Reading file headers in friendly way for: provider: {}, localId: {}, represenatation: {}, fileName: {}", providerId, localId, representationName, fileName); final String cloudId = findCloudIdFor(providerId, localId); final Representation representation = selectRepresentationVersion(cloudId, representationName); if (representation == null) { throw new RepresentationNotExistsException(); } if (userHasRightsToReadFile(cloudId, representation.getRepresentationName(), representation.getVersion())) { final File requestedFile = readFile(cloudId, representationName, representation.getVersion(), fileName); String md5 = requestedFile.getMd5(); MediaType fileMimeType = null; if (StringUtils.isNotBlank(requestedFile.getMimeType())) { fileMimeType = MediaType.parseMediaType(requestedFile.getMimeType()); } EnrichUriUtil.enrich(httpServletRequest, representation, requestedFile); ResponseEntity.BodyBuilder response = ResponseEntity .status(HttpStatus.OK) .location(requestedFile.getContentUri()); if (md5 != null) { response.eTag(md5); } if (fileMimeType != null) { response.contentType(fileMimeType); } return response.build(); } else { throw new AccessDeniedException("Access is denied"); } } SimplifiedFileAccessResource(RecordService recordService, UISClientHandler uisClientHandler, PermissionEvaluator permissionEvaluator); @GetMapping ResponseEntity<StreamingResponseBody> getFile( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName); @RequestMapping(method = RequestMethod.HEAD) ResponseEntity<?> getFileHeaders( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName); }### Answer: @Test public void fileHeadersShouldBeReadSuccessfully() throws FileNotExistsException, RecordNotExistsException, ProviderNotExistsException, RepresentationNotExistsException, URISyntaxException { setupUriInfo(); ResponseEntity<?> response = fileAccessResource.getFileHeaders(URI_INFO, EXISTING_PROVIDER_ID, EXISTING_LOCAL_ID, existingRepresentationName, "fileWithoutReadRights"); Assert.assertEquals(200, response.getStatusCodeValue()); Assert.assertNotNull(response.getHeaders().get("Location")); response.toString(); }
### Question: RepresentationVersionsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public RepresentationsListWrapper listVersions( final HttpServletRequest request, @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExistsException { List<Representation> representationVersions = recordService.listRepresentationVersions(cloudId, representationName); for (Representation representationVersion : representationVersions) { EnrichUriUtil.enrich(request, representationVersion); } return new RepresentationsListWrapper(representationVersions); } RepresentationVersionsResource(RecordService recordService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody RepresentationsListWrapper listVersions( final HttpServletRequest request, @PathVariable String cloudId, @PathVariable String representationName); static final Logger LOGGER; }### Answer: @Test @Parameters(method = "mimeTypes") public void testListVersions(MediaType mediaType) throws Exception { List<Representation> expected = copy(REPRESENTATIONS); Representation expectedRepresentation = expected.get(0); URITools.enrich(expectedRepresentation, getBaseUri()); when(recordService.listRepresentationVersions(GLOBAL_ID, SCHEMA)).thenReturn(copy(REPRESENTATIONS)); ResultActions response = mockMvc.perform(get(LIST_VERSIONS_PATH).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); List<Representation> entity = responseContentAsRepresentationList(response, mediaType); assertThat(entity, is(expected)); verify(recordService, times(1)).listRepresentationVersions(GLOBAL_ID, SCHEMA); verifyNoMoreInteractions(recordService); }
### Question: SimplifiedRecordsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public @ResponseBody Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String providerId, @PathVariable String localId) throws RecordNotExistsException, ProviderNotExistsException { final String cloudId = findCloudIdFor(providerId, localId); Record record = recordService.getRecord(cloudId); prepare(httpServletRequest, record); return record; } SimplifiedRecordsResource(RecordService recordService, UISClientHandler uisHandler); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String providerId, @PathVariable String localId); }### Answer: @Test(expected = ProviderNotExistsException.class) public void exceptionShouldBeThrowForNotExistingProviderId() throws RecordNotExistsException, ProviderNotExistsException { recordsResource.getRecord(null, NOT_EXISTING_PROVIDER_ID, "anyLocalId"); } @Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrowForNotExistingCloudId() throws RecordNotExistsException, ProviderNotExistsException { recordsResource.getRecord(null, PROVIDER_ID, LOCAL_ID_FOR_NOT_EXISTING_RECORD); } @Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrowForRecordWithoutRepresentations() throws RecordNotExistsException, ProviderNotExistsException { recordsResource.getRecord(null, PROVIDER_ID, LOCAL_ID_FOR_RECORD_WITHOUT_REPRESENTATIONS); } @Test public void properRecordShouldBeReturned() throws RecordNotExistsException, ProviderNotExistsException { HttpServletRequest info = mockHttpServletRequest(); Record record = recordsResource.getRecord(info, PROVIDER_ID, LOCAL_ID_FOR_EXISTING_RECORD); Assert.assertNotNull(record); for (Representation representation : record.getRepresentations()) { Assert.assertTrue(representation.getCloudId() == null); } }
### Question: RepresentationVersionResource { @GetMapping(value = REPRESENTATION_VERSION, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") public @ResponseBody Representation getRepresentationVersion( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version) throws RepresentationNotExistsException { Representation representation = recordService.getRepresentation(cloudId, representationName, version); EnrichUriUtil.enrich(httpServletRequest, representation); return representation; } RepresentationVersionResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(value = REPRESENTATION_VERSION, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") @ResponseBody Representation getRepresentationVersion( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @DeleteMapping(value = REPRESENTATION_VERSION) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', delete)") @ResponseStatus(HttpStatus.NO_CONTENT) void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_PERSIST) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', write)") ResponseEntity<Void> persistRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_COPY) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") ResponseEntity<Void> copyRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); }### Answer: @Test @Parameters(method = "mimeTypes") public void testGetRepresentationVersion(MediaType mediaType) throws Exception { Representation expected = new Representation(representation); URITools.enrich(expected, getBaseUri()); when(recordService.getRepresentation(globalId, schema, version)).thenReturn(new Representation(representation)); ResultActions response = mockMvc.perform(get(URITools.getVersionPath(globalId, schema, version)).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); Representation entity = responseContent(response, Representation.class, mediaType); assertThat(entity, is(expected)); verify(recordService, times(1)).getRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); }
### Question: RepresentationVersionResource { @DeleteMapping(value = REPRESENTATION_VERSION) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', delete)") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version) throws RepresentationNotExistsException, CannotModifyPersistentRepresentationException { recordService.deleteRepresentation(cloudId, representationName, version); ObjectIdentity dataSetIdentity = new ObjectIdentityImpl(REPRESENTATION_CLASS_NAME, cloudId + "/" + representationName + "/" + version); mutableAclService.deleteAcl(dataSetIdentity, false); } RepresentationVersionResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(value = REPRESENTATION_VERSION, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") @ResponseBody Representation getRepresentationVersion( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @DeleteMapping(value = REPRESENTATION_VERSION) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', delete)") @ResponseStatus(HttpStatus.NO_CONTENT) void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_PERSIST) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', write)") ResponseEntity<Void> persistRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_COPY) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") ResponseEntity<Void> copyRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); }### Answer: @Test public void testDeleteRepresentation() throws Exception { mockMvc.perform(delete(URITools.getVersionPath(globalId, schema, version))) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "errors") public void testDeleteRepresentationReturns404IfRecordOrRepresentationDoesNotExists(Throwable exception, String errorCode, int statusCode) throws Exception { Mockito.doThrow(exception).when(recordService).deleteRepresentation(globalId, schema, version); ResultActions response = mockMvc.perform(delete(URITools.getVersionPath(globalId, schema, version))) .andExpect(status().is(statusCode)); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).deleteRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); }
### Question: CQLBuilder { public static String getMatchCountStatementFromTargetTable(String targetTableName, List<String> names) { String wherePart = getStringWherePart(names); StringBuilder selectStatementFromTargetTableBuilder = new StringBuilder(); selectStatementFromTargetTableBuilder.append("Select count(*) from ").append(targetTableName).append(" WHERE ").append(wherePart); return selectStatementFromTargetTableBuilder.toString(); } static String getMatchCountStatementFromTargetTable(String targetTableName, List<String> names); static String constructSelectPrimaryKeysFromSourceTable(String sourceTableName, List<String> primaryKeyNames); }### Answer: @Test public void shouldReturnTheExpectedCountStatement() { assertEquals(EXPECTED_COUNT_STATEMENT, CQLBuilder.getMatchCountStatementFromTargetTable(SOURCE_TABLE, primaryKeys)); }
### Question: RepresentationVersionResource { @PostMapping(value = REPRESENTATION_VERSION_PERSIST) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', write)") public ResponseEntity<Void> persistRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version) throws RepresentationNotExistsException, CannotModifyPersistentRepresentationException, CannotPersistEmptyRepresentationException { Representation persistentRepresentation = recordService.persistRepresentation(cloudId, representationName, version); EnrichUriUtil.enrich(httpServletRequest, persistentRepresentation); return ResponseEntity.created(persistentRepresentation.getUri()).build(); } RepresentationVersionResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(value = REPRESENTATION_VERSION, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") @ResponseBody Representation getRepresentationVersion( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @DeleteMapping(value = REPRESENTATION_VERSION) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', delete)") @ResponseStatus(HttpStatus.NO_CONTENT) void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_PERSIST) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', write)") ResponseEntity<Void> persistRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); @PostMapping(value = REPRESENTATION_VERSION_COPY) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") ResponseEntity<Void> copyRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version); }### Answer: @Test public void testPersistRepresentation() throws Exception { when(recordService.persistRepresentation(globalId, schema, version)).thenReturn( new Representation(representation)); mockMvc.perform(post(persistPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.LOCATION, URITools.getVersionUri(getBaseUri(), globalId, schema, version).toString())); verify(recordService, times(1)).persistRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "persistErrors") public void testPersistRepresentationReturns40XIfExceptionOccur(Throwable exception, String errorCode, int statusCode) throws Exception { when(recordService.persistRepresentation(globalId, schema, version)).thenThrow(exception); ResultActions response = mockMvc.perform(post(persistPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().is(statusCode)); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).persistRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); }
### Question: RecordsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String cloudId) throws RecordNotExistsException { Record record = recordService.getRecord(cloudId); prepare(httpServletRequest, record); return record; } RecordsResource(RecordService recordService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String cloudId); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRecord( @PathVariable String cloudId); }### Answer: @Test @Parameters(method = "mimeTypes") public void getRecord(MediaType mediaType) throws Exception { String globalId = "global1"; Record record = new Record(globalId, Lists.newArrayList(new Representation(globalId, "DC", "1", null, null, "FBC", Lists.newArrayList(new File("dc.xml", "text/xml", "91162629d258a876ee994e9233b2ad87", "2013-10-21", 12345L, URI.create("http: + "/representations/DC/versions/1/files/dc.xml"))), null, false, new Date()))); Record expected = new Record(record); Representation expectedRepresentation = expected.getRepresentations().get(0); expectedRepresentation.setCloudId(null); expectedRepresentation.setAllVersionsUri(URI.create(getBaseUri() + "records/" + globalId + "/representations/DC/versions")); expectedRepresentation.setUri(URI.create(getBaseUri() + "records/" + globalId + "/representations/DC/versions/1")); when(recordService.getRecord(globalId)).thenReturn(record); ResultActions response = mockMvc.perform(get("/records/" + globalId).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); System.out.println("Response body:\n" + response.andReturn().getResponse().getContentAsString()); Record entity = responseContent(response, Record.class, mediaType); assertThat(entity, is(expected)); verify(recordService, times(1)).getRecord(globalId); verifyNoMoreInteractions(recordService); } @Test public void getRecordReturns404IfRecordDoesNotExists() throws Exception { String globalId = "global1"; Throwable exception = new RecordNotExistsException(); when(recordService.getRecord(globalId)).thenThrow(exception); mockMvc.perform(get("/records/" + globalId).contentType(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); verify(recordService, times(1)).getRecord(globalId); verifyNoMoreInteractions(recordService); }
### Question: RecordsResource { @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") public void deleteRecord( @PathVariable String cloudId) throws RecordNotExistsException, RepresentationNotExistsException { recordService.deleteRecord(cloudId); } RecordsResource(RecordService recordService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String cloudId); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRecord( @PathVariable String cloudId); }### Answer: @Test public void deleteRecord() throws Exception { String globalId = "global1"; mockMvc.perform(delete("/records/" + globalId)) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRecord(globalId); verifyNoMoreInteractions(recordService); } @Test public void deleteRecordReturns404IfRecordDoesNotExists() throws Exception { String globalId = "global1"; Throwable exception = new RecordNotExistsException(); Mockito.doThrow(exception).when(recordService).deleteRecord(globalId); mockMvc.perform(delete("/records/" + globalId).contentType(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); verify(recordService, times(1)).deleteRecord(globalId); verifyNoMoreInteractions(recordService); } @Test public void deleteRecordReturns404IfRecordHasNoRepresentations() throws Exception { String globalId = "global1"; Throwable exception = new RepresentationNotExistsException(); Mockito.doThrow(exception).when(recordService).deleteRecord(globalId); mockMvc.perform(delete("/records/" + globalId).contentType(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); verify(recordService, times(1)).deleteRecord(globalId); verifyNoMoreInteractions(recordService); }
### Question: DataSetsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public ResultSlice<DataSet> getDataSets( @PathVariable String providerId, @RequestParam(required = false) String startFrom) { return dataSetService.getDataSets(providerId, startFrom, numberOfElementsOnPage); } DataSetsResource(DataSetService dataSetService, MutableAclService mutableAclService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody ResultSlice<DataSet> getDataSets( @PathVariable String providerId, @RequestParam(required = false) String startFrom); @PreAuthorize("isAuthenticated()") @PostMapping ResponseEntity<Void> createDataSet( HttpServletRequest httpServletRequest, @PathVariable String providerId, @RequestParam String dataSetId, @RequestParam(required = false) String description); }### Answer: @Test public void shouldCreateDataset() throws Exception { Mockito.doReturn(new DataProvider()).when(uisHandler) .getProvider("provId"); String datasetId = "datasetId"; String description = "dataset description"; ResultActions createResponse = mockMvc.perform(post(dataSetsWebTarget, "provId").contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(F_DATASET, datasetId).param(F_DESCRIPTION, description) ).andExpect(status().isCreated()); String uriFromResponse = createResponse.andReturn().getResponse().getHeader(HttpHeaders.LOCATION); assertEquals("http: List<DataSet> dataSetsForPrivider = dataSetService.getDataSets( "provId", null, 10000).getResults(); assertEquals("Expected single dataset in service", 1, dataSetsForPrivider.size()); DataSet ds = dataSetsForPrivider.get(0); assertEquals(datasetId, ds.getId()); assertEquals(description, ds.getDescription()); }
### Question: MigrationExecutor { public void migrate() { CassandraMigration cm = new CassandraMigration(); cm.getConfigs().setScriptsLocations(scriptsLocations); cm.setKeyspace(keyspace); cm.migrate(); } MigrationExecutor(String cassandraKeyspace, String cassandraContactPoint, int cassandraPort, String cassandraUsername, String cassandraPassword, String[] scriptsLocations); void migrate(); }### Answer: @Test public void shouldSuccessfullyMigrateData() { MigrationExecutor migrator = new MigrationExecutor(EmbeddedCassandra.KEYSPACE, contactPoint, EmbeddedCassandra.PORT, cassandraUsername, cassandraPassword, scriptsLocations); migrator.migrate(); validateMigration(); List<String> cloudIds = getCloudIds(session.execute("SELECT * FROM data_set_assignments_by_data_set;").all()); assertThat(cloudIds.size(), is(2)); } @Test public void shouldThrowExceptionOnTwiceDataMigrations() { MigrationExecutor migrator = new MigrationExecutor(EmbeddedCassandra.KEYSPACE, contactPoint, EmbeddedCassandra.PORT, cassandraUsername, cassandraPassword, scriptsLocations); migrator.migrate(); migrator.migrate(); List<String> cloudIds = getCloudIds(session.execute("SELECT * FROM data_set_assignments_by_data_set;").all()); assertThat(cloudIds.size(), is(2)); } @Test public void shouldSuccessfullyMigrateDataInUIS() { final String[] scriptsLocations1 = new String[]{"migrations/service/uis", "testMigrations/uis"}; MigrationExecutor migrator = new MigrationExecutor(EmbeddedCassandra.KEYSPACE, contactPoint, EmbeddedCassandra.PORT, cassandraUsername, cassandraPassword, scriptsLocations1); migrator.migrate(); List<Row> rows = session.execute("SELECT * FROM provider_record_id;").all(); assertEquals(rows.size(), 1); Row row = rows.get(0); assertTheMigratedTableValues(row); } @Test public void shouldSuccessfullyMigrateDataInDPS() { final String[] scriptsLocations1 = new String[]{"migrations/service/dps", "testMigrations/dps"}; MigrationExecutor migrator = new MigrationExecutor(EmbeddedCassandra.KEYSPACE, contactPoint, EmbeddedCassandra.PORT, cassandraUsername, cassandraPassword, scriptsLocations1); migrator.migrate(); validateDPSMigration(); }
### Question: DataSetsResource { @PreAuthorize("isAuthenticated()") @PostMapping public ResponseEntity<Void> createDataSet( HttpServletRequest httpServletRequest, @PathVariable String providerId, @RequestParam String dataSetId, @RequestParam(required = false) String description) throws ProviderNotExistsException, DataSetAlreadyExistsException { DataSet dataSet = dataSetService.createDataSet(providerId, dataSetId, description); EnrichUriUtil.enrich(httpServletRequest, dataSet); String creatorName = SpringUserUtils.getUsername(); if (creatorName != null) { ObjectIdentity dataSetIdentity = new ObjectIdentityImpl(DATASET_CLASS_NAME, dataSetId + "/" + providerId); MutableAcl datasetAcl = mutableAclService.createAcl(dataSetIdentity); datasetAcl.insertAce(0, BasePermission.READ, new PrincipalSid(creatorName), true); datasetAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creatorName), true); datasetAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creatorName), true); datasetAcl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creatorName), true); mutableAclService.updateAcl(datasetAcl); } return ResponseEntity.created(dataSet.getUri()).build(); } DataSetsResource(DataSetService dataSetService, MutableAclService mutableAclService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody ResultSlice<DataSet> getDataSets( @PathVariable String providerId, @RequestParam(required = false) String startFrom); @PreAuthorize("isAuthenticated()") @PostMapping ResponseEntity<Void> createDataSet( HttpServletRequest httpServletRequest, @PathVariable String providerId, @RequestParam String dataSetId, @RequestParam(required = false) String description); }### Answer: @Test public void shouldNotCreateTwoDatasetsWithSameId() throws Exception { Mockito.doReturn(new DataProvider()).when(uisHandler) .getProvider("provId"); String dataSetId = "dataset"; dataSetService.createDataSet("provId", dataSetId, ""); ResultActions createResponse = mockMvc.perform(post(dataSetsWebTarget, "provId") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(F_DATASET, dataSetId)).andExpect(status().isConflict()); ErrorInfo errorInfo = responseContentAsErrorInfo(createResponse); assertEquals(McsErrorCode.DATASET_ALREADY_EXISTS.toString(), errorInfo.getErrorCode()); }
### Question: RepresentationResource { @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody public Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExistsException { Representation info = recordService.getRepresentation(cloudId, representationName); prepare(httpServletRequest, info); return info; } RepresentationResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @RequestParam String providerId); }### Answer: @Test @Parameters(method = "mimeTypes") public void getRepresentation(MediaType mediaType) throws Exception { Representation expected = new Representation(representation); expected.setUri(URITools.getVersionUri(getBaseUri(), globalId, schema, version)); expected.setAllVersionsUri(URITools.getAllVersionsUri(getBaseUri(), globalId, schema)); ArrayList<File> files = new ArrayList<>(1); files.add(new File("1.xml", "text/xml", "91162629d258a876ee994e9233b2ad87", "2013-01-01", 12345L, URI.create("http: + "/representations/" + schema + "/versions/" + version + "/files/1.xml"))); expected.setFiles(files); when(recordService.getRepresentation(globalId, schema)).thenReturn(new Representation(representation)); ResultActions response = mockMvc.perform(get(URITools.getRepresentationPath(globalId, schema)).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); Representation entity = responseContent(response,Representation.class, mediaType); assertThat(entity, is(expected)); verify(recordService, times(1)).getRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "representationErrors") public void getRepresentationReturns404IfRepresentationOrRecordDoesNotExists(Throwable exception, String errorCode) throws Exception { when(recordService.getRepresentation(globalId, schema)).thenThrow(exception); ResultActions response = mockMvc.perform(get(URITools.getRepresentationPath(globalId, schema)) .accept(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContent(response,ErrorInfo.class,MediaType.APPLICATION_XML); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).getRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); }
### Question: RepresentationResource { @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") public void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExistsException { recordService.deleteRepresentation(cloudId, representationName); } RepresentationResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @RequestParam String providerId); }### Answer: @Test public void deleteRecord() throws Exception { mockMvc.perform(delete(URITools.getRepresentationPath(globalId, schema))) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "representationErrors") public void deleteRepresentationReturns404IfRecordOrRepresentationDoesNotExists(Throwable exception, String errorCode) throws Exception { Mockito.doThrow(exception).when(recordService).deleteRepresentation(globalId, schema); ResultActions response = mockMvc.perform(delete(URITools.getRepresentationPath(globalId, schema))) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).deleteRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); }
### Question: RepresentationResource { @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") public ResponseEntity<Void> createRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @RequestParam String providerId) throws RecordNotExistsException, ProviderNotExistsException { Representation version = recordService.createRepresentation(cloudId, representationName, providerId); EnrichUriUtil.enrich(httpServletRequest, version); String creatorName = SpringUserUtils.getUsername(); if (creatorName != null) { ObjectIdentity versionIdentity = new ObjectIdentityImpl(REPRESENTATION_CLASS_NAME, cloudId + "/" + representationName + "/" + version.getVersion()); MutableAcl versionAcl = mutableAclService .createAcl(versionIdentity); versionAcl.insertAce(0, BasePermission.READ, new PrincipalSid(creatorName), true); versionAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creatorName), true); versionAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creatorName), true); versionAcl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creatorName), true); mutableAclService.updateAcl(versionAcl); } return ResponseEntity.created(version.getUri()).build(); } RepresentationResource(RecordService recordService, MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @RequestParam String providerId); }### Answer: @Test public void createRepresentation() throws Exception { when(recordService.createRepresentation(globalId, schema, providerID)).thenReturn( new Representation(representation)); mockMvc.perform(post(URITools.getRepresentationPath(globalId, schema)) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(ParamConstants.F_PROVIDER, providerID)) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.LOCATION, URITools.getVersionUri(getBaseUri(), globalId, schema, version).toString())); verify(recordService, times(1)).createRepresentation(globalId, schema, providerID); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "recordErrors") public void createRepresentationReturns404IfRecordOrRepresentationDoesNotExists(Throwable exception, String errorCode) throws Exception { Mockito.doThrow(exception).when(recordService).createRepresentation(globalId, schema, providerID); ResultActions response = mockMvc.perform(post(URITools.getRepresentationPath(globalId, schema)) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(ParamConstants.F_PROVIDER, providerID)) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).createRepresentation(globalId, schema, providerID); verifyNoMoreInteractions(recordService); }
### Question: CSVReader implements RevisionsReader { @Override public List<RevisionInformation> getRevisionsInformation(String filePath) throws IOException { List<RevisionInformation> revisionInformationList = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line = ""; br.readLine(); while ((line = br.readLine()) != null) { String[] lines = line.split(LINE_SEPARATOR); RevisionInformation revisionInformation = new RevisionInformation(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5]); revisionInformationList.add(revisionInformation); } } return revisionInformationList; } @Override List<RevisionInformation> getRevisionsInformation(String filePath); }### Answer: @Test public void shouldReadAndReturnTaskIdsForCSVFile() throws IOException { List<RevisionInformation> taskIds = csvReader.getRevisionsInformation(Paths.get("src/test/resources/revisions.csv").toString()); assertNotNull(taskIds); assertEquals(8, taskIds.size()); }
### Question: RepresentationsResource { @GetMapping(produces = {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @ResponseBody public RepresentationsListWrapper getRepresentations( HttpServletRequest httpServletRequest, @PathVariable String cloudId) throws RecordNotExistsException { List<Representation> representationInfos = recordService.getRecord(cloudId).getRepresentations(); prepare(httpServletRequest, representationInfos); return new RepresentationsListWrapper(representationInfos); } RepresentationsResource(RecordService recordService); @GetMapping(produces = {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @ResponseBody RepresentationsListWrapper getRepresentations( HttpServletRequest httpServletRequest, @PathVariable String cloudId); }### Answer: @Test @Parameters(method = "mimeTypes") public void getRepresentations(MediaType mediaType) throws Exception { Record expected = new Record(record); Representation expectedRepresentation = expected.getRepresentations().get(0); expectedRepresentation.setUri(URITools.getVersionUri(getBaseUri(), globalId, schema, version)); expectedRepresentation.setAllVersionsUri(URITools.getAllVersionsUri(getBaseUri(), globalId, schema)); expectedRepresentation.setFiles(new ArrayList<File>()); when(recordService.getRecord(globalId)).thenReturn(new Record(record)); ResultActions response = mockMvc.perform(get(URITools.getRepresentationsPath(globalId).toString()).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); List<Representation> entity = responseContentAsRepresentationList(response, mediaType); assertThat(entity, is(expected.getRepresentations())); verify(recordService, times(1)).getRecord(globalId); verifyNoMoreInteractions(recordService); }
### Question: ContentStreamDetector { public static MediaType detectMediaType(InputStream inputStream) throws IOException { if (!inputStream.markSupported()) { throw new UnsupportedOperationException("InputStream marking support is required!"); } return new AutoDetectParser().getDetector().detect(inputStream, new Metadata()); } private ContentStreamDetector(); static MediaType detectMediaType(InputStream inputStream); }### Answer: @Test @Parameters({ "example_metadata.xml, application/xml", "example_jpg2000.jp2, image/jp2" }) public void shouldProperlyGuessMimeType_Xml(String fileName, String expectedMimeType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream( resource.getFile())); String mimeType = detectMediaType(inputStream).toString(); assertThat(mimeType,is(expectedMimeType)); byte[] actual = readFully(inputStream, expected.length); assertThat(actual,is(expected)); }
### Question: StorageSelector { public Storage selectStorage() { return decide(assertUserMediaType(), getAvailable()); } StorageSelector(final PreBufferedInputStream inputStream, final String userMediaType); Storage selectStorage(); }### Answer: @Test @Parameters({ "example_metadata.xml, DATA_BASE, application/xml", "example_jpg2000.jp2, OBJECT_STORAGE, image/jp2" }) public void shouldDetectStorage(String fileName, String expectedDecision, String mediaType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); PreBufferedInputStream inputStream = new PreBufferedInputStream( new FileInputStream(resource.getFile()), 512 * 1024); StorageSelector instance = new StorageSelector(inputStream, mediaType); Storage decision = instance.selectStorage(); assertThat(decision.toString(), is(expectedDecision)); byte[] actual = readFully(inputStream, expected.length); assertThat(actual, is(expected)); } @Test(expected = BadRequestException.class) @Parameters({ "example_metadata.xml, image/jp2", "example_jpg2000.jp2, application/xml" }) public void shouldThrowBadRequestOnDifferentMimeTypeProvidedByUser(String fileName, String mediaType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); PreBufferedInputStream inputStream = new PreBufferedInputStream( new FileInputStream(resource.getFile()), 512 * 1024); StorageSelector instance = new StorageSelector(inputStream, mediaType); Storage decision = instance.selectStorage(); }
### Question: PreBufferedInputStream extends BufferedInputStream { @Override public synchronized int available() throws IOException { ensureIsNotClosed(); int inBufferAvailable = bufferFill - position; int avail = super.available(); return inBufferAvailable > (Integer.MAX_VALUE - avail) ? Integer.MAX_VALUE : inBufferAvailable + avail; } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data, final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); }### Answer: @Test @Parameters({ "10, 20", "20, 10", "10, 10000", "10000, 20", "10000, 3000", "10000, 4000", "10, 20", "20, 10" }) public void shouldProperlyCheckAvailableForByteArrayInputStream(int size, int bufferSize) throws IOException { byte[] expected = Helper.generateRandom(size); ByteArrayInputStream inputStream = new ByteArrayInputStream(expected); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int available = instance.available(); assertThat(available, is(size)); assertUnchangedStream(expected, instance); } @Test @Parameters({ "10, example_metadata.xml", "200, example_metadata.xml", "2000, example_metadata.xml", "3000, example_metadata.xml", "10, example_jpg2000.jp2", "2000, example_jpg2000.jp2", "3000, example_jpg2000.jp2" }) public void shouldProperlyCheckAvailableForFile(final int bufferSize, final String fileName) throws IOException { URL resourceUri = Resources.getResource(fileName); final byte[] expected = Resources.toByteArray(resourceUri); FileInputStream inputStream = new FileInputStream( resourceUri.getFile()); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int available = instance.available(); assertThat(available,is((expected.length))); assertThat(available,is(((int) new File(resourceUri.getFile()).length()))); assertUnchangedStream(expected, instance); }
### Question: PreBufferedInputStream extends BufferedInputStream { @Override public synchronized int read() throws IOException { ensureIsNotClosed(); if (position < bufferFill) { return buffer[position++] & 0xff; } return super.read(); } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data, final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); }### Answer: @Test @Parameters({ "10, 20", "200, 10", "100, 10000", "100, 200", "200, 100" }) public void shouldReadStreamPerByte(int size, int bufferSize) throws IOException { byte[] randomByes = Helper.generateSeq(size); ByteArrayInputStream inputStream = new ByteArrayInputStream(randomByes); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int[] actual = new int[randomByes.length]; for (int i = 0; i < actual.length; i++) { actual[i] = instance.read(); } int[] randomIntegers = new int[actual.length]; for (int i = 0; i < randomIntegers.length; i++) { randomIntegers[i] = randomByes[i] & 0xff; } assertThat(actual, is(randomIntegers)); }
### Question: PreBufferedInputStream extends BufferedInputStream { @Override public synchronized void close() throws IOException { if (in == null && buffer == null) { return; } buffer = null; in.close(); in = null; } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data, final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); }### Answer: @Test public void shouldCloseClosedStream() throws IOException { PreBufferedInputStream instance = new PreBufferedInputStream(new NullInputStream(1), 1); instance.close(); instance.close(); }