src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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(); }
@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()); }
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(); }
@Test public void getObject() throws Exception { Integer mockObj = 34; Event event = new Event(mockObj); assertEquals(event.getObject(), mockObj); }
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(); }
@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); }
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); }
@Test public void getContact() throws Exception { BarcodeInfo.Contact contact = new BarcodeInfo.Contact(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setContact(contact); assertEquals(barcodeInfo.getContact(), contact); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@Test public void getCalendarEvent() throws Exception { BarcodeInfo.CalendarEvent calendarEvent = new BarcodeInfo.CalendarEvent(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setCalendarEvent(calendarEvent); assertEquals(barcodeInfo.getCalendarEvent(), calendarEvent); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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()); }
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(); }
@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()); }
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(); }
@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()); }
LexDelimitedString { 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 input stream when parsing delimited string literal"); } if (next != 'q') { throw new LexerException(start_line, start_col, "Not a delimited string literal"); } in_stream.read(); next = in_stream.peek(); if (next != '"') { throw new LexerException(start_line, start_col, "Not a delimited string literal"); } in_stream.read(); next = in_stream.peek(); boolean is_identifier = false; boolean is_nesting = false; int nests = 0; StringBuilder delimiter = new StringBuilder(); if (is_nesting_open(next)) { is_nesting = true; delimiter.append(Character.toChars(in_stream.read())); } else if (Character.isLetter(next) || next == '_') { is_identifier = true; delimiter.append(Character.toChars(in_stream.read())); next = in_stream.peek(); while (Character.isLetterOrDigit(next) || next == '_') { delimiter.append(Character.toChars(in_stream.read())); next = in_stream.peek(); } if (next != '\n') { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "String delimiter must be followed by newline"); } in_stream.read(); } else { delimiter.append(Character.toChars(in_stream.read())); } next = in_stream.peek(); String start_delim = delimiter.toString(); String end_delim; if (is_identifier) { end_delim = start_delim; } else { end_delim = String.valueOf((char)valid_close(start_delim.charAt(0))); } StringBuilder result = new StringBuilder(); while (next != -1) { if (next == '\n' && is_identifier) { result.append((char)in_stream.read()); next = in_stream.peek(); StringBuilder sb = new StringBuilder(); for (char c : end_delim.toCharArray()) { if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream in delimited string literal"); } else if (next != c) { break; } sb.append(Character.toChars(in_stream.read())); next = in_stream.peek(); } if (next == '"' && sb.toString().equals(end_delim)) { in_stream.read(); break; } result.append(sb); } else if (is_nesting && next == start_delim.charAt(0)) { nests++; } else if (next == end_delim.charAt(0)) { nests--; if (nests < 0) { if (in_stream.peek(2) == '"') { in_stream.read(); in_stream.read(); break; } else { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Improperly delimited string"); } } } result.append(Character.toChars(in_stream.read())); next = in_stream.peek(); } if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream in delimited string literal"); } return factory.create(TokenType.LiteralUtf8, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), result.toString()); } LexDelimitedString(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void normal() throws Exception { String str = "q\"!foo!\""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals("foo", tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(1, tok.getEndLine()); Assert.assertEquals(9, tok.getEndCol()); } @Test public void bracketed() throws Exception { String str = "q\"{foo][{b}f}\"bar"; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals("foo][{b}f", tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(1, tok.getEndLine()); Assert.assertEquals(15, tok.getEndCol()); } @Test public void parens() throws Exception { String str = "q\"((f)\""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals("(f", tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(1, tok.getEndLine()); Assert.assertEquals(13, tok.getEndCol()); } @Test public void identifier() throws Exception { String str = "q\"END\nsome\nmultiline\nstring\nEND\" "; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals("some\nmultiline\nstring\n", tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(5, tok.getEndLine()); Assert.assertEquals(5, tok.getEndCol()); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void not() throws Exception { String str = "q[]"; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void also_not() throws Exception { String str = "\"q{}\""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void unterminated() throws Exception { String str = "q\"{lalala}"; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void partial_delimiter() throws Exception { String str = "q\"/abc/def/\""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void unnested() throws Exception { String str = "q\"{foo][}f}\"bar"; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); lex.read(); }
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(); }
@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()); }
LexHexLiteral { 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 input stream when parsing string literal"); } if (next != 'x') { 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 literal hex string"); } in_stream.read(); next = in_stream.peek(); StringBuilder sb = new StringBuilder(); boolean pair = false; while (next != -1 && is_valid_hex(next)) { if (!Character.isWhitespace(next)) { sb.append(Character.toChars(next)); if (pair) { sb.append(' '); } pair = !pair; } in_stream.read(); next = in_stream.peek(); } if (next != '"') { throw new LexerException(start_line, start_col, "Unterminated literal hex string"); } in_stream.read(); StringBuilder result = new StringBuilder(); String raw = sb.toString(); for (String bite : raw.split(" ")) { result.append(Character.toChars(Integer.parseInt(bite, 16))); } return factory.create(TokenType.LiteralHex, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), result.toString()); } LexHexLiteral(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void simple() throws Exception { String str = "x\"0A\""; StringBuilder sb = new StringBuilder(); sb.append(Character.toChars(0x0a)); String expected = sb.toString(); LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralHex, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals(expected, tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(1, tok.getEndLine()); Assert.assertEquals(6, tok.getEndCol()); } @Test public void spaces() throws Exception { String str = "x\"00 FbcD 3 2FD 0A \""; StringBuilder sb = new StringBuilder(); sb.append(Character.toChars(0x00)); sb.append(Character.toChars(0xfb)); sb.append(Character.toChars(0xcd)); sb.append(Character.toChars(0x32)); sb.append(Character.toChars(0xfd)); sb.append(Character.toChars(0x0a)); String expected = sb.toString(); LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralHex, tok.getType()); assertTrue(tok.getValue() instanceof String); Assert.assertEquals(expected, tok.getValue()); Assert.assertEquals(1, tok.getLine()); Assert.assertEquals(1, tok.getCol()); Assert.assertEquals(1, tok.getEndLine()); Assert.assertEquals(23, tok.getEndCol()); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void not() throws Exception { String str = "hex string"; LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void also_not() throws Exception { String str = "x00AB"; LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void unterminated() throws Exception { String str = "x\"AB CD"; LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); lex.read(); }
LexOperator { public Token read() throws IOException, LexerException { int index = in_stream.getPosition(); int line = in_stream.getLine(); int col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when parsing operator"); } if (next == '.') { int tmp = in_stream.peek(2); if (tmp > 0 && Character.isDigit(tmp)) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Literal float encountered when operator '.' expected"); } } char cur = (char)in_stream.read(); next = in_stream.peek(); switch (cur) { case '+': switch (next) { case '+': in_stream.read(); return factory.create(TokenType.Increment, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.PlusAssign, index, line, col, 2); } return factory.create(TokenType.Plus, index, line, col); case '-': switch (next) { case '-': in_stream.read(); return factory.create(TokenType.Decrement, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.MinusAssign, index, line, col, 2); } return factory.create(TokenType.Minus, index, line, col); case '*': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.TimesAssign, index, line, col, 2); default: break; } return factory.create(TokenType.Times, index, line, col); case '/': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.DivAssign, index, line, col, 2); } return factory.create(TokenType.Div, index, line, col); case '%': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.ModAssign, index, line, col, 2); } return factory.create(TokenType.Mod, index, line, col); case '&': switch (next) { case '&': in_stream.read(); return factory.create(TokenType.LogicalAnd, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.BitwiseAndAssign, index, line, col, 2); } return factory.create(TokenType.BitwiseAnd, index, line, col); case '|': switch (next) { case '|': in_stream.read(); return factory.create(TokenType.LogicalOr, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.BitwiseOrAssign, index, line, col, 2); } return factory.create(TokenType.BitwiseOr, index, line, col); case '^': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.XorAssign, index, line, col, 2); case '^': in_stream.read(); if (in_stream.peek() == '=') { in_stream.read(); return factory.create(TokenType.PowAssign, index, line, col, 3); } return factory.create(TokenType.Pow, index, line, col, 2); } return factory.create(TokenType.Xor, index, line, col); case '!': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.NotEqual, index, line, col, 2); case '<': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.UnorderedOrGreater, index, line, col, 3); case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.Unordered, index, line, col, 4); } return factory.create(TokenType.UnorderedOrEqual, index, line, col, 3); } return factory.create(TokenType.UnorderedGreaterOrEqual, index, line, col, 2); case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.UnorderedOrLess, index, line, col, 3); default: break; } return factory.create(TokenType.UnorderedLessOrEqual, index, line, col, 2); } return factory.create(TokenType.Not, index, line, col); case '~': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.TildeAssign, index, line, col, 2); } return factory.create(TokenType.Tilde, index, line, col); case '=': switch (next) { case '=': in_stream.read(); return factory.create(TokenType.Equal, index, line, col, 2); case '>': in_stream.read(); return factory.create(TokenType.GoesTo, index, line, col, 2); } return factory.create(TokenType.Assign, index, line, col); case '<': switch (next) { case '<': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.ShiftLeftAssign, index, line, col, 3); default: break; } return factory.create(TokenType.ShiftLeft, index, line, col, 2); case '>': in_stream.read(); switch (in_stream.peek()) { case '=': in_stream.read(); return factory.create(TokenType.LessEqualOrGreater, index, line, col, 3); default: break; } return factory.create(TokenType.LessOrGreater, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.LessEqual, index, line, col, 2); } return factory.create(TokenType.LessThan, index, line, col); case '>': switch (next) { case '>': in_stream.read(); int p = in_stream.peek(); if (p != -1) { switch ((char)p) { case '=': in_stream.read(); return factory.create(TokenType.ShiftRightAssign, index, line, col, 3); case '>': in_stream.read(); int q = in_stream.peek(); if (q != -1 && q == '=') { in_stream.read(); return factory.create(TokenType.TripleRightShiftAssign, index, line, col, 4); } return factory.create(TokenType.ShiftRightUnsigned, index, line, col, 3); } } return factory.create(TokenType.ShiftRight, index, line, col, 2); case '=': in_stream.read(); return factory.create(TokenType.GreaterEqual, index, line, col, 2); } return factory.create(TokenType.GreaterThan, index, line, col); case '?': return factory.create(TokenType.Question, index, line, col); case '$': return factory.create(TokenType.Dollar, index, line, col); case ';': return factory.create(TokenType.Semicolon, index, line, col); case ':': return factory.create(TokenType.Colon, index, line, col); case ',': return factory.create(TokenType.Comma, index, line, col); case '.': if (next == '.') { in_stream.read(); int p = in_stream.peek(); if (p != -1 && p == '.') { in_stream.read(); return factory.create(TokenType.TripleDot, index, line, col, 3); } return factory.create(TokenType.DoubleDot, index, line, col, 2); } return factory.create(TokenType.Dot, index, line, col); case ')': return factory.create(TokenType.CloseParenthesis, index, line, col); case '(': return factory.create(TokenType.OpenParenthesis, index, line, col); case ']': return factory.create(TokenType.CloseSquareBracket, index, line, col); case '[': return factory.create(TokenType.OpenSquareBracket, index, line, col); case '}': return factory.create(TokenType.CloseCurlyBrace, index, line, col); case '{': return factory.create(TokenType.OpenCurlyBrace, index, line, col); case '#': return factory.create(TokenType.Hash, index, line, col); default: return null; } } LexOperator(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void not_op() throws Exception { String str = "foo"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); Token tok = lex.read(); assertNull(tok); lex = new LexOperator(new BaseTokenFactory(), new LexerStream(new StringReader(""))); try { tok = lex.read(); } catch (LexerException e) { return; } fail(); } @Test public void assign() throws Exception { String str = "a=b"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.Assign, tok.getType()); assertEquals("=", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(3, tok.getEndCol()); } @Test public void equality() throws Exception { String str = "a==b != c"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.Equal, tok.getType()); assertEquals("==", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.NotEqual, tok.getType()); assertEquals("!=", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(6, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(8, tok.getEndCol()); } @Test public void inequality() throws Exception { String str = "a<b>c<=d>=e<>d<>=e"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.LessThan, tok.getType()); assertEquals("<", tok.getValue()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(3, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.GreaterThan, tok.getType()); assertEquals(">", tok.getValue()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(4, tok.getCol()); assertEquals(5, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LessEqual, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(6, tok.getCol()); assertEquals(8, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.GreaterEqual, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(9, tok.getCol()); assertEquals(11, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LessOrGreater, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(12, tok.getCol()); assertEquals(14, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LessEqualOrGreater, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(15, tok.getCol()); assertEquals(18, tok.getEndCol()); } @Test public void add() throws Exception { String str = "+ w++ += f"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.Plus, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(2, tok.getEndCol()); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.Increment, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(4, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(6, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.PlusAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(7, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); assertEquals(' ', ls.read()); assertEquals('f', ls.read()); assertEquals(-1, ls.read()); } @Test public void sub() throws Exception { String str = "a-=b-- -c"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.MinusAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Decrement, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Minus, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(8, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); assertEquals('c', ls.read()); assertEquals(-1, ls.read()); } @Test public void mul() throws Exception { String str = "a *=b*c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); ls.read(); Token tok = lex.read(); assertEquals(TokenType.TimesAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(3, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(5, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Times, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(6, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); assertEquals('c', ls.read()); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); assertEquals(-1, ls.read()); } @Test public void div() throws Exception { String str = "a/=b/c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.DivAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Div, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(6, tok.getEndCol()); assertEquals('c', ls.read()); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); assertEquals(-1, ls.read()); } @Test public void mod() throws Exception { String str = "a%=b%c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.ModAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Mod, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(6, tok.getEndCol()); assertEquals('c', ls.read()); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); assertEquals(-1, ls.read()); } @Test public void bitwise() throws Exception { String str = "a&=b|c|=d&e^=f^g;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.BitwiseAndAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.BitwiseOr, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(6, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.BitwiseOrAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(7, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.BitwiseAnd, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(10, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(11, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.XorAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(12, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(14, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Xor, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(15, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(16, tok.getEndCol()); assertEquals('g', ls.read()); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); assertEquals(-1, ls.read()); } @Test public void logical() throws Exception { String str = "a&&b ||!c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.LogicalAnd, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(4, tok.getEndCol()); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.LogicalOr, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(6, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(8, tok.getEndCol()); tok = lex.read(); assertEquals(TokenType.Not, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(8, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); } @Test public void pow() throws Exception { String str = "a^^=b^^c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.PowAssign, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(5, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Pow, tok.getType()); assertEquals(1, tok.getLine()); assertEquals(6, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(8, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Semicolon, tok.getType()); } @Test public void unordered() throws Exception { String str = "a !< b !<> c !<>= d !<= e !> f !>= g"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); ls.read(); Token tok = lex.read(); assertEquals(TokenType.UnorderedGreaterOrEqual, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(3, tok.getCol()); assertEquals(5, tok.getEndCol()); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.UnorderedOrEqual, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(8, tok.getCol()); assertEquals(11, tok.getEndCol()); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.Unordered, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(14, tok.getCol()); assertEquals(18, tok.getEndCol()); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.UnorderedOrGreater, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(21, tok.getCol()); assertEquals(24, tok.getEndCol()); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.UnorderedLessOrEqual, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(27, tok.getCol()); assertEquals(29, tok.getEndCol()); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.UnorderedOrLess, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(32, tok.getCol()); assertEquals(35, tok.getEndCol()); } @Test public void tilde() throws Exception { String str = "a~=b~c;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.TildeAssign, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Tilde, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(5, tok.getCol()); assertEquals(6, tok.getEndCol()); } @Test public void eleven() throws Exception { String str = "v=>11;"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.GoesTo, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndCol()); } @Test public void shift() throws Exception { String str = "a<<b>>c<<=d>>=e"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.ShiftLeft, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.ShiftRight, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(5, tok.getCol()); assertEquals(7, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.ShiftLeftAssign, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(8, tok.getCol()); assertEquals(11, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.ShiftRightAssign, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(12, tok.getCol()); assertEquals(15, tok.getEndCol()); } @Test public void u_shift() throws Exception { String str = "a>>>=b>>>"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.TripleRightShiftAssign, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(6, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.ShiftRightUnsigned, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(7, tok.getCol()); assertEquals(10, tok.getEndCol()); } @Test public void tri() throws Exception { String str = "a?b:c$d"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.Question, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(3, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Colon, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(4, tok.getCol()); assertEquals(5, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Dollar, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(6, tok.getCol()); assertEquals(7, tok.getEndCol()); } @Test public void dot() throws Exception { String str = "a.b .3"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.Dot, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(3, tok.getEndCol()); ls.read(); ls.read(); try { tok = lex.read(); } catch (LexerException e) { return; } fail(); } @Test public void range() throws Exception { String str = "1..2...3,4"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.DoubleDot, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.TripleDot, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(5, tok.getCol()); assertEquals(8, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.Comma, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(9, tok.getCol()); assertEquals(10, tok.getEndCol()); } @Test public void paren() throws Exception { String str = "(1)[2]{3}"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.OpenParenthesis, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(1, tok.getCol()); assertEquals(2, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.CloseParenthesis, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(3, tok.getCol()); assertEquals(4, tok.getEndCol()); tok = lex.read(); assertEquals(TokenType.OpenSquareBracket, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(4, tok.getCol()); assertEquals(5, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.CloseSquareBracket, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(6, tok.getCol()); assertEquals(7, tok.getEndCol()); tok = lex.read(); assertEquals(TokenType.OpenCurlyBrace, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(7, tok.getCol()); assertEquals(8, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.CloseCurlyBrace, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(9, tok.getCol()); assertEquals(10, tok.getEndCol()); } @Test public void hash() throws Exception { String str = "##"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.Hash, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(1, tok.getCol()); assertEquals(2, tok.getEndCol()); tok = lex.read(); assertEquals(TokenType.Hash, tok.getType()); assertTrue(tok.getLine() == 1 && tok.getEndLine() == 1); assertEquals(2, tok.getCol()); assertEquals(3, tok.getEndCol()); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); lex.read(); }
LexIdentifier { 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 input stream when parsing identifier"); } if (!Character.isLetter(next) && next != '_') { throw new LexerException(start_line, start_col, "Invalid character for start of identifier: "+(char)next); } StringBuilder sb = new StringBuilder(); while (valid_ident_char(next)) { sb.append(Character.toChars(in_stream.read())); next = in_stream.peek(); } String result = sb.toString(); TokenType type = TokenType.forValue(result); if (type == null) { type = TokenType.Identifier; } if (type == TokenType.Identifier && result.startsWith("__")) { throw new LexerException(start_line, start_col, "Unknown reserved identifier"); } return factory.create(type, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), result); } LexIdentifier(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void keywords() throws Exception { StringBuilder words = new StringBuilder(); for (String word : keywords) { words.append(word).append(" "); } LexerStream ls = new LexerStream(new StringReader(words.toString())); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); for (String word : keywords) { Token tok = lex.read(); assertEquals(word, tok.getValue()); assertEquals(TokenType.forValue(word), tok.getType()); ls.read(); } assertEquals(-1, ls.read()); } @Test public void identifier() throws Exception { String str = "foo _bar a_2"; LexerStream ls = new LexerStream(new StringReader(str)); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.Identifier, tok.getType()); assertEquals("foo", 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.Identifier, tok.getType()); assertEquals("_bar", 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.Identifier, tok.getType()); assertEquals("a_2", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(10, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(13, tok.getEndCol()); } @Test public void dotted() throws Exception { String str = "foo.bar"; LexerStream ls = new LexerStream(new StringReader(str)); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.Identifier, tok.getType()); assertEquals("foo", 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.Identifier, tok.getType()); assertEquals("bar", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(8, tok.getEndCol()); } @Test(expected = LexerException.class) public void reserved() throws Exception { String str = "__FOO__"; LexerStream ls = new LexerStream(new StringReader(str)); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void not() throws Exception { String str = "9d"; LexerStream ls = new LexerStream(new StringReader(str)); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); lex.read(); }
LexStringLiteral { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); boolean is_literal = false; int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of input stream when parsing string literal"); } if (next == 'r') { is_literal = true; in_stream.read(); next = in_stream.peek(); } int initial = next; if (initial == '`') { is_literal = true; } TokenType type = TokenType.LiteralUtf8; StringBuilder sb = new StringBuilder(); in_stream.read(); next = in_stream.peek(); while (next != -1 && next != initial) { if (next == '\\' && !is_literal) { sb.append(Character.toChars(LexEscape.read(in_stream))); } else { sb.append(Character.toChars(in_stream.read())); } next = in_stream.peek(); } if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of input stream when parsing string literal"); } in_stream.read(); next = in_stream.peek(); if (next == 'c') { type = TokenType.LiteralUtf8; in_stream.read(); } else if (next == 'w') { type = TokenType.LiteralUtf16; in_stream.read(); } else if (next == 'd') { type = TokenType.LiteralUtf32; in_stream.read(); } return factory.create(type, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), sb.toString()); } LexStringLiteral(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void simple() throws Exception { String str = "\"Here is a string\""; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("Here is a string", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(19, tok.getEndCol()); assertEquals(-1, ls.read()); } @Test public void escaped() throws Exception { String str = "\"\\n\\\"\\tfoo\\\" \\x7c\""; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("\n\"\tfoo\" |", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(19, tok.getEndCol()); assertEquals(-1, ls.read()); } @Test public void wysiwyg() throws Exception { String str = "r\"a\\b\\nc\""; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("a\\b\\nc", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(10, tok.getEndCol()); assertEquals(-1, ls.read()); } @Test public void tick() throws Exception { String str = "`a\\b\\nc`"; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("a\\b\\nc", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(9, tok.getEndCol()); assertEquals(-1, ls.read()); } @Test public void explicit_utf8() throws Exception { String str = "\"foo\"c"; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("foo", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); } @Test public void explicit_utf16() throws Exception { String str = "\"foo\"w"; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf16, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("foo", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); } @Test public void explicit_utf32() throws Exception { String str = "\"foo\"d"; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf32, tok.getType()); assertTrue(tok.getValue() instanceof String); assertEquals("foo", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); lex.read(); } @Test(expected = LexerException.class) public void unterminated() throws Exception { String str = "\"yadayada"; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); lex.read(); }
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(); }
@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(); }
LexComment { 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(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when parsing comment"); } if (next != '/') { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Comments must start with '/'"); } TokenType type; StringBuilder sb = new StringBuilder(); sb.append((char)in_stream.read()); next = in_stream.peek(); switch (next) { case '+': sb.append((char)in_stream.read()); if (in_stream.peek() == '+') { sb.append((char)in_stream.read()); type = TokenType.DocCommentNest; } else { type = TokenType.BlockCommentNest; } sb.append(read_multi_nested(in_stream)); break; case '*': sb.append((char)in_stream.read()); if (in_stream.peek() == '*') { sb.append((char)in_stream.read()); type = TokenType.DocComment; } else { type = TokenType.BlockComment; } sb.append(read_multi(in_stream)); break; case '/': sb.append((char)in_stream.read()); next = in_stream.peek(); if (next == '/') { sb.append((char)in_stream.read()); type = TokenType.DocLineComment; } else { type = TokenType.LineComment; } while (next != -1 && next != '\n') { sb.append((char)in_stream.read()); next = in_stream.peek(); } break; default: throw new LexerException(start_line, start_col, "Error while reading comment"); } return factory.create(type, start_index, start_line, start_col, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol(), sb.toString()); } LexComment(TokenFactory factory, LexerStream in_stream); Token read(); }
@Test public void line() throws Exception { String str = "a LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.LineComment, tok.getType()); assertEquals(" assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(7, tok.getEndCol()); ls.read(); tok = lex.read(); assertEquals(TokenType.LineComment, tok.getType()); assertEquals(" assertEquals(2, tok.getLine()); assertEquals(1, tok.getCol()); assertEquals(2, tok.getEndLine()); assertEquals(9, tok.getEndCol()); } @Test public void block() throws Exception { String str = "a\ncde"; LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.BlockComment, tok.getType()); assertEquals("", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndLine()); assertEquals(3, tok.getEndCol()); } @Test public void block_inline() throws Exception { String str = "a=c"; LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); ls.read(); Token tok = lex.read(); assertEquals(TokenType.BlockComment, tok.getType()); assertEquals("", tok.getValue()); assertEquals(1, tok.getLine()); assertEquals(3, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(8, tok.getEndCol()); } @Test public void nest() throws Exception { String str = "a/+ /+b\n+/ /+c /+\nd\n +/ e+ LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.BlockCommentNest, tok.getType()); assertEquals("/+ /+b\n" + "+/ /+c /+\n" + "d\n" + " +/ e+ assertEquals(1, tok.getLine()); assertEquals(2, tok.getCol()); assertEquals(4, tok.getEndLine()); assertEquals(12, tok.getEndCol()); } @Test public void nest_inline() throws Exception { String str = "a = /+ "a = /+ \"+/\" +/ 1\";\n" + "a = /+ 3;"; LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); ls.read(); ls.read(); ls.read(); Token tok = lex.read(); assertEquals(TokenType.BlockCommentNest, tok.getType()); assertEquals("/+ assertEquals(1, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(1, tok.getEndLine()); assertEquals(13, tok.getEndCol()); ls.readLine(); ls.read(); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.BlockCommentNest, tok.getType()); assertEquals("/+ \"+/", tok.getValue()); assertEquals(2, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(2, tok.getEndLine()); assertEquals(11, tok.getEndCol()); ls.readLine(); ls.read(); ls.read(); ls.read(); ls.read(); tok = lex.read(); assertEquals(TokenType.BlockCommentNest, tok.getType()); assertEquals("/+ /* +/", tok.getValue()); assertEquals(3, tok.getLine()); assertEquals(5, tok.getCol()); assertEquals(3, tok.getEndLine()); assertEquals(13, tok.getEndCol()); }
LexEscape { public static int read(final LexerStream in_stream) throws IOException, LexerException { int next = in_stream.peek(); if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when inside escape sequence"); } if (next != '\\') { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Not an escape sequence"); } int result; in_stream.read(); int cur = in_stream.read(); next = in_stream.peek(); switch (cur) { case '\'': result = '\''; break; case '\"': result = '\"'; break; case '?': result = '?'; break; case '\\': result = '\\'; break; case '0': result = '\0'; break; case 'a': result = 0x07; break; case 'b': result = '\b'; break; case 'f': result = '\f'; break; case 'n': result = '\n'; break; case 'r': result = '\r'; break; case 't': result = '\t'; break; case 'v': result = 0x0B; break; case 'x': result = 0; for (int i = 0; i < 2; i++) { if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream"); } try { int n = Integer.parseInt(String.valueOf((char)next), 16); result = (16 * result) + n; } catch (NumberFormatException e) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Invalid character in literal: "+next, e); } in_stream.read(); next = in_stream.peek(); } break; case 'u': result = 0; for (int i = 0; i < 4; i++) { if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream"); } try { int n = Integer.parseInt(String.valueOf((char)next), 16); result = (16 * result) + n; } catch (NumberFormatException e) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Invalid character in literal: "+next, e); } in_stream.read(); next = in_stream.peek(); } break; case 'U': result = 0; for (int i = 0; i < 8; i++) { if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream"); } try { int n = Integer.parseInt(String.valueOf((char)next), 16); result = (16 * result) + n; } catch (NumberFormatException e) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Invalid character in literal: "+next, e); } in_stream.read(); next = in_stream.peek(); } break; case '&': StringBuilder entity = new StringBuilder(); entity.append((char)cur); while (true) { if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of stream"); } if (next == ';') { entity.append((char)in_stream.read()); break; } if (Character.isLetter(next)) { entity.append((char)in_stream.read()); } else { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected character found in named entity: "+next); } next = in_stream.peek(); } if (entity.length() < 1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Empty named character entity encountered"); } String val = StringEscapeUtils.unescapeHtml4(entity.toString()); result = Character.codePointAt(val, 0); break; default: if (!is_oct(cur)) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unrecognized escape sequence: "+next); } result = Integer.parseInt(String.valueOf((char)cur), 8); int cnt = 1; while (is_oct(next) && cnt < 3) { cnt++; try { int n = Integer.parseInt(String.valueOf((char)next), 8); result = (8 * result) + n; } catch (NumberFormatException e) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Invalid character in octal literal: "+next, e); } in_stream.read(); next = in_stream.peek(); } break; } return result; } static int read(final LexerStream in_stream); }
@Test public void escape() throws Exception { String str = "\\'" + "\\\"" + "\\?" + "\\\\" + "\\a" + "\\b" + "\\f" + "\\n" + "\\r" + "\\t" + "\\v" + "\\0" + ""; LexerStream ls = new LexerStream(new StringReader(str)); assertEquals('\'', (char)LexEscape.read(ls)); assertEquals('"', (char)LexEscape.read(ls)); assertEquals('?', (char)LexEscape.read(ls)); assertEquals('\\', (char)LexEscape.read(ls)); assertEquals(0x07, LexEscape.read(ls)); assertEquals('\b', (char)LexEscape.read(ls)); assertEquals('\f', (char)LexEscape.read(ls)); assertEquals('\n', (char)LexEscape.read(ls)); assertEquals('\r', (char)LexEscape.read(ls)); assertEquals('\t', (char)LexEscape.read(ls)); assertEquals(0x0B, LexEscape.read(ls)); assertEquals(0x00, LexEscape.read(ls)); } @Test public void oct() throws Exception { String str = "\\123 \\37 \\4"; LexerStream ls = new LexerStream(new StringReader(str)); assertEquals(83, LexEscape.read(ls)); ls.read(); assertEquals(31, LexEscape.read(ls)); ls.read(); assertEquals(4, LexEscape.read(ls)); } @Test public void hex() throws Exception { String str = "\\xA1 \\uF0a5 \\UdeaDbEef"; LexerStream ls = new LexerStream(new StringReader(str)); assertEquals(0xa1, LexEscape.read(ls)); ls.read(); assertEquals(0xf0a5, LexEscape.read(ls)); ls.read(); assertEquals(0xdeadbeef, LexEscape.read(ls)); } @Test public void html() throws Exception { String str = "\\&gt; \\&yuml; \\&perp;"; LexerStream ls = new LexerStream(new StringReader(str)); assertEquals(62, LexEscape.read(ls)); ls.read(); assertEquals(255, LexEscape.read(ls)); ls.read(); assertEquals(8869, LexEscape.read(ls)); } @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexEscape.read(ls); } @Test(expected = LexerException.class) public void not() throws Exception { String str = "escape"; LexerStream ls = new LexerStream(new StringReader(str)); LexEscape.read(ls); } @Test(expected = LexerException.class) public void unknown() throws Exception { String str = "\\z"; LexerStream ls = new LexerStream(new StringReader(str)); LexEscape.read(ls); }
Lexer { public Token next() throws IOException { Token token; try { token = _next(); } catch (LexerException e) { token = factory.create(TokenType.Unknown, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol()); in_stream.read(); } return token; } Lexer(TokenFactory tokenFactory, Reader inStream); private Lexer(TokenFactory tokenFactory, LexerStream inStream); int position(); Token next(); Token _next(); }
@Test public void lex() throws Exception { String code = "" + " "import std.stdio;\n" + "\n" + "void main() {\n" + " ulong lines = 0;\n" + " double sumLength=0;\n" + " foreach (line;stdin.byLine()){\n" + " ++lines;\n" + " sumLength += line.length;\n" + " }\n" + " writeln(\"Average line length: \",\n" + " lines ? sumLength/lines : 0);\n" + " }\n" + ""; List<TokenType> expected = new ArrayList<TokenType>(); expected.add(TokenType.LineComment); expected.add(TokenType.Whitespace); expected.add(TokenType.Import); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Dot); expected.add(TokenType.Identifier); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.Void); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.OpenParenthesis); expected.add(TokenType.CloseParenthesis); expected.add(TokenType.Whitespace); expected.add(TokenType.OpenCurlyBrace); expected.add(TokenType.Whitespace); expected.add(TokenType.Ulong); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Whitespace); expected.add(TokenType.Assign); expected.add(TokenType.Whitespace); expected.add(TokenType.Literal); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.Double); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Assign); expected.add(TokenType.Literal); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.Foreach); expected.add(TokenType.Whitespace); expected.add(TokenType.OpenParenthesis); expected.add(TokenType.Identifier); expected.add(TokenType.Semicolon); expected.add(TokenType.Identifier); expected.add(TokenType.Dot); expected.add(TokenType.Identifier); expected.add(TokenType.OpenParenthesis); expected.add(TokenType.CloseParenthesis); expected.add(TokenType.CloseParenthesis); expected.add(TokenType.OpenCurlyBrace); expected.add(TokenType.Whitespace); expected.add(TokenType.Increment); expected.add(TokenType.Identifier); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Whitespace); expected.add(TokenType.PlusAssign); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Dot); expected.add(TokenType.Identifier); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.CloseCurlyBrace); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.OpenParenthesis); expected.add(TokenType.LiteralUtf8); expected.add(TokenType.Comma); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Whitespace); expected.add(TokenType.Question); expected.add(TokenType.Whitespace); expected.add(TokenType.Identifier); expected.add(TokenType.Div); expected.add(TokenType.Identifier); expected.add(TokenType.Whitespace); expected.add(TokenType.Colon); expected.add(TokenType.Whitespace); expected.add(TokenType.Literal); expected.add(TokenType.CloseParenthesis); expected.add(TokenType.Semicolon); expected.add(TokenType.Whitespace); expected.add(TokenType.CloseCurlyBrace); expected.add(TokenType.Whitespace); expected.add(TokenType.EOF); Lexer lexer = new Lexer(new BaseTokenFactory(), new StringReader(code)); List<Token> tokens = new ArrayList<Token>(); Token tok; do { tok = lexer.next(); tokens.add(tok); } while (tok != null && tok.getType() != TokenType.EOF); assertNull(lexer.next()); for (int i = 0; i < expected.size(); i++) { assertEquals(expected.get(i), tokens.get(i).getType()); } assertEquals("std", tokens.get(4).getValue()); assertEquals("stdio", tokens.get(6).getValue()); assertEquals("main", tokens.get(11).getValue()); assertEquals("lines", tokens.get(19).getValue()); assertEquals(0L, tokens.get(23).getValue()); assertEquals("sumLength", tokens.get(28).getValue()); assertEquals(0L, tokens.get(30).getValue()); assertEquals("line", tokens.get(36).getValue()); assertEquals("stdin", tokens.get(38).getValue()); assertEquals("byLine", tokens.get(40).getValue()); assertEquals("lines", tokens.get(47).getValue()); assertEquals("sumLength", tokens.get(50).getValue()); assertEquals("line", tokens.get(54).getValue()); assertEquals("length", tokens.get(56).getValue()); assertEquals("writeln", tokens.get(61).getValue()); assertEquals("Average line length: ", tokens.get(63).getValue()); assertEquals("lines", tokens.get(66).getValue()); assertEquals("sumLength", tokens.get(70).getValue()); assertEquals("lines", tokens.get(72).getValue()); assertEquals(0L, tokens.get(76).getValue()); } @Test public void error() throws Exception { String code = "" + "\n" + "q\"/abc/def/\"\n" + ""; Lexer lexer = new Lexer(new BaseTokenFactory(), new StringReader(code)); assertEquals(TokenType.BlockComment, lexer.next().getType()); assertEquals(TokenType.Whitespace, lexer.next().getType()); assertEquals(TokenType.Unknown, lexer.next().getType()); Token tok = lexer.next(); assertEquals(TokenType.Identifier, tok.getType()); assertEquals("def", tok.getValue()); assertEquals(TokenType.Div, lexer.next().getType()); assertEquals(TokenType.Unknown, lexer.next().getType()); assertEquals(TokenType.EOF, lexer.next().getType()); assertNull(lexer.next()); }
MCacheDb extends AbstractActor { public String getValue(String key) { return this.map.get(key); } @Override Receive createReceive(); String getValue(String key); }
@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"); }
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); }
@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()); }
DefaultRegisteredServiceMfaRoleProcessorImpl implements RegisteredServiceMfaRoleProcessor { public List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication, @NotNull final WebApplicationService targetService) { String authenticationMethodAttributeName = null; final List<MultiFactorAuthenticationRequestContext> list = new ArrayList<>(); if (authentication != null && targetService != null) { final ServiceMfaData serviceMfaData = getServicesAuthenticationData(targetService); if (serviceMfaData == null || !serviceMfaData.isValid()) { logger.debug("No specific mfa role service attributes found"); return list; } logger.debug("Found MFA Role: {}", serviceMfaData); authenticationMethodAttributeName = serviceMfaData.attributeName; final Object mfaAttributeValueAsObject = authentication.getPrincipal().getAttributes().get(serviceMfaData.attributeName); if (mfaAttributeValueAsObject != null) { if (mfaAttributeValueAsObject instanceof String) { final String mfaAttributeValue = mfaAttributeValueAsObject.toString(); final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, mfaAttributeValue, targetService); if (ctx != null) { list.add(ctx); } } else if (mfaAttributeValueAsObject instanceof List) { final List<String> mfaAttributeValues = (List<String>) mfaAttributeValueAsObject; for (final String mfaAttributeValue : mfaAttributeValues) { final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, mfaAttributeValue, targetService); if (ctx != null) { list.add(ctx); } } } else if (mfaAttributeValueAsObject instanceof Collection) { final Collection mfaAttributeValues = (Collection) mfaAttributeValueAsObject; for (final Object mfaAttributeValue : mfaAttributeValues) { final MultiFactorAuthenticationRequestContext ctx = getMfaRequestContext( serviceMfaData, String.valueOf(mfaAttributeValue), targetService); if (ctx != null) { list.add(ctx); } } } else { logger.debug("No MFA attribute found."); } } } if (list.isEmpty()) { logger.debug("No multifactor authentication requests could be resolved based on [{}].", authenticationMethodAttributeName); return null; } return list; } DefaultRegisteredServiceMfaRoleProcessorImpl( final MultiFactorWebApplicationServiceFactory mfaServiceFactory, final AuthenticationMethodConfigurationProvider authenticationMethodConfiguration, final ServicesManager servicesManager); List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication, @NotNull final WebApplicationService targetService); }
@Test public void testResolveWithoutAnyServiceMfaAttributes() throws Exception { final WebApplicationService was = getTargetService(); final Authentication auth = getAuthentication(true); final RegisteredService rswa = TestUtils.getRegisteredService("test1"); final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl( getMFWASF(was), getAMCP(), getServicesManager(rswa)); final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was); assertNotNull(result); assertEquals(0, result.size()); } @Test public void testResolveWithoutIncompleteServiceMfaAttributes() throws Exception { final WebApplicationService was = getTargetService(); final Authentication auth = getAuthentication(true); final RegisteredService rswa = TestUtils.getRegisteredService("test1"); DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(CAS_AUTHN_METHOD)); rswa.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop); prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(MEMBER_OF_VALUE)); rswa.getProperties().put(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_PATTERN, prop); final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl( getMFWASF(was), getAMCP(), getServicesManager(rswa)); final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was); assertNotNull(result); assertEquals(0, result.size()); } @Test public void testResolveServiceWithMfaAttributesUserInRole() throws Exception { final WebApplicationService was = getTargetService(); final Authentication auth = getAuthentication(true); final RegisteredService rswa = TestUtils.getRegisteredService("test1"); DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(CAS_AUTHN_METHOD)); rswa.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop); prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(MEMBER_OF)); rswa.getProperties().put(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_NAME, prop); prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(MEMBER_OF_VALUE)); rswa.getProperties().put(RegisteredServiceMfaRoleProcessor.MFA_ATTRIBUTE_PATTERN, prop); final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl( getMFWASF(was), getAMCP(), getServicesManager(rswa)); final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was); assertNotNull(result); assertEquals(CAS_AUTHN_METHOD, result.get(0).getMfaService().getAuthenticationMethod()); } @Test public void testResolveServiceWithOnlyAuthnMethodAttribute() throws Exception { final WebApplicationService was = getTargetService(); final Authentication auth = getAuthentication(true); final RegisteredService rswa = TestUtils.getRegisteredService("test1"); final DefaultRegisteredServiceProperty prop = new DefaultRegisteredServiceProperty(); prop.setValues(Collections.singleton(CAS_AUTHN_METHOD)); rswa.getProperties().put(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD, prop); final DefaultRegisteredServiceMfaRoleProcessorImpl resolver = new DefaultRegisteredServiceMfaRoleProcessorImpl( getMFWASF(was), getAMCP(), getServicesManager(rswa)); final List<MultiFactorAuthenticationRequestContext> result = resolver.resolve(auth, was); assertNotNull(result); assertEquals(0, result.size()); }
RevisionRemoverJob implements Runnable { void setRevisionInformation(RevisionInformation revisionInformation) { this.revisionInformation = revisionInformation; } RevisionRemoverJob(DataSetServiceClient dataSetServiceClient, RecordServiceClient recordServiceClient, RevisionInformation revisionInformation, RevisionServiceClient revisionServiceClient); @Override void run(); }
@Test public void shouldRemoveRevisionsOnly() throws Exception { final int NUMBER_OF_REVISIONS = 3; final int NUMBER_OF_RESPONSES = 2; RevisionInformation revisionInformation = new RevisionInformation("DATASET", DATA_PROVIDER, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date)); revisionRemoverJob.setRevisionInformation(revisionInformation); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, date); List<Representation> representations = new ArrayList<>(1); representations.add(representation); List<Revision> revisions = getRevisions(NUMBER_OF_REVISIONS); representation.setRevisions(revisions); ResultSlice<CloudTagsResponse> resultSlice = getCloudTagsResponseResultSlice(NUMBER_OF_RESPONSES); when(dataSetServiceClient.getDataSetRevisionsChunk(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyInt())).thenReturn(resultSlice); when(recordServiceClient.getRepresentationsByRevision(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date))).thenReturn(Arrays.asList(representation)); when(recordServiceClient.getRepresentationsByRevision(SOURCE + CLOUD_ID2, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date))).thenReturn(Arrays.asList(representation)); Thread thread = new Thread(revisionRemoverJob); thread.start(); thread.join(); verify(revisionServiceClient, times(NUMBER_OF_RESPONSES * NUMBER_OF_REVISIONS)).deleteRevision(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); verify(recordServiceClient, times(0)).deleteRepresentation(anyString(), anyString(), anyString()); } @Test public void shouldRemoveEntireRepresentation() throws Exception { final int NUMBER_OF_REVISIONS = 1; final int NUMBER_OF_RESPONSES = 2; RevisionInformation revisionInformation = new RevisionInformation("DATASET", DATA_PROVIDER, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date)); revisionRemoverJob.setRevisionInformation(revisionInformation); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, date); List<Representation> representations = new ArrayList<>(1); representations.add(representation); List<Revision> revisions = getRevisions(NUMBER_OF_REVISIONS); representation.setRevisions(revisions); ResultSlice<CloudTagsResponse> resultSlice = getCloudTagsResponseResultSlice(NUMBER_OF_RESPONSES); when(dataSetServiceClient.getDataSetRevisionsChunk(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyInt())).thenReturn(resultSlice); when(recordServiceClient.getRepresentationsByRevision(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date))).thenReturn(Arrays.asList(representation)); when(recordServiceClient.getRepresentationsByRevision(SOURCE + CLOUD_ID2, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date))).thenReturn(Arrays.asList(representation)); Thread thread = new Thread(revisionRemoverJob); thread.start(); thread.join(); verify(revisionServiceClient, times(0)).deleteRevision(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); verify(recordServiceClient, times(NUMBER_OF_RESPONSES)).deleteRepresentation(anyString(), anyString(), anyString()); }
LinkCheckBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple tuple) { ResourceInfo resourceInfo = readResourceInfoFromTuple(tuple); if (!hasLinksForCheck(resourceInfo)) { emitSuccessNotification(anchorTuple, tuple.getTaskId(), tuple.getFileUrl(), "", "The EDM file has no resources", "", StormTaskTupleHelper.getRecordProcessingStartTime(tuple)); outputCollector.ack(anchorTuple); } else { FileInfo edmFile = checkProvidedLink(tuple, resourceInfo); edmFile.addSourceTuple(anchorTuple); if (isFileFullyProcessed(edmFile)) { cache.remove(edmFile.fileUrl); if (edmFile.errors == null || edmFile.errors.isEmpty()) emitSuccessNotification(anchorTuple, tuple.getTaskId(), tuple.getFileUrl(), "", "", "", StormTaskTupleHelper.getRecordProcessingStartTime(tuple)); else emitSuccessNotification(anchorTuple, tuple.getTaskId(), tuple.getFileUrl(), "", "", "", "resource exception", edmFile.errors, StormTaskTupleHelper.getRecordProcessingStartTime(tuple)); ackAllSourceTuplesForFile(edmFile); } } } @Override void prepare(); @Override void execute(Tuple anchorTuple, StormTaskTuple tuple); }
@Test public void shouldEmitSameTupleWhenNoResourcesHasToBeChecked() { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = prepareTupleWithLinksCountEqualsToZero(); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(1)).emit( eq("NotificationStream"), eq(anchorTuple), captor.capture()); validateCapturedValues(captor); } @Test public void shouldCheckOneLinkWithoutEmittingTuple() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = prepareRandomTuple(); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(0)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(1)).performLinkChecking(tuple.getParameter(PluginParameterKeys.RESOURCE_URL)); } @Test public void shouldEmitTupleAfterCheckingAllResourcesFromFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = prepareRandomTuple(); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(0)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(1)).performLinkChecking(tuple.getParameter(PluginParameterKeys.RESOURCE_URL)); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(0)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(2)).performLinkChecking(tuple.getParameter(PluginParameterKeys.RESOURCE_URL)); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(0)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(3)).performLinkChecking(tuple.getParameter(PluginParameterKeys.RESOURCE_URL)); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(0)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(4)).performLinkChecking(tuple.getParameter(PluginParameterKeys.RESOURCE_URL)); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(1)).emit(eq("NotificationStream"), any(Tuple.class), Mockito.anyList()); verify(linkChecker, times(5)).performLinkChecking(Mockito.anyString()); } @Test public void shouldEmitTupleWithErrorIncluded() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); doThrow(new LinkCheckingException(new Throwable())).when(linkChecker).performLinkChecking(Mockito.anyString()); StormTaskTuple tuple = prepareRandomTuple(); linkCheckBolt.execute(anchorTuple, tuple); linkCheckBolt.execute(anchorTuple, tuple); linkCheckBolt.execute(anchorTuple, tuple); linkCheckBolt.execute(anchorTuple, tuple); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(1)).emit(eq("NotificationStream"), any(Tuple.class), captor.capture()); validateCapturedValuesForError(captor); }
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(); }
@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)); }
RecordHarvestingBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { long harvestingStartTime = new Date().getTime(); LOGGER.info("Starting harvesting for: {}", stormTaskTuple.getParameter(CLOUD_LOCAL_IDENTIFIER)); String endpointLocation = readEndpointLocation(stormTaskTuple); String recordId = readRecordId(stormTaskTuple); String metadataPrefix = readMetadataPrefix(stormTaskTuple); if (parametersAreValid(endpointLocation, recordId, metadataPrefix)) { LOGGER.info("OAI Harvesting started for: {} and {}", recordId, endpointLocation); try (final InputStream record = harvester.harvestRecord(endpointLocation, recordId, metadataPrefix, expr, isDeletedExpression)) { stormTaskTuple.setFileData(record); if (useHeaderIdentifier(stormTaskTuple)) trimLocalId(stormTaskTuple); else useEuropeanaId(stormTaskTuple); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); LOGGER.info("Harvesting finished successfully for: {} and {}", recordId, endpointLocation); } catch (HarvesterException | IOException | EuropeanaIdException e) { LOGGER.error("Exception on harvesting", e); emitErrorNotification( anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), "Error while harvesting a record", "The full error is: " + e.getMessage() + ". The cause of the error is: " + e.getCause(), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); LOGGER.error(e.getMessage()); } } else { emitErrorNotification( anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getParameter(DPS_TASK_INPUT_DATA), "Invalid parameters", null, StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } LOGGER.info("Harvesting finished in: {}ms for {}", Calendar.getInstance().getTimeInMillis() - harvestingStartTime, stormTaskTuple.getParameter(CLOUD_LOCAL_IDENTIFIER)); outputCollector.ack(anchorTuple); } @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); }
@Test public void harvestingForAllParametersSpecified() throws IOException, HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithAllNeededParameters(); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifySuccessfulEmit(); verify(spiedTask).setFileData(Mockito.any(InputStream.class)); } @Test public void shouldHarvestRecordInEDMAndExtractIdentifiers() throws IOException, HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithAllNeededParameters(); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifySuccessfulEmit(); verify(spiedTask).setFileData(Mockito.any(InputStream.class)); assertEquals("http: assertEquals("/2020739_Ag_EU_CARARE_2Cultur/object_DCU_24927017", spiedTask.getParameter(PluginParameterKeys.CLOUD_LOCAL_IDENTIFIER)); } @Test public void shouldHarvestRecordInEDMAndNotUseHeaderIdentifierIfParameterIsDifferentThanTrue() throws IOException, HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithGivenValueOfUseHeaderIdentifiersParameter("blablaba"); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifySuccessfulEmit(); verify(spiedTask).setFileData(Mockito.any(InputStream.class)); assertEquals("http: assertEquals("/2020739_Ag_EU_CARARE_2Cultur/object_DCU_24927017", spiedTask.getParameter(PluginParameterKeys.CLOUD_LOCAL_IDENTIFIER)); } @Test public void shouldHarvestRecordInEDMAndUseHeaderIdentifierIfSpecifiedInTaskParameters() throws IOException, HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithGivenValueOfUseHeaderIdentifiersParameter("true"); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifySuccessfulEmit(); verify(spiedTask).setFileData(Mockito.any(InputStream.class)); assertNull( spiedTask.getParameter(PluginParameterKeys.ADDITIONAL_LOCAL_IDENTIFIER)); assertEquals("http: } @Test public void shouldHarvestRecordInEDMAndUseHeaderIdentifierAndTrimItIfSpecifiedInTaskParameters() throws IOException, HarvesterException { InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); Tuple anchorTuple = mock(TupleImpl.class); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithGivenValueOfUseHeaderIdentifiersAndTrimmingPrefix("true"); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifySuccessfulEmit(); verify(spiedTask).setFileData(Mockito.any(InputStream.class)); assertNull(spiedTask.getParameter(PluginParameterKeys.ADDITIONAL_LOCAL_IDENTIFIER)); assertEquals("/item/2064203/o_aj_kk_tei_3", spiedTask.getParameter(PluginParameterKeys.CLOUD_LOCAL_IDENTIFIER)); } @Test public void shouldEmitErrorOnHarvestingExceptionWhenCannotExctractEuropeanaIdFromEDM() throws HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/corruptedEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenReturn(fileContentAsStream); StormTaskTuple task = taskWithAllNeededParameters(); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifyErrorEmit(); } @Test public void shouldEmitErrorOnHarvestingException() throws HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), any(XPathExpression.class))).thenThrow(new HarvesterException("Some!")); StormTaskTuple task = taskWithAllNeededParameters(); StormTaskTuple spiedTask = spy(task); recordHarvestingBolt.execute(anchorTuple, spiedTask); verifyErrorEmit(); } @Test public void harvestingForEmptyUrl() { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple task = taskWithoutResourceUrl(); recordHarvestingBolt.execute(anchorTuple, task); verifyErrorEmit(); } @Test public void harvestingForEmptyRecordId() { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple task = taskWithoutRecordId(); recordHarvestingBolt.execute(anchorTuple, task); verifyErrorEmit(); } @Test public void harvestForEmptyPrefix() { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple task = taskWithoutPrefix(); recordHarvestingBolt.execute(anchorTuple, task); verifyErrorEmit(); }
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); }
@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))); }
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); }
@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); }
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; }
@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(); }
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); }
@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())); }
ParseFileBolt extends ReadFileBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try (InputStream stream = getFileStreamByStormTuple(stormTaskTuple)) { byte[] fileContent = IOUtils.toByteArray(stream); List<RdfResourceEntry> rdfResourceEntries = getResourcesFromRDF(fileContent); int linksCount = getLinksCount(stormTaskTuple, rdfResourceEntries.size()); if (linksCount == 0) { StormTaskTuple tuple = new Cloner().deepClone(stormTaskTuple); LOGGER.info("The EDM file has no resource Links "); outputCollector.emit(anchorTuple, tuple.toStormTuple()); } else { for (RdfResourceEntry rdfResourceEntry : rdfResourceEntries) { if (AbstractDpsBolt.taskStatusChecker.hasKillFlag(stormTaskTuple.getTaskId())) break; StormTaskTuple tuple = createStormTuple(stormTaskTuple, rdfResourceEntry, linksCount); outputCollector.emit(anchorTuple, tuple.toStormTuple()); } } } catch (Exception e) { LOGGER.error("Unable to read and parse file ", e); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Error while reading and parsing the EDM file. The full error is: " + ExceptionUtils.getStackTrace(e), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } ParseFileBolt(String ecloudMcsAddress); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); }
@Test public void shouldParseFileAndEmitResources() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); when(taskStatusChecker.hasKillFlag(eq(TASK_ID))).thenReturn(false); parseFileBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(5)).emit(captor.capture()); List<Values> capturedValuesList = captor.getAllValues(); assertEquals(4, capturedValuesList.size()); for (Values values : capturedValuesList) { assertEquals(8, values.size()); Map<String, String> val = (Map) values.get(4); assertNotNull(val); for (String parameterKey : val.keySet()) { assertTrue(expectedParametersKeysList.contains(parameterKey)); } } } } @Test public void shouldDropTaskAndStopEmitting() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); when(taskStatusChecker.hasKillFlag(eq(TASK_ID))).thenReturn(false).thenReturn(false).thenReturn(true); parseFileBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(2)).emit(captor.capture()); } } @Test public void shouldParseFileWithEmptyResourcesAndForwardOneTuple() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/no-resources.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); parseFileBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(1)).emit(captor.capture()); Values values = captor.getValue(); assertNotNull(values); System.out.println(values); Map<String, String> map = (Map) values.get(4); System.out.println(map); assertEquals(2, map.size()); assertNull(map.get(PluginParameterKeys.RESOURCE_LINKS_COUNT)); assertNull(map.get(PluginParameterKeys.RESOURCE_LINK_KEY)); } } @Test public void shouldEmitErrorWhenDownloadFileFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); doThrow(IOException.class).when(fileClient).getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION)); parseFileBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(1)).emit(eq(NOTIFICATION_STREAM_NAME), any(Tuple.class), captor.capture()); Values values = captor.getValue(); assertNotNull(values); Map<String, String> valueMap = (Map) values.get(2); assertNotNull(valueMap); assertEquals(4, valueMap.size()); assertTrue(valueMap.get("additionalInfo").contains("Error while reading and parsing the EDM file")); assertEquals(RecordState.ERROR.toString(), valueMap.get("state")); assertNull(valueMap.get(PluginParameterKeys.RESOURCE_LINKS_COUNT)); verify(outputCollector, Mockito.times(0)).emit(anyList()); } @Test public void shouldEmitErrorWhenGettingResourceLinksFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/broken.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); parseFileBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(1)).emit(eq(NOTIFICATION_STREAM_NAME), any(Tuple.class), captor.capture()); Values values = captor.getValue(); assertNotNull(values); Map<String, String> valueMap = (Map) values.get(2); assertNotNull(valueMap); assertEquals(4, valueMap.size()); assertTrue(valueMap.get("additionalInfo").contains("Error while reading and parsing the EDM file")); assertEquals(RecordState.ERROR.toString(), valueMap.get("state")); assertNull(valueMap.get(PluginParameterKeys.RESOURCE_LINKS_COUNT)); verify(outputCollector, Mockito.times(0)).emit(anyList()); } }
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); }
@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); }
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); }
@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)); }
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); }
@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); }
TaskExecutor implements Callable<Void> { @Override public Void call() { try { execute(); } catch (Exception e) { taskStatusUpdater.setTaskDropped(dpsTask.getTaskId(), "The task was dropped because of " + e.getMessage() + ". The full exception is" + Throwables.getStackTraceAsString(e)); } return null; } TaskExecutor(SpoutOutputCollector collector, TaskStatusChecker taskStatusChecker, TaskStatusUpdater taskStatusUpdater, ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls, String mcsClientURL, String stream, DpsTask dpsTask); @Override Void call(); }
@Test public void shouldEmitTheFilesWhenNoRevisionIsSpecified() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(dataSets, prepareStormTaskTupleParameters()); Representation representation = testHelper.prepareRepresentationWithMultipleFiles(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date(), 2); when(dataSetServiceClient.getRepresentationIterator(eq("testDataProvider"), eq("dataSet"))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); when(fileServiceClient.getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName"))).thenReturn(new URI(FILE_URL)).thenReturn(new URI(FILE_URL)); ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls = new ArrayBlockingQueue<>(QUEUE_MAX_SIZE); TaskExecutor taskExecutor = new TaskExecutor(collector, taskStatusChecker, cassandraTaskInfoDAO, tuplesWithFileUrls, anyString(), DATASET_URLS.name(), dpsTask); taskExecutor.call(); assertEquals(tuplesWithFileUrls.size(), 2); } @Test public void shouldFailWhenReadFileThrowMCSExceptionWhenNoRevisionIsSpecified() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(dataSets, prepareStormTaskTupleParameters()); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date()); when(dataSetServiceClient.getRepresentationIterator(eq("testDataProvider"), eq("dataSet"))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); doThrow(MCSException.class).when(fileServiceClient).getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName")); ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls = new ArrayBlockingQueue<>(QUEUE_MAX_SIZE); TaskExecutor taskExecutor = new TaskExecutor(collector, taskStatusChecker, cassandraTaskInfoDAO, tuplesWithFileUrls, anyString(), DATASET_URLS.name(), dpsTask); taskExecutor.call(); verify(collector, times(0)).emit(anyListOf(Object.class)); verify(fileServiceClient, times(1)).getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName")); verify(collector, times(1)).emit(eq(AbstractDpsBolt.NOTIFICATION_STREAM_NAME), anyListOf(Object.class)); } @Test public void shouldFailPerEachFileWhenReadFileThrowDriverExceptionWhenNoRevisionIsSpecified() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(dataSets, prepareStormTaskTupleParameters()); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date()); when(dataSetServiceClient.getRepresentationIterator(eq("testDataProvider"), eq("dataSet"))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); doThrow(DriverException.class).when(fileServiceClient).getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName")); ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls = new ArrayBlockingQueue<>(QUEUE_MAX_SIZE); TaskExecutor taskExecutor = new TaskExecutor(collector, taskStatusChecker, cassandraTaskInfoDAO, tuplesWithFileUrls, anyString(), DATASET_URLS.name(), dpsTask); taskExecutor.call(); verify(collector, times(0)).emit(anyListOf(Object.class)); verify(fileServiceClient, times(1)).getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName")); verify(collector, times(1)).emit(eq(AbstractDpsBolt.NOTIFICATION_STREAM_NAME), anyListOf(Object.class)); } @Test public void shouldStopEmittingFilesWhenTaskIsKilled() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false, false, true); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(dataSets, prepareStormTaskTupleParameters()); Representation representation = testHelper.prepareRepresentationWithMultipleFiles(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date(), 2); when(dataSetServiceClient.getRepresentationIterator(eq("testDataProvider"), eq("dataSet"))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); when(fileServiceClient.getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName"))).thenReturn(new URI(FILE_URL)).thenReturn(new URI(FILE_URL)); ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls = new ArrayBlockingQueue<>(QUEUE_MAX_SIZE); TaskExecutor taskExecutor = new TaskExecutor(collector, taskStatusChecker, cassandraTaskInfoDAO, tuplesWithFileUrls, anyString(), DATASET_URLS.name(), dpsTask); taskExecutor.call(); assertEquals(tuplesWithFileUrls.size(), 1); } @Test public void shouldNotEmitAnyFilesWhenTaskIsKilledBeforeIteratingRepresentation() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(true); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(dataSets, prepareStormTaskTupleParameters()); Representation representation = testHelper.prepareRepresentationWithMultipleFiles(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date(), 2); when(dataSetServiceClient.getRepresentationIterator(eq("testDataProvider"), eq("dataSet"))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true, false); when(representationIterator.next()).thenReturn(representation); when(fileServiceClient.getFileUri(eq(SOURCE + CLOUD_ID), eq(SOURCE + REPRESENTATION_NAME), eq(SOURCE + VERSION), eq("fileName"))).thenReturn(new URI(FILE_URL)).thenReturn(new URI(FILE_URL)); ArrayBlockingQueue<StormTaskTuple> tuplesWithFileUrls = new ArrayBlockingQueue<>(QUEUE_MAX_SIZE); TaskExecutor taskExecutor = new TaskExecutor(collector, taskStatusChecker, cassandraTaskInfoDAO, tuplesWithFileUrls, anyString(), DATASET_URLS.name(), dpsTask); taskExecutor.call(); assertEquals(tuplesWithFileUrls.size(), 0); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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()); }
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); }
@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); }
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; }
@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); }
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); }
@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)); }
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); }
@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); }
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); }
@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); }
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); }
@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(); }
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); }
@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()); }
NotificationBolt extends BaseRichBolt { @Override public void execute(Tuple tuple) { try { NotificationTuple notificationTuple = NotificationTuple .fromStormTuple(tuple); NotificationCache nCache = cache.get(notificationTuple.getTaskId()); if (nCache == null) { nCache = new NotificationCache(notificationTuple.getTaskId()); cache.put(notificationTuple.getTaskId(), nCache); } storeTaskDetails(notificationTuple, nCache); } catch (NoHostAvailableException | QueryExecutionException ex) { LOGGER.error("Cannot store notification to Cassandra because: {}", ex.getMessage()); } catch (Exception ex) { LOGGER.error("Problem with store notification because: {}", ex.getMessage(), ex); } finally { outputCollector.ack(tuple); } } NotificationBolt(String hosts, int port, String keyspaceName, String userName, String password); @Override void execute(Tuple tuple); @Override void prepare(Map stormConf, TopologyContext tc, OutputCollector outputCollector); @Override void declareOutputFields(OutputFieldsDeclarer ofd); void clearCache(); }
@Test public void testUpdateBasicInfoStateWithStartDateAndInfo() throws Exception { long taskId = 1; int containsElements = 1; int expectedSize = 1; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; Date startTime = new Date(); TaskInfo expectedTaskInfo = createTaskInfo(taskId, containsElements, topologyName, taskState, taskInfo, null, startTime, null); taskInfoDAO.insert(taskId, topologyName, expectedSize, containsElements, taskState.toString(), taskInfo, null, startTime, null, 0, null); final Tuple tuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, startTime)); testedBolt.execute(tuple); TaskInfo result = taskInfoDAO.findById(taskId).get(); assertThat(result, notNullValue()); assertThat(result, is(expectedTaskInfo)); } @Test public void testUpdateBasicInfoStateWithFinishDateAndInfo() throws Exception { long taskId = 1; int containsElements = 1; int expectedSize = 1; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; Date finishDate = new Date(); TaskInfo expectedTaskInfo = createTaskInfo(taskId, containsElements, topologyName, taskState, taskInfo, null, null, finishDate); taskInfoDAO.insert(taskId, topologyName, expectedSize, containsElements, taskState.toString(), taskInfo, null, null, finishDate, 0, null); final Tuple tuple = createTestTuple(NotificationTuple.prepareEndTask(taskId, taskInfo, taskState, finishDate)); testedBolt.execute(tuple); TaskInfo result = taskInfoDAO.findById(taskId).get(); assertThat(result, notNullValue()); assertThat(result, is(expectedTaskInfo)); } @Test public void verifyOnlyOneNotificationForRepeatedRecord() throws Exception { long taskId = 1; taskInfoDAO.insert(taskId, null, 10, 0, TaskState.CURRENTLY_PROCESSING.toString(), "", null, null, null, 0, null); Tuple tuple = createNotificationTuple(taskId, RecordState.SUCCESS); testedBolt.execute(tuple); testedBolt.execute(tuple); TaskInfo taskProgress = cassandraReportService.getTaskProgress(String.valueOf(taskId)); List<SubTaskInfo> notifications = cassandraReportService.getDetailedTaskReportBetweenChunks("" + taskId, 0, 100); assertThat(notifications, hasSize(1)); assertEquals(taskProgress.getProcessedElementCount(), 1); } @Test public void testSuccessfulNotificationFor101Tuples() throws Exception { long taskId = 1; int expectedSize = 101; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, expectedSize, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); TaskInfo beforeExecute = cassandraReportService.getTaskProgress(String.valueOf(taskId)); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); for (int i = 0; i < 98; i++) { testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); } Thread.sleep(5001); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); TaskInfo afterOneHundredExecutions = cassandraReportService.getTaskProgress(String.valueOf(taskId)); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); assertEquals(beforeExecute.getProcessedElementCount(), 0); assertThat(beforeExecute.getState(), is(TaskState.CURRENTLY_PROCESSING)); assertEquals(afterOneHundredExecutions.getProcessedElementCount(), 100); assertThat(afterOneHundredExecutions.getState(), is(TaskState.CURRENTLY_PROCESSING)); } @Test public void testSuccessfulProgressUpdateAfterBoltRecreate() throws Exception { long taskId = 1; int expectedSize =4; String topologyName = ""; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, expectedSize, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); createBolt(); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); Thread.sleep(5001); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); TaskInfo info = cassandraReportService.getTaskProgress(String.valueOf(taskId)); assertEquals(3, info.getProcessedElementCount()); assertEquals(TaskState.CURRENTLY_PROCESSING, info.getState()); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); info = cassandraReportService.getTaskProgress(String.valueOf(taskId)); assertEquals(expectedSize, info.getProcessedElementCount()); assertEquals(TaskState.PROCESSED, info.getState()); } @Test public void testValidNotificationAfterBoltRecreate() throws Exception { long taskId = 1; int expectedSize = 2; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, 2, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); createBolt(); testedBolt.execute(createNotificationTuple(taskId, RecordState.SUCCESS)); assertEquals(expectedSize,subtaskDAO.getProcessedFilesCount(taskId)); } @Test public void testValidErrorReportDataAfterBoltRecreate() throws Exception { long taskId = 1; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, 2, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); testedBolt.execute(createNotificationTuple(taskId, RecordState.ERROR, RESOURCE_1)); createBolt(); testedBolt.execute(createNotificationTuple(taskId, RecordState.ERROR, RESOURCE_2)); assertEquals(2,subtaskDAO.getProcessedFilesCount(taskId)); TaskErrorsInfo errorReport = cassandraReportService.getGeneralTaskErrorReport("" + taskId, 100); assertEquals(1 ,errorReport.getErrors().size()); assertEquals(2 ,errorReport.getErrors().get(0).getOccurrences()); TaskErrorsInfo specificReport = cassandraReportService.getSpecificTaskErrorReport("" + taskId, errorReport.getErrors().get(0).getErrorType(), 100); assertEquals(1,specificReport.getErrors().size()); TaskErrorInfo specificReportErrorInfo = specificReport.getErrors().get(0); assertEquals("text",specificReportErrorInfo.getMessage()); assertEquals(2,specificReportErrorInfo.getErrorDetails().size()); assertEquals(RESOURCE_1, specificReportErrorInfo.getErrorDetails().get(0).getIdentifier()); assertEquals(RESOURCE_2, specificReportErrorInfo.getErrorDetails().get(1).getIdentifier()); } @Test public void testNotificationProgressPercentage() throws Exception { CassandraReportService cassandraReportService = new CassandraReportService(HOST, PORT, KEYSPACE, "", ""); long taskId = 1; int expectedSize = 330; int errors = 5; int middle = (int) (Math.random() * expectedSize); String topologyName = ""; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, expectedSize, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); List<Tuple> tuples = prepareTuples(taskId, expectedSize, errors); TaskInfo beforeExecute = cassandraReportService.getTaskProgress(String.valueOf(taskId)); TaskInfo middleExecute = null; for (int i = 0; i < tuples.size(); i++) { if(i == middle - 1){ Thread.sleep(5001); testedBolt.execute(tuples.get(i)); middleExecute = cassandraReportService.getTaskProgress(String.valueOf(taskId)); }else{ testedBolt.execute(tuples.get(i)); } } TaskInfo afterExecute = cassandraReportService.getTaskProgress(String.valueOf(taskId)); assertEquals(beforeExecute.getProcessedElementCount(), 0); assertThat(beforeExecute.getState(), is(TaskState.CURRENTLY_PROCESSING)); assertEquals(beforeExecute.getProcessedPercentage(), 0); if (middleExecute != null) { assertEquals(middleExecute.getProcessedElementCount(), (middle)); assertThat(middleExecute.getState(), is(TaskState.CURRENTLY_PROCESSING)); assertEquals(middleExecute.getProcessedPercentage(), 100 * middle / expectedSize); } int totalProcessed = expectedSize; assertEquals(afterExecute.getProcessedElementCount(), totalProcessed+(expectedSize - totalProcessed) ); assertThat(afterExecute.getState(), is(TaskState.PROCESSED)); assertEquals(afterExecute.getProcessedPercentage(), 100 * ((afterExecute.getProcessedElementCount() / (totalProcessed+(expectedSize - totalProcessed))))); } @Test public void testNotificationForErrors() throws Exception { CassandraReportService cassandraReportService = new CassandraReportService(HOST, PORT, KEYSPACE, "", ""); long taskId = 1; int expectedSize = 20; int errors = 9; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; taskInfoDAO.insert(taskId, topologyName, expectedSize, 0, taskState.toString(), taskInfo, null, null, null, 0, null); final Tuple setUpTuple = createTestTuple(NotificationTuple.prepareUpdateTask(taskId, taskInfo, taskState, null)); testedBolt.execute(setUpTuple); List<Tuple> tuples = prepareTuples(taskId, expectedSize, errors); TaskInfo beforeExecute = cassandraReportService.getTaskProgress(String.valueOf(taskId)); for (Tuple tuple : tuples) { testedBolt.execute(tuple); } TaskErrorsInfo errorsInfo = cassandraReportService.getGeneralTaskErrorReport(String.valueOf(taskId), 0); assertEquals(beforeExecute.getProcessedElementCount(), 0); assertThat(beforeExecute.getState(), is(TaskState.CURRENTLY_PROCESSING)); assertEquals(beforeExecute.getErrors(), 0); assertEquals(errorsInfo.getErrors().size(), 1); assertEquals(errorsInfo.getErrors().get(0).getOccurrences(), errors); }
MCSTaskSubmiter { public void execute(SubmitTaskParameters submitParameters) { DpsTask task = submitParameters.getTask(); try { LOGGER.info("Sending task id={} to topology {} by kafka topic {}. Parameters:\n{}", task.getTaskId(), submitParameters.getTopologyName(), submitParameters.getTopicName(), submitParameters); checkIfTaskIsKilled(task); logProgress(submitParameters, 0); int expectedSize; if (taskContainsFileUrls(task)) { expectedSize = executeForFilesList(submitParameters); } else { expectedSize = executeForDatasetList(submitParameters); } checkIfTaskIsKilled(task); if (expectedSize != 0) { taskStatusUpdater.updateStatusExpectedSize(task.getTaskId(), TaskState.QUEUED.toString(), expectedSize); LOGGER.info("Submitting {} records of task id={} to Kafka succeeded.", expectedSize, task.getTaskId()); } else { taskStatusUpdater.setTaskDropped(task.getTaskId(), "The task was dropped because it is empty"); LOGGER.warn("The task id={} was dropped because it is empty.", task.getTaskId()); } } catch (SubmitingTaskWasKilled e) { LOGGER.warn(e.getMessage(), e); } catch (Exception e) { LOGGER.error("MCSTaskSubmiter error for taskId={}", task.getTaskId(), e); taskStatusUpdater.setTaskDropped(task.getTaskId(), "The task was dropped because " + e.getMessage()); } } MCSTaskSubmiter(TaskStatusChecker taskStatusChecker, TaskStatusUpdater taskStatusUpdater, RecordExecutionSubmitService recordSubmitService, ProcessedRecordsDAO processedRecordsDAO, String mcsClientURL); void execute(SubmitTaskParameters submitParameters); }
@Test public void executeMcsBasedTask_taskIsNotKilled_verifyUpdateTaskInfoInCassandra() { task.addDataEntry(InputDataType.FILE_URLS, Collections.singletonList(FILE_URL_1)); submiter.execute(submitParameters); verify(taskStatusUpdater).updateStatusExpectedSize(eq(TASK_ID), eq(String.valueOf(TaskState.QUEUED)),eq(1)); } @Test public void executeMcsBasedTask_oneFileUrl() { task.addDataEntry(InputDataType.FILE_URLS, Collections.singletonList(FILE_URL_1)); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1); } @Test public void executeMcsBasedTask_threeFileUrls() { task.addDataEntry(InputDataType.FILE_URLS, Arrays.asList(FILE_URL_1,FILE_URL_2,FILE_URL_3)); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1,FILE_URL_2,FILE_URL_3); } @Test public void executeMcsBasedTask_3000FileUrls() { List<String> fileUrls=new ArrayList<>(); for(int i =0;i<3000;i++) { fileUrls.add(FILE_URL_1); } task.addDataEntry(InputDataType.FILE_URLS, fileUrls); submiter.execute(submitParameters); verifyValidTaskSent(fileUrls.toArray(new String[0])); } @Test public void executeMcsBasedTask_oneDatasetWithOneFile() { task.addDataEntry(InputDataType.DATASET_URLS, Collections.singletonList(DATASET_URL_1)); when(dataSetServiceClient.getRepresentationIterator(eq(DATASET_PROVIDER_1),eq(DATASET_ID_1))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true,false); when(representationIterator.next()).thenReturn(REPRESENTATION_1); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1); } @Test public void executeMcsBasedTask_oneDatasetWithThreeFiles() { task.addDataEntry(InputDataType.DATASET_URLS, Collections.singletonList(DATASET_URL_1)); when(dataSetServiceClient.getRepresentationIterator(eq(DATASET_PROVIDER_1),eq(DATASET_ID_1))).thenReturn(representationIterator); when(representationIterator.hasNext()).thenReturn(true,true,true,false); when(representationIterator.next()).thenReturn(REPRESENTATION_1); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1,FILE_URL_1,FILE_URL_1); } @Test public void executeMcsBasedTask_oneLastRevisionWithOneFile() throws MCSException { task.addDataEntry(InputDataType.DATASET_URLS, Collections.singletonList(DATASET_URL_1)); task.addParameter(PluginParameterKeys.REVISION_NAME, REVISION_NAME); task.addParameter(PluginParameterKeys.REVISION_PROVIDER,REVISION_PROVIDER_1); task.addParameter(PluginParameterKeys.REPRESENTATION_NAME, REPRESENTATION_NAME); when(dataSetServiceClient.getLatestDataSetCloudIdByRepresentationAndRevisionChunk(eq(DATASET_ID_1) , eq(DATASET_PROVIDER_1), eq(REVISION_PROVIDER_1), eq(REVISION_NAME), eq(REPRESENTATION_NAME), eq(false), eq(null))).thenReturn(latestDataChunk); when(latestDataChunk.getResults()).thenReturn(latestDataList); latestDataList.add(new CloudIdAndTimestampResponse(CLOUD_ID1, FILE_CREATION_DATE_1)); when(recordServiceClient.getRepresentationsByRevision(eq(CLOUD_ID1),eq(REPRESENTATION_NAME),eq(REVISION_NAME),eq(REVISION_PROVIDER_1),anyString())).thenReturn(Collections.singletonList(REPRESENTATION_1)); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1); } @Test public void executeMcsBasedTask_lastRevisionsForTwoObject_verifyTwoRecordsSentToKafka() throws MCSException { prepareInvocationForLastRevisionOfTwoObjects(); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1,FILE_URL_1); } @Test public void executeMcsBasedTask_lastRevisionsForTwoObjectAndLimitTo1_verifyOnlyOneRecordSentToKafka() throws MCSException { prepareInvocationForLastRevisionOfTwoObjects(); task.addParameter(PluginParameterKeys.SAMPLE_SIZE,"1"); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1); } @Test public void executeMcsBasedTask_lastRevisionsForThreeObjectsInThreeChunks_verifyThreeRecordsSentToKafka() throws MCSException { prepareInvocationForLastRevisionForThreeObjectsInThreeChunks(); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1,FILE_URL_1,FILE_URL_1); } @Test public void executeMcsBasedTask_lastRevisionsForThreeObjectsInThreeChunks_verifyOnlyTwoRecordSentToKafka() throws MCSException { prepareInvocationForLastRevisionForThreeObjectsInThreeChunks(); task.addParameter(PluginParameterKeys.SAMPLE_SIZE,"2"); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1,FILE_URL_1); } @Test public void executeMcsBasedTask_oneRevisionForGivenTimestampWithOneFile() throws MCSException { task.addDataEntry(InputDataType.DATASET_URLS, Collections.singletonList(DATASET_URL_1)); task.addParameter(PluginParameterKeys.REVISION_NAME, REVISION_NAME); task.addParameter(PluginParameterKeys.REVISION_PROVIDER,REVISION_PROVIDER_1); task.addParameter(PluginParameterKeys.REVISION_TIMESTAMP,FILE_CREATION_DATE_STRING_1); task.addParameter(PluginParameterKeys.REPRESENTATION_NAME, REPRESENTATION_NAME); when(dataSetServiceClient.getDataSetRevisionsChunk( eq(DATASET_PROVIDER_1), eq(DATASET_ID_1), eq(REPRESENTATION_NAME), eq(REVISION_NAME),eq(REVISION_PROVIDER_1),eq(FILE_CREATION_DATE_STRING_1), eq(null), eq(null))).thenReturn(dataChunk); when(dataChunk.getResults()).thenReturn(dataList); dataList.add(new CloudTagsResponse(CLOUD_ID1,false,false,false)); when(recordServiceClient.getRepresentationsByRevision(eq(CLOUD_ID1),eq(REPRESENTATION_NAME),eq(REVISION_NAME),eq(REVISION_PROVIDER_1),anyString())).thenReturn(Collections.singletonList(REPRESENTATION_1)); submiter.execute(submitParameters); verifyValidTaskSent(FILE_URL_1); }
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); }
@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); }
TopologyTasksResource { @GetMapping(value = "{taskId}/progress", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") public TaskInfo getTaskProgress( @PathVariable final String topologyName, @PathVariable final String taskId) throws AccessDeniedOrObjectDoesNotExistException, AccessDeniedOrTopologyDoesNotExistException { taskSubmissionValidator.assertContainTopology(topologyName); reportService.checkIfTaskExists(taskId, topologyName); return reportService.getTaskProgress(taskId); } @GetMapping(value = "{taskId}/progress", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") TaskInfo getTaskProgress( @PathVariable final String topologyName, @PathVariable final String taskId); @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#topologyName,'" + TOPOLOGY_PREFIX + "', write)") ResponseEntity<Void> submitTask( final HttpServletRequest request, @RequestBody final DpsTask task, @PathVariable final String topologyName, @RequestHeader("Authorization") final String authorizationHeader ); @PostMapping(path = "{taskId}/restart", consumes = {MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#topologyName,'" + TOPOLOGY_PREFIX + "', write)") ResponseEntity<Void> restartTask( final HttpServletRequest request, @PathVariable final long taskId, @PathVariable final String topologyName, @RequestHeader("Authorization") final String authorizationHeader ); @PostMapping(path = "{taskId}/cleaner", consumes = {MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#topologyName,'" + TOPOLOGY_PREFIX + "', write)") ResponseEntity<Void> cleanIndexingDataSet( @PathVariable final String topologyName, @PathVariable final String taskId, @RequestBody final DataSetCleanerParameters cleanerParameters ); @PostMapping(path = "{taskId}/permit") @PreAuthorize("hasRole('ROLE_ADMIN')") @ReturnType("java.lang.Void") ResponseEntity<Void> grantPermissions( @PathVariable String topologyName, @PathVariable String taskId, @RequestParam String username); @PostMapping(path = "{taskId}/kill") @PreAuthorize("hasRole('ROLE_ADMIN') OR hasPermission(#taskId,'" + TASK_PREFIX + "', write)") ResponseEntity<String> killTask( @PathVariable String topologyName, @PathVariable String taskId, @RequestParam(defaultValue = "Dropped by the user") String info); static final String TASK_PREFIX; }
@Test public void shouldGetProgressReport() throws Exception { TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, EMPTY_STRING, 100, 100, 10, 50, new Date(), new Date(), new Date()); when(reportService.getTaskProgress(eq(Long.toString(TASK_ID)))).thenReturn(taskInfo); when(topologyManager.containsTopology(TOPOLOGY_NAME)).thenReturn(true); ResultActions response = mockMvc.perform(get(PROGRESS_REPORT_WEB_TARGET, TOPOLOGY_NAME, TASK_ID)); TaskInfo resultedTaskInfo = new ObjectMapper().readValue(response.andReturn().getResponse().getContentAsString(),TaskInfo.class); assertThat(taskInfo, is(resultedTaskInfo)); } @Test public void shouldThrowExceptionIfTaskIdWasNotFound() throws Exception { when(reportService.getTaskProgress(eq(Long.toString(TASK_ID)))).thenThrow(AccessDeniedOrObjectDoesNotExistException.class); when(topologyManager.containsTopology(TOPOLOGY_NAME)).thenReturn(true); ResultActions response = mockMvc.perform( get(PROGRESS_REPORT_WEB_TARGET, TOPOLOGY_NAME, TASK_ID) ); response.andExpect(status().isMethodNotAllowed()); }
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; }
@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()); }
TaskSubmitterFactory { public TaskSubmitter provideTaskSubmitter(SubmitTaskParameters parameters) { switch (parameters.getTopologyName()) { case TopologiesNames.OAI_TOPOLOGY: return oaiTopologyTaskSubmitter; case TopologiesNames.HTTP_TOPOLOGY: return httpTopologyTaskSubmitter; case TopologiesNames.ENRICHMENT_TOPOLOGY: case TopologiesNames.INDEXING_TOPOLOGY: case TopologiesNames.LINKCHECK_TOPOLOGY: case TopologiesNames.MEDIA_TOPOLOGY: case TopologiesNames.NORMALIZATION_TOPOLOGY: case TopologiesNames.VALIDATION_TOPOLOGY: case TopologiesNames.XSLT_TOPOLOGY: return otherTopologiesTaskSubmitter; case TopologiesNames.DEPUBLICATION_TOPOLOGY: return depublicationTaskSubmitter; default: throw new IllegalArgumentException("Unable to find the TaskSubmitter for the given topology name: " + parameters.getTopologyName()); } } TaskSubmitterFactory(OaiTopologyTaskSubmitter oaiTopologyTaskSubmitter, HttpTopologyTaskSubmitter httpTopologyTaskSubmitter, OtherTopologiesTaskSubmitter otherTopologiesTaskSubmitter, TaskSubmitter depublicationTaskSubmitter); TaskSubmitter provideTaskSubmitter(SubmitTaskParameters parameters); }
@Test public void shouldProvideSubmitterForDepublicationTopology() { TaskSubmitter taskSubmitter = new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ).provideTaskSubmitter( SubmitTaskParameters.builder().topologyName(TopologiesNames.DEPUBLICATION_TOPOLOGY).build()); assertTrue(taskSubmitter instanceof DepublicationTaskSubmitter); } @Test public void shouldProvideSubmitterForOaiTopology() { TaskSubmitter taskSubmitter = new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ).provideTaskSubmitter( SubmitTaskParameters.builder().topologyName(TopologiesNames.OAI_TOPOLOGY).build()); assertTrue(taskSubmitter instanceof OaiTopologyTaskSubmitter); } @Test public void shouldProvideSubmitterForHttpTopology() { TaskSubmitter taskSubmitter = new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ).provideTaskSubmitter( SubmitTaskParameters.builder().topologyName(TopologiesNames.HTTP_TOPOLOGY).build()); assertTrue(taskSubmitter instanceof HttpTopologyTaskSubmitter); } @Test public void shouldProvideSubmitterForOtherTopologies() { TaskSubmitterFactory taskSubmitterFactory = new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.VALIDATION_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.INDEXING_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.ENRICHMENT_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.NORMALIZATION_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.LINKCHECK_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.MEDIA_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); assertTrue(taskSubmitterFactory.provideTaskSubmitter( SubmitTaskParameters .builder() .topologyName(TopologiesNames.XSLT_TOPOLOGY) .build() ) instanceof OtherTopologiesTaskSubmitter); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForUnknownTopologyName() { new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ).provideTaskSubmitter( SubmitTaskParameters.builder().topologyName("Unknown topology name").build()); }
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; }
@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)); }
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(); }
@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)); }
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); }
@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); }
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(); }
@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()); }
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; }
@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); }
OaiPmhFilesCounter extends FilesCounter { @Override public int getFilesCount(DpsTask task) throws TaskSubmissionException { OAIPMHHarvestingDetails harvestingDetails = task.getHarvestingDetails(); if (harvestingDetails != null) { if (specified(harvestingDetails.getExcludedSets()) || specified(harvestingDetails.getExcludedSchemas())) { LOGGER.info("Cannot count completeListSize for taskId= {} . Excluded sets or schemas are not supported", task.getTaskId()); return DEFAULT_LIST_SIZE; } String repositoryUrl = getRepositoryUrl(task.getInputData()); if (repositoryUrl != null) { ListIdentifiersParameters params = new ListIdentifiersParameters() .withFrom(harvestingDetails.getDateFrom()) .withUntil(harvestingDetails.getDateUntil()); Set<String> schemas = harvestingDetails.getSchemas(); Set<String> sets = harvestingDetails.getSets(); if (specified(sets)) { if (sets.size() == 1) { params.withSetSpec(sets.iterator().next()); } else { LOGGER.info("Cannot count completeListSize for taskId= {} . Specifying multiple sets is not supported ", task.getTaskId()); return DEFAULT_LIST_SIZE; } } try { return getListSizeForSchemasAndSet(repositoryUrl, params, schemas); } catch (OAIResponseParseException e) { LOGGER.info("Cannot count completeListSize for taskId= {}", task.getTaskId(), e); return DEFAULT_LIST_SIZE; } catch (OAIRequestException e) { String logMessage = "Cannot complete the request for the following repository URL " + repositoryUrl; LOGGER.info(logMessage, e); throw new TaskSubmissionException(logMessage + " Because: " + e.getMessage(), e); } } else { throw new TaskSubmissionException("The task was dropped because the repositoryUrl can not be null"); } } else return DEFAULT_LIST_SIZE; } @Override int getFilesCount(DpsTask task); static final String COMPLETE_LIST_SIZE; }
@Test public void shouldGetCorrectCompleteListSize() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(2932, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenEmptyCompleteListSize() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiersNoCompleteListSize.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null,null ); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenIncorrectCompleteListSize() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiersIncorrectCompleteListSize.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhen200ReturnedButErrorInResponse() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiersIncorrectMetadataPrefix.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenNoResumptionToken() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiersNoResumptionToken.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test(expected = TaskSubmissionException.class) public void shouldRetry10TimesAndFail() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")).inScenario("Retry and fail scenario") .willReturn(response404())); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); counter.getFilesCount(task); } @Test public void shouldRetryAndReturnACorrectValue() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")).inScenario("Retry and success scenario").whenScenarioStateIs(STARTED).willSetStateTo("one time requested") .willReturn(response404())); stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")).inScenario("Retry and success scenario").whenScenarioStateIs("one time requested") .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(2932, counter.getFilesCount(task)); } @Test public void shouldReturnCorrectSumWhenSchemasAndSetListed() throws Exception { String schema1 = "schema1"; String schema2 = "schema2"; String set1 = "set1"; stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers&set=" + set1 + "&metadataPrefix=" + schema1)) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers&set=" + set1 + "&metadataPrefix=" + schema2)) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers2.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(Sets.newHashSet(schema1, schema2), Sets.newHashSet(set1), null, null, null); DpsTask task = getDpsTask(details); assertEquals(2934, counter.getFilesCount(task)); } @Test public void shouldReturnCorrectSumWhenSchemasAndNoSetsListed() throws Exception { String schema1 = "schema1"; String schema2 = "schema2"; stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers&metadataPrefix=" + schema1)) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers&metadataPrefix=" + schema2)) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers2.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(Sets.newHashSet(schema1, schema2), null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(2934, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenMultipleSetsSpecified() throws Exception { OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, Sets.newHashSet("a", "b", "c"), null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnCountForSchemaWhenEmptySetsProvided() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, new HashSet<String>(), null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(2932, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenSetsExcluded() throws Exception { OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, Sets.newHashSet("a", "b", "c"), null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWheHarvestingDetailsIsNotProvided() throws Exception { OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); DpsTask task = getDpsTask(null); assertEquals(-1, counter.getFilesCount(task)); } @Test public void shouldReturnMinusOneWhenSchemasExcluded() throws Exception { OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, Sets.newHashSet("a", "b", "c"), null, null, null, null, null); DpsTask task = getDpsTask(details); assertEquals(-1, counter.getFilesCount(task)); } @Test(expected = TaskSubmissionException.class) public void shouldThrowTaskSubmissionExceptionWhenURLsIsNull() throws Exception { OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingDetails(null, null, null, null, null, null, null); DpsTask task = getDpsTaskNoEndpoint(details); counter.getFilesCount(task); }
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); }
@Test public void TestValidator() { Validator validator = ValidatorFactory.getValidator(ValidatorType.KEYSPACE); assertTrue(validator instanceof KeyspaceValidator); validator = ValidatorFactory.getValidator(ValidatorType.TABLE); assertTrue(validator instanceof TableValidator); }
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); }
@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); }
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); }
@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(); }
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); }
@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)); }
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(); }
@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); }
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(); }
@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")); } }
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(); }
@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)); }
DpsClient { public String killTask(final String topologyName, final long taskId, String info) throws DpsException { Response response = null; try { WebTarget webTarget = client.target(dpsUrl).path(KILL_TASK_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName).resolveTemplate(TASK_ID, taskId); if (info != null) { webTarget = webTarget.queryParam("info", info); } response = webTarget.request().post(null); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(String.class); } else { LOGGER.error("Task Can't be killed"); 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(); }
@Test @Betamax(tape = "DPSClient/killTaskTest") public final void shouldKillTask() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); String responseMessage = dpsClient.killTask(TOPOLOGY_NAME, TASK_ID, null); assertEquals(responseMessage, "The task was killed because of Dropped by the user"); } @Test @Betamax(tape = "DPSClient/killTaskTestWithSpecificInfo") public final void shouldKillTaskWithSpecificInfo() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); String responseMessage = dpsClient.killTask(TOPOLOGY_NAME, TASK_ID, "Aggregator-choice"); assertEquals(responseMessage, "The task was killed because of Aggregator-choice"); } @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "DPSClient/shouldThrowExceptionWhenKillingNonExistingTaskTest") public final void shouldThrowExceptionWhenKillingNonExistingTaskTest() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); long nonExistedTaskId = 1111l; dpsClient.killTask(TOPOLOGY_NAME, nonExistedTaskId, null); } @Test(expected = AccessDeniedOrTopologyDoesNotExistException.class) @Betamax(tape = "DPSClient/shouldThrowExceptionWhenKillingTaskForNonExistedTopologyTest") public final void shouldThrowExceptionWhenKillingTaskForNonExistedTopologyTest() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); dpsClient.killTask(NOT_DEFINED_TOPOLOGY_NAME, TASK_ID, null); }
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(); }
@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)); }
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(); }
@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)); }
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); }
@Test public void prepareBoundStatementForMatchingTargetTableTest() { assertThat(CassandraHelper.prepareBoundStatementForMatchingTargetTable(cassandraConnectionProvider, "table", primaryKeys), is(boundStatement)); }
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(); }
@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)); }
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(); }
@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()); }
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(); }
@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); }
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(); }
@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()); }
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); }
@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!")); } }
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); }
@Test public void getPrimaryKeysFromSourceTableTest() { ResultSet resultSet = mock(ResultSet.class); when(session.execute(boundStatement)).thenReturn(resultSet); assertThat(CassandraHelper.getPrimaryKeysFromSourceTable(cassandraConnectionProvider, "table", primaryKeys), is(resultSet)); }
XmlXPath { String xpathToString(XPathExpression expr) throws HarvesterException { try { return evaluateExpression(expr); } catch (XPathExpressionException e) { throw new HarvesterException("Cannot xpath XML!", e); } } XmlXPath(String input); }
@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))); }
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); }
@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); }
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; }
@Test public void should_successfully_getTopologyNames() { List<String> resultNameList = instance.getNames(); List<String> expectedNameList = convertStringToList(nameList); assertThat(resultNameList, is(equalTo(expectedNameList))); }
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; }
@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))); }
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); }
@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)); }
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); }
@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)); }
SimplifiedFileAccessResource { @GetMapping public ResponseEntity<StreamingResponseBody> getFile( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName) throws RepresentationNotExistsException, FileNotExistsException, RecordNotExistsException, ProviderNotExistsException, WrongContentRangeException { LOGGER.info("Reading file 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); final FileResource.ContentRange contentRange = new FileResource.ContentRange(-1L, -1L); Consumer<OutputStream> downloadingMethod = recordService.getContent(cloudId, representationName, representation.getVersion(), fileName, contentRange.getStart(), contentRange.getEnd()); ResponseEntity.BodyBuilder response = ResponseEntity .status(HttpStatus.OK) .location(requestedFile.getContentUri()); if (md5 != null) { response.eTag(md5); } if (fileMimeType != null) { response.contentType(fileMimeType); } return response.body(output -> downloadingMethod.accept(output)); } 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); }
@Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrownWhenProviderIdDoesNotExist() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException { fileAccessResource.getFile(null, NOT_EXISTING_PROVIDER_ID, NOT_EXISTING_LOCAL_ID, "repName", "fileName"); } @Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrownWhenLocalIdDoesNotExist() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException { fileAccessResource.getFile(null, EXISTING_PROVIDER_ID, NOT_EXISTING_LOCAL_ID, "repName", "fileName"); } @Test(expected = RepresentationNotExistsException.class) public void exceptionShouldBeThrownWhenRepresentationIsMissing() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException { fileAccessResource.getFile(null, EXISTING_PROVIDER_ID, EXISTING_LOCAL_ID, NOT_EXISTING_REPRESENTATION_NAME, "fileName"); } @Test(expected = RepresentationNotExistsException.class) public void exceptionShouldBeThrownWhenThereIsNoPersistentRepresentationInGivenRecord() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException { fileAccessResource.getFile(null, EXISTING_PROVIDER_ID, EXISTING_LOCAL_ID_FOR_RECORD_WITHOUT_PERSISTENT_REPRESENTATION, existingRepresentationName, "fileName"); } @Test public void fileShouldBeReadSuccessfully() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException, URISyntaxException { setupUriInfo(); ResponseEntity<?> response = fileAccessResource.getFile(URI_INFO, EXISTING_PROVIDER_ID, EXISTING_LOCAL_ID, existingRepresentationName, "fileWithoutReadRights"); Assert.assertEquals(200, response.getStatusCodeValue()); response.toString(); }
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); }
@Test public void shouldReturnTheExpectedPrimaryKeysSelectionCQL() { assertEquals(EXPECTED_PRIMARY_KEYS_SELECTION_STATEMENT, CQLBuilder.constructSelectPrimaryKeysFromSourceTable(SOURCE_TABLE, primaryKeys)); }
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); }
@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(); }
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; }
@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); }
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); }
@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); } }
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); }
@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); }
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); }
@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); }
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); }
@Test public void shouldReturnTheExpectedCountStatement() { assertEquals(EXPECTED_COUNT_STATEMENT, CQLBuilder.getMatchCountStatementFromTargetTable(SOURCE_TABLE, primaryKeys)); }
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); }
@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); }
RepresentationVersionResource { @PostMapping(value = REPRESENTATION_VERSION_COPY) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") public ResponseEntity<Void> copyRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String version) throws RepresentationNotExistsException { Representation representationCopy = recordService.copyRepresentation(cloudId, representationName, version); EnrichUriUtil.enrich(httpServletRequest, representationCopy); String copiedReprOwner = SpringUserUtils.getUsername(); if (copiedReprOwner != null) { ObjectIdentity versionIdentity = new ObjectIdentityImpl(REPRESENTATION_CLASS_NAME, cloudId + "/" + representationName + "/" + representationCopy.getVersion()); MutableAcl versionAcl = mutableAclService.createAcl(versionIdentity); versionAcl.insertAce(0, BasePermission.READ, new PrincipalSid(copiedReprOwner), true); versionAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid(copiedReprOwner), true); versionAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid(copiedReprOwner), true); versionAcl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(copiedReprOwner),true); mutableAclService.updateAcl(versionAcl); } return ResponseEntity.created(representationCopy.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); }
@Test public void testCopyRepresentation() throws Exception { when(recordService.copyRepresentation(globalId, schema, version)) .thenReturn(new Representation(representation)); mockMvc.perform(post(copyPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.LOCATION, URITools.getVersionUri(getBaseUri(), globalId, schema, version).toString())); verify(recordService, times(1)).copyRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); } @Test @Parameters(method = "errors") public void testCopyRepresentationReturns404IfRepresentationOrRecordOrVersionDoesNotExists(Throwable exception, String errorCode, int statusCode) throws Exception { when(recordService.copyRepresentation(globalId, schema, version)).thenThrow(exception); ResultActions response = mockMvc.perform(post(copyPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().is(statusCode)); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).copyRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); }
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); }
@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); }
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); }
@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); }
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); }
@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()); }
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(); }
@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(); }